]> git.saurik.com Git - apple/security.git/blobdiff - OSX/libsecurity_keychain/lib/SecKeychain.cpp
Security-59754.80.3.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / lib / SecKeychain.cpp
index d307e2bd1f3770e8e856795a80a796ed08495b1a..ca80c80b0a322530139cbda1a3f5b8a3217718f2 100644 (file)
 #include <security_cdsa_utilities/Schema.h>
 #include <security_cdsa_client/mdsclient.h>
 #include <pwd.h>
+#include <os/activity.h>
 #include <Security/AuthorizationTagsPriv.h>
 #include <Security/Authorization.h>
 #include "TokenLogin.h"
+#include "LegacyAPICounts.h"
+
+extern "C" {
+#include "ctkloginhelper.h"
+}
 
 OSStatus
 SecKeychainMDSInstall()
 {
-       BEGIN_SECAPI
+    BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainMDSInstall", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
 
        Security::MDSClient::Directory d;
        d.install();
@@ -64,6 +74,7 @@ SecKeychainGetTypeID(void)
 OSStatus
 SecKeychainGetVersion(UInt32 *returnVers)
 {
+    COUNTLEGACYAPI
     if (!returnVers)
                return errSecSuccess;
 
@@ -77,39 +88,24 @@ SecKeychainOpen(const char *pathName, SecKeychainRef *keychainRef)
 {
     BEGIN_SECAPI
 
-       RequiredParam(keychainRef)=globals().storageManager.make(pathName, false)->handle();
-
-       END_SECAPI
-}
-
-
-OSStatus
-SecKeychainOpenWithGuid(const CSSM_GUID *guid, uint32 subserviceId, uint32 subserviceType, const char* dbName,
-                                               const CSSM_NET_ADDRESS *dbLocation, SecKeychainRef *keychain)
-{
-    BEGIN_SECAPI
+          os_activity_t activity = os_activity_create("SecKeychainOpen", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
 
-       // range check parameters
-       RequiredParam (guid);
-       RequiredParam (dbName);
-       
-       // create a DLDbIdentifier that describes what should be opened
-    const CSSM_VERSION *version = NULL;
-    const CssmSubserviceUid ssuid(*guid, version, subserviceId, subserviceType);
-       DLDbIdentifier dLDbIdentifier(ssuid, dbName, dbLocation);
-       
-       // make a keychain from the supplied info
-       RequiredParam(keychain) = globals().storageManager.makeKeychain(dLDbIdentifier, false, false)->handle ();
+       RequiredParam(keychainRef)=globals().storageManager.make(pathName, false)->handle();
 
        END_SECAPI
 }
 
-
 OSStatus
 SecKeychainCreate(const char *pathName, UInt32 passwordLength, const void *password,
        Boolean promptUser, SecAccessRef initialAccess, SecKeychainRef *keychainRef)
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainCreate", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
     
     KCThrowParamErrIf_(!pathName);
        Keychain keychain = globals().storageManager.make(pathName, true, true);
@@ -135,6 +131,10 @@ SecKeychainDelete(SecKeychainRef keychainOrArray)
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainDelete", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        KCThrowIf_(!keychainOrArray, errSecInvalidKeychain);
        StorageManager::KeychainList keychains;
        globals().storageManager.optionalSearchList(keychainOrArray, keychains);
@@ -150,6 +150,10 @@ SecKeychainSetSettings(SecKeychainRef keychainRef, const SecKeychainSettings *ne
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetSettings", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        Keychain keychain = Keychain::optional(keychainRef);
        if (newSettings->version==SEC_KEYCHAIN_SETTINGS_VERS1)
        {
@@ -167,6 +171,10 @@ SecKeychainCopySettings(SecKeychainRef keychainRef, SecKeychainSettings *outSett
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopySettings", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        Keychain keychain = Keychain::optional(keychainRef);
        if (outSettings->version==SEC_KEYCHAIN_SETTINGS_VERS1)
        {
@@ -187,6 +195,10 @@ SecKeychainUnlock(SecKeychainRef keychainRef, UInt32 passwordLength, const void
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainUnlock", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        Keychain keychain = Keychain::optional(keychainRef);
 
        if (usePassword)
@@ -203,6 +215,10 @@ SecKeychainLock(SecKeychainRef     keychainRef)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainLock", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        Keychain keychain = Keychain::optional(keychainRef);
        keychain->lock();
 
@@ -215,6 +231,10 @@ SecKeychainLockAll(void)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainLockAll", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        globals().storageManager.lockAll();
 
        END_SECAPI
@@ -224,6 +244,10 @@ SecKeychainLockAll(void)
 OSStatus SecKeychainResetLogin(UInt32 passwordLength, const void* password, Boolean resetSearchList)
 {
        BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainResetLogin", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
         //
         // Get the current user (using fallback method if necessary)
         //
@@ -239,10 +263,12 @@ OSStatus SecKeychainResetLogin(UInt32 passwordLength, const void* password, Bool
             endpwent();
         }
         if ( userName.length() == 0 )  // did we ultimately get one?
+        {
             MacOSError::throwMe(errAuthorizationInternal);
+        }
 
         SecurityServer::ClientSession().resetKeyStorePassphrase(password ? CssmData(const_cast<void *>(password), passwordLength) : CssmData());
-
+        secwarning("SecKeychainResetLogin: reset AKS passphrase");
                if (password)
                {
                        // Clear the plist and move aside (rename) the existing login.keychain
@@ -261,11 +287,13 @@ OSStatus SecKeychainResetLogin(UInt32 passwordLength, const void* password, Bool
                        // (implicitly calls resetKeychain, login, and defaultKeychain)
                        globals().storageManager.makeLoginAuthUI(NULL, true);
                }
+        secwarning("SecKeychainResetLogin: reset osx keychain");
 
                // Post a "list changed" event after a reset, so apps can refresh their list.
                // Make sure we are not holding mLock when we post this event.
                KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent);
 
+
        END_SECAPI
 }
 
@@ -285,6 +313,10 @@ SecKeychainSetDefault(SecKeychainRef keychainRef)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetDefault", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        globals().storageManager.defaultKeychain(Keychain::optional(keychainRef));
 
        END_SECAPI
@@ -294,6 +326,10 @@ OSStatus SecKeychainCopySearchList(CFArrayRef *searchList)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopySearchList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(searchList);
        StorageManager &smr = globals().storageManager;
        StorageManager::KeychainList keychainList;
@@ -307,6 +343,10 @@ OSStatus SecKeychainSetSearchList(CFArrayRef searchList)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetSearchList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(searchList);
        StorageManager &smr = globals().storageManager;
        StorageManager::KeychainList keychainList;
@@ -320,6 +360,10 @@ OSStatus SecKeychainCopyDomainDefault(SecPreferencesDomain domain, SecKeychainRe
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopyDomainDefault", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(keychainRef)=globals().storageManager.defaultKeychain(domain)->handle();
 
        END_SECAPI
@@ -329,6 +373,10 @@ OSStatus SecKeychainSetDomainDefault(SecPreferencesDomain domain, SecKeychainRef
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetDomainDefault", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        globals().storageManager.defaultKeychain(domain, Keychain::optional(keychainRef));
 
        END_SECAPI
@@ -351,6 +399,10 @@ OSStatus SecKeychainSetDomainSearchList(SecPreferencesDomain domain, CFArrayRef
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetDomainSearchList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(searchList);
        StorageManager &smr = globals().storageManager;
        StorageManager::KeychainList keychainList;
@@ -364,6 +416,10 @@ OSStatus SecKeychainSetPreferenceDomain(SecPreferencesDomain domain)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainSetPreferenceDomain", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        globals().storageManager.domain(domain);
 
        END_SECAPI
@@ -372,6 +428,10 @@ OSStatus SecKeychainSetPreferenceDomain(SecPreferencesDomain domain)
 OSStatus SecKeychainGetPreferenceDomain(SecPreferencesDomain *domain)
 {
        BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainGetPreferenceDomain", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
        
        *domain = globals().storageManager.domain();
        
@@ -416,7 +476,7 @@ SecKeychainGetKeychainVersion(SecKeychainRef keychainRef, UInt32* version)
 {
     BEGIN_SECAPI
 
-    RequiredParam(version);
+          RequiredParam(version);
 
     *version = Keychain::optional(keychainRef)->database()->dbBlobVersion();
 
@@ -428,6 +488,10 @@ SecKeychainAttemptMigrationWithMasterKey(SecKeychainRef keychain, UInt32 version
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainAttemptMigrationWithMasterKey", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
     RequiredParam(masterKeyFilename);
     Keychain kc = Keychain::optional(keychain);
 
@@ -523,6 +587,10 @@ SecKeychainAddCallback(SecKeychainCallback callbackFunction, SecKeychainEventMas
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainAddCallback", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(callbackFunction);
        CCallbackMgr::AddCallback(callbackFunction,eventMask,userContext);
 
@@ -535,6 +603,10 @@ SecKeychainRemoveCallback(SecKeychainCallback callbackFunction)
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainRemoveCallback", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(callbackFunction);
        CCallbackMgr::RemoveCallback(callbackFunction);
 
@@ -546,6 +618,10 @@ SecKeychainAddInternetPassword(SecKeychainRef keychainRef, UInt32 serverNameLeng
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainAddInternetPassword", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        KCThrowParamErrIf_(passwordLength!=0 && passwordData==NULL);
        // @@@ Get real itemClass
        Item item(kSecInternetPasswordItemClass, 'aapl', passwordLength, passwordData, false);
@@ -605,6 +681,10 @@ SecKeychainFindInternetPassword(CFTypeRef keychainOrArray, UInt32 serverNameLeng
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainFindInternetPassword", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        StorageManager::KeychainList keychains;
        globals().storageManager.optionalSearchList(keychainOrArray, keychains);
        KCCursor cursor(keychains, kSecInternetPasswordItemClass, NULL);
@@ -681,6 +761,10 @@ SecKeychainAddGenericPassword(SecKeychainRef keychainRef, UInt32 serviceNameLeng
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainAddGenericPassword", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        KCThrowParamErrIf_(passwordLength!=0 && passwordData==NULL);
        // @@@ Get real itemClass
 
@@ -690,17 +774,7 @@ SecKeychainAddGenericPassword(SecKeychainRef keychainRef, UInt32 serviceNameLeng
        {
                CssmData service(const_cast<void *>(reinterpret_cast<const void *>(serviceName)), serviceNameLength);
                item->setAttribute(Schema::attributeInfo(kSecServiceItemAttr), service);
-               // use service name as default label (UNLESS the service is iTools and we have an account name [3787371])
-               const char *iTools = "iTools";
-               if (accountNameLength && serviceNameLength==strlen(iTools) && !memcmp(serviceName, iTools, serviceNameLength))
-               {
-                       CssmData account(const_cast<void *>(reinterpret_cast<const void *>(accountName)), accountNameLength);
-                       item->setAttribute(Schema::attributeInfo(kSecLabelItemAttr), account);
-               }
-               else
-               {
-                       item->setAttribute(Schema::attributeInfo(kSecLabelItemAttr), service);
-               }
+        item->setAttribute(Schema::attributeInfo(kSecLabelItemAttr), service);
        }
 
        if (accountName && accountNameLength)
@@ -737,6 +811,10 @@ SecKeychainFindGenericPassword(CFTypeRef keychainOrArray, UInt32 serviceNameLeng
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainFindGenericPassword", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        StorageManager::KeychainList keychains;
        globals().storageManager.optionalSearchList(keychainOrArray, keychains);
        KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL);
@@ -806,6 +884,10 @@ SecKeychainGetDLDBHandle(SecKeychainRef keychainRef, CSSM_DL_DB_HANDLE *dldbHand
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainGetDLDBHandle", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(dldbHandle);
        
        Keychain keychain = Keychain::optional(keychainRef);
@@ -814,6 +896,8 @@ SecKeychainGetDLDBHandle(SecKeychainRef keychainRef, CSSM_DL_DB_HANDLE *dldbHand
     END_SECAPI
 }
 
+static ModuleNexus<Mutex> gSecReturnedKeychainCSPsMutex;
+static ModuleNexus<std::set<CssmClient::CSP>> gSecReturnedKeychainCSPs;
 
 OSStatus
 SecKeychainGetCSPHandle(SecKeychainRef keychainRef, CSSM_CSP_HANDLE *cspHandle)
@@ -823,7 +907,15 @@ SecKeychainGetCSPHandle(SecKeychainRef keychainRef, CSSM_CSP_HANDLE *cspHandle)
        RequiredParam(cspHandle);
 
        Keychain keychain = Keychain::optional(keychainRef);
-       *cspHandle = keychain->csp()->handle();
+
+    // Once we vend this handle, we can no longer delete this CSP object via RAII (and thus call CSSM_ModuleDetach on the CSP).
+    // Keep a global pointer to it to force the CSP to stay live forever.
+    CssmClient::CSP returnedKeychainCSP = keychain->csp();
+    {
+        StLock<Mutex> _(gSecReturnedKeychainCSPsMutex());
+        gSecReturnedKeychainCSPs().insert(returnedKeychainCSP);
+    }
+       *cspHandle = returnedKeychainCSP->handle();
 
        END_SECAPI
 }
@@ -859,6 +951,10 @@ SecKeychainChangePassword(SecKeychainRef keychainRef, UInt32 oldPasswordLength,
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainChangePassword", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        Keychain keychain = Keychain::optional(keychainRef);
         keychain->changePassphrase (oldPasswordLength, oldPassword,  newPasswordLength, newPassword);
 
@@ -871,6 +967,10 @@ SecKeychainCopyLogin(SecKeychainRef *keychainRef)
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopyLogin", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(keychainRef)=globals().storageManager.loginKeychain()->handle();
 
     END_SECAPI
@@ -882,6 +982,10 @@ SecKeychainLogin(UInt32 nameLength, const void* name, UInt32 passwordLength, con
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainLogin", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        try
        {
                if (password) {
@@ -892,6 +996,7 @@ SecKeychainLogin(UInt32 nameLength, const void* name, UInt32 passwordLength, con
        }
        catch (CommonError &e)
        {
+        secnotice("KCLogin", "SecKeychainLogin failed: %d, password was%s supplied", (int)e.osStatus(), password?"":" not");
                if (e.osStatus() == CSSMERR_DL_OPERATION_AUTH_DENIED)
                {
                        return errSecAuthFailed;
@@ -901,13 +1006,22 @@ SecKeychainLogin(UInt32 nameLength, const void* name, UInt32 passwordLength, con
                        return e.osStatus();
                }
        }
-       
+
+    catch (...) {
+        __secapiresult=errSecInternalComponent;
+    }
+    secnotice("KCLogin", "SecKeychainLogin result: %d, password was%s supplied", (int)__secapiresult, password?"":" not");
+
     END_SECAPI
 }
 
 OSStatus SecKeychainStash()
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainStash", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
     
        try
        {
@@ -933,6 +1047,10 @@ SecKeychainLogout()
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainLogout", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        globals().storageManager.logout();
 
     END_SECAPI
@@ -952,7 +1070,8 @@ static Keychain make(const char *name)
 OSStatus SecKeychainMakeFromFullPath(const char *fullPathName, SecKeychainRef *keychainRef)
 {
     BEGIN_SECAPI
-        RequiredParam(fullPathName);
+
+       RequiredParam(fullPathName);
         RequiredParam(keychainRef)=make(fullPathName)->handle();
        END_SECAPI
 }
@@ -963,7 +1082,8 @@ OSStatus SecKeychainMakeFromFullPath(const char *fullPathName, SecKeychainRef *k
 OSStatus SecKeychainIsValid(SecKeychainRef keychainRef, Boolean* isValid)
 {
     BEGIN_SECAPI
-        *isValid = false;
+
+       *isValid = false;
         if (KeychainImpl::optional(keychainRef)->dlDbIdentifier().ssuid().guid() == gGuidAppleCSPDL)
             *isValid = true;
        END_SECAPI
@@ -974,6 +1094,10 @@ OSStatus SecKeychainIsValid(SecKeychainRef keychainRef, Boolean* isValid)
 OSStatus SecKeychainRemoveFromSearchList(SecKeychainRef keychainRef)
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainRemoveFromSearchList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
         StorageManager::KeychainList singleton;
         singleton.push_back(KeychainImpl::required(keychainRef));
         globals().storageManager.remove(singleton);
@@ -985,6 +1109,10 @@ OSStatus SecKeychainRemoveFromSearchList(SecKeychainRef keychainRef)
 OSStatus SecKeychainCreateNew(SecKeychainRef keychainRef, UInt32 passwordLength, const char* inPassword)
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainCreateNew", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
         RequiredParam(inPassword);
         KeychainImpl::required(keychainRef)->create(passwordLength, inPassword);
        END_SECAPI
@@ -996,6 +1124,10 @@ OSStatus SecKeychainRecodeKeychain(SecKeychainRef keychainRef, CFArrayRef dbBlob
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainRecodeKeychain", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        // do error checking for required parameters
        RequiredParam(dbBlobArray);
        RequiredParam(extraData);
@@ -1071,6 +1203,10 @@ OSStatus SecKeychainCopySignature(SecKeychainRef keychainRef, CFDataRef *keychai
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopySignature", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        // do error checking for required parameters
        RequiredParam(keychainSignature);
 
@@ -1095,6 +1231,10 @@ OSStatus SecKeychainCopyBlob(SecKeychainRef keychainRef, CFDataRef *dbBlob)
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainCopyBlob", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        // do error checking for required parameters
        RequiredParam(dbBlob);
 
@@ -1113,6 +1253,10 @@ OSStatus SecKeychainCopyBlob(SecKeychainRef keychainRef, CFDataRef *dbBlob)
 OSStatus SecKeychainCreateWithBlob(const char* fullPathName, CFDataRef dbBlob, SecKeychainRef *kcRef)
 {
        BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainCreateWithBlob", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
        
        KCThrowParamErrIf_(!fullPathName);
        KCThrowParamErrIf_(!dbBlob);
@@ -1138,6 +1282,10 @@ OSStatus SecKeychainAddDBToKeychainList (SecPreferencesDomain domain, const char
 {
        BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainAddDBToKeychainList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
        RequiredParam(dbName);
        StorageManager &smr = globals().storageManager;
        smr.addToDomainList(domain, dbName, *guid, subServiceType);
@@ -1150,7 +1298,8 @@ OSStatus SecKeychainDBIsInKeychainList (SecPreferencesDomain domain, const char*
                                                                                const CSSM_GUID *guid, uint32 subServiceType)
 {
        BEGIN_SECAPI
-       RequiredParam(dbName);
+
+          RequiredParam(dbName);
        StorageManager &smr = globals().storageManager;
        smr.isInDomainList(domain, dbName, *guid, subServiceType);
        END_SECAPI
@@ -1161,6 +1310,10 @@ OSStatus SecKeychainRemoveDBFromKeychainList (SecPreferencesDomain domain, const
                                                                                          const CSSM_GUID *guid, uint32 subServiceType)
 {
        BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainRemoveDBFromKeychainList", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
        RequiredParam(dbName);
        StorageManager &smr = globals().storageManager;
        smr.removeFromDomainList(domain, dbName, *guid, subServiceType);
@@ -1179,6 +1332,10 @@ void SecKeychainSetServerMode()
 OSStatus SecKeychainSetBatchMode (SecKeychainRef kcRef, Boolean mode, Boolean rollback)
 {
        BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainSetBatchMode", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
        RequiredParam(kcRef);
        Keychain keychain = Keychain::optional(kcRef);
        keychain->setBatchMode(mode, rollback);
@@ -1190,12 +1347,17 @@ OSStatus SecKeychainSetBatchMode (SecKeychainRef kcRef, Boolean mode, Boolean ro
 OSStatus SecKeychainCleanupHandles()
 {
        BEGIN_SECAPI
-       END_SECAPI // which causes the handle cache cleanup routine to run
+
+          END_SECAPI // which causes the handle cache cleanup routine to run
 }
 
 OSStatus SecKeychainVerifyKeyStorePassphrase(uint32_t retries)
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainVerifyKeyStorePassphrase", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
     SecurityServer::ClientSession().verifyKeyStorePassphrase(retries);
     END_SECAPI
 }
@@ -1203,6 +1365,10 @@ OSStatus SecKeychainVerifyKeyStorePassphrase(uint32_t retries)
 OSStatus SecKeychainChangeKeyStorePassphrase()
 {
     BEGIN_SECAPI
+
+          os_activity_t activity = os_activity_create("SecKeychainChangeKeyStorePassphrase", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
     SecurityServer::ClientSession().changeKeyStorePassphrase();
     END_SECAPI
 }
@@ -1211,6 +1377,10 @@ static OSStatus SecKeychainGetMasterKey(SecKeychainRef userKeychainRef, CFDataRe
 {
     BEGIN_SECAPI
 
+          os_activity_t activity = os_activity_create("SecKeychainGetMasterKey", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
     // make a keychain object "wrapper" for this keychain ref
        Keychain keychain = Keychain::optional(userKeychainRef);
 
@@ -1325,6 +1495,7 @@ static bool _SASetAutologinPW(CFStringRef inAutologinPW)
 }
 
 OSStatus SecKeychainStoreUnlockKey(SecKeychainRef userKeychainRef, SecKeychainRef systemKeychainRef, CFStringRef username, CFStringRef password) {
+       COUNTLEGACYAPI
     SecTrustedApplicationRef itemPath;
     SecAccessRef ourAccessRef = NULL;
     
@@ -1426,6 +1597,10 @@ OSStatus SecKeychainGetUserPromptAttempts(uint32_t * attempts)
 {
     BEGIN_SECAPI
 
+    os_activity_t activity = os_activity_create("SecKeychainGetUserPromptAttempts", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_IF_NONE_PRESENT);
+    os_activity_scope(activity);
+    os_release(activity);
+
     if(attempts) {
         SecurityServer::ClientSession().getUserPromptAttempts(*attempts);
     }
@@ -1436,6 +1611,7 @@ OSStatus SecKeychainGetUserPromptAttempts(uint32_t * attempts)
 OSStatus SecKeychainStoreUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash, CFStringRef tokenID, CFDataRef wrapPubKeyHash,
                                                  SecKeychainRef userKeychain, CFStringRef password)
 {
+       COUNTLEGACYAPI
        CFRef<CFStringRef> pwd;
        OSStatus result;
 
@@ -1443,47 +1619,52 @@ OSStatus SecKeychainStoreUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash, CFStringR
                AuthorizationRef authorizationRef;
                result = AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &authorizationRef);
                if (result != errAuthorizationSuccess) {
-                       secinfo("SecKeychain", "failed to create authorization");
+                       secnotice("SecKeychain", "failed to create authorization");
                        return result;
                }
 
                AuthorizationItem myItems = {"com.apple.ctk.pair", 0, NULL, 0};
                AuthorizationRights myRights = {1, &myItems};
-               AuthorizationRights *authorizedRights = NULL;
 
                char pathName[PATH_MAX];
                UInt32 pathLength = PATH_MAX;
                result = SecKeychainGetPath(userKeychain, &pathLength, pathName);
                if (result != errSecSuccess) {
-                       secinfo("SecKeychain", "Failed to get kc path: %d", (int) result);
+                       secnotice("SecKeychain", "failed to create authorization");
                        return result;
                }
 
                Boolean checkPwd = TRUE;
+               Boolean ignoreSession = TRUE;
                AuthorizationItem envItems[] = {
                        {AGENT_HINT_KEYCHAIN_PATH, pathLength, pathName, 0},
-                       {AGENT_HINT_KEYCHAIN_CHECK, sizeof(checkPwd), &checkPwd}
+                       {AGENT_HINT_KEYCHAIN_CHECK, sizeof(checkPwd), &checkPwd},
+                       {AGENT_HINT_IGNORE_SESSION, sizeof(ignoreSession), &ignoreSession}
                };
 
-               AuthorizationEnvironment environment  = {2, envItems};
+               AuthorizationEnvironment environment  = {3, envItems};
                AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
-               result = AuthorizationCopyRights(authorizationRef, &myRights, &environment, flags, &authorizedRights);
-               if (authorizedRights)
-                       AuthorizationFreeItemSet(authorizedRights);
+               result = AuthorizationCopyRights(authorizationRef, &myRights, &environment, flags, NULL);
+        secnotice("SecKeychain", "Authorization result: %d", (int)result);
 
                if (result == errAuthorizationSuccess) {
                        AuthorizationItemSet *items;
                        result = AuthorizationCopyInfo(authorizationRef, kAuthorizationEnvironmentPassword, &items);
+            secnotice("SecKeychain", "Items copy result: %d", (int)result);
                        if (result == errAuthorizationSuccess) {
+                secnotice("SecKeychain", "Items count: %d", items->count);
                                if (items->count > 0) {
                                        pwd = CFStringCreateWithCString(kCFAllocatorDefault, (const char *)items->items[0].value, kCFStringEncodingUTF8);
+                    if (pwd) {
+                        secnotice("SecKeychain", "Got kcpass");
+                    }
                                }
                                AuthorizationFreeItemSet(items);
                        }
                }
                AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
                if (result != errAuthorizationSuccess) {
-                       secinfo("SecKeychain", "did not get authorization to pair the card");
+                       secnotice("SecKeychain", "did not get authorization to pair the card");
                        return result;
                }
        } else {
@@ -1491,7 +1672,7 @@ OSStatus SecKeychainStoreUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash, CFStringR
        }
 
        if (!pwd) {
-               secinfo("SecKeychain", "did not get kcpass");
+               secnotice("SecKeychain", "did not get kcpass");
                return errSecInternalComponent;
        }
 
@@ -1516,15 +1697,32 @@ OSStatus SecKeychainStoreUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash, CFStringR
        }
 
        secnotice("SecKeychain", "SecKeychainStoreUnlockKeyWithPubKeyHash result %d", (int) result);
+    
+    // create SC KEK
+    // this might fail if KC password is different from user's password
+    uid_t uid = geteuid();
+    if (!uid) {
+        uid = getuid();
+    }
+    struct passwd *passwd = getpwuid(uid);
+    if (passwd) {
+        CFRef<CFStringRef> username = CFStringCreateWithCString(kCFAllocatorDefault, passwd->pw_name, kCFStringEncodingUTF8);
+        OSStatus kekRes = TKAddSecureToken(username, pwd, tokenID, wrapPubKeyHash);
+        if (kekRes != noErr) {
+            secnotice("SecKeychain", "Failed to register SC token: %d", (int) kekRes); // do not fail because KC functionality be still OK
+        }
+    } else {
+        secnotice("SecKeychain", "Unable to get name for uid %d", uid);
+    }
        return result;
 }
 
 OSStatus SecKeychainEraseUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash)
 {
+       COUNTLEGACYAPI
     OSStatus result = TokenLoginDeleteUnlockData(pubKeyHash);
     if (result != errSecSuccess) {
         secnotice("SecKeychain", "Failed to erase stored wrapped unlock key: %d", (int) result);
     }
     return result;
 }
-