static int do_keychain_set_settings(const char *keychainName, SecKeychainSettings newKeychainSettings) { SecKeychainRef keychain = NULL; OSStatus result; if (keychainName) { keychain = keychain_open(keychainName); if (!keychain) { result = 1; goto cleanup; } } result = SecKeychainSetSettings(keychain, &newKeychainSettings); if (result) { sec_error("SecKeychainSetSettings %s: %s", keychainName ? keychainName : "<NULL>", sec_errstr(result)); } cleanup: if (keychain) CFRelease(keychain); return result; }
static int do_lock(const char *keychainName) { SecKeychainRef keychain = NULL; OSStatus result; if (keychainName) { keychain = keychain_open(keychainName); if (!keychain) { result = 1; goto loser; } } result = SecKeychainLock(keychain); if (result) { sec_error("SecKeychainLock %s: %s", keychainName ? keychainName : "<NULL>", sec_errstr(result)); } loser: if (keychain) CFRelease(keychain); return result; }
/* Convert a reference key to a raw key. */ static CSSM_RETURN refKeyToRaw( CSSM_CSP_HANDLE cspHand, const CSSM_KEY *refKey, CSSM_KEY_PTR rawKey) // RETURNED { CSSM_CC_HANDLE ccHand; CSSM_RETURN crtn; CSSM_ACCESS_CREDENTIALS creds; memset(rawKey, 0, sizeof(CSSM_KEY)); memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS)); crtn = CSSM_CSP_CreateSymmetricContext(cspHand, CSSM_ALGID_NONE, CSSM_ALGMODE_NONE, &creds, // passPhrase NULL, // wrapping key NULL, // init vector CSSM_PADDING_NONE, // Padding 0, // Params &ccHand); if(crtn) { sec_error("CSSM_CSP_CreateSymmetricContext: refKeyToRaw context err: %s", sec_errstr(crtn)); return crtn; } crtn = CSSM_WrapKey(ccHand, &creds, refKey, NULL, // DescriptiveData rawKey); if(crtn != CSSM_OK) { sec_error("CSSM_WrapKey: refKeyToRaw wrap err: %s", sec_errstr(crtn)); return crtn; } CSSM_DeleteContext(ccHand); return CSSM_OK; }
OSStatus makeMasterPassword(const char *fvmkcName, const char *masterPasswordPassword, uint32 keySizeInBits, SecKeychainRef *keychainRef) { /* OSStatus SecFileVaultMakeMasterPassword(CFStringRef masterPasswordPassword); *** In the real code, this will be done directly rather than exec'ing a tool, since there are too many parameters to specify *** this needs to be done as root, since the keychain will be a system keychain /usr/bin/certtool y c k=/Library/Keychains/FileVaultMaster.keychain p=<masterPasswordPassword> /usr/bin/certtool c k=/Library/Keychains/FileVaultMaster.keychain o=/Library/Keychains/FileVaultMaster.cer Two steps: create the keychain, then create the keypair */ SecAccessRef initialAccess = NULL; if (!masterPasswordPassword) { sec_error("You must supply a non-empty password"); return -2; } // We return an error if the keychain already exists OSStatus status = SecKeychainCreate(fvmkcName, (UInt32) strlen(masterPasswordPassword), masterPasswordPassword, false, initialAccess, keychainRef); if (status!=noErr) { if (status==errSecDuplicateKeychain || status==CSSMERR_DL_DATASTORE_ALREADY_EXISTS) sec_error("The keychain file %s already exists", fvmkcName); return status; } // Create the key pair char host[PATH_MAX]; int rx = gethostname(host, sizeof(host)); if (rx) strcpy(host, "localhost"); CFStringRef hostName = CFSTR("FileVault Recovery Key"); // This is what shows up in Keychain Access display CFStringRef userName = CFStringCreateWithCString(kCFAllocatorDefault, host, kCFStringEncodingUTF8); CFDataRef certData = NULL; printf("Generating a %d bit key pair; this may take several minutes\n", keySizeInBits); status = createPair(hostName,userName,*keychainRef,keySizeInBits, &certData); if (status) sec_error("Error in createPair: %s", sec_errstr(status)); if (certData) CFRelease(certData); return status; }
int keychain_import(int argc, char * const *argv) { int ch, result = 0; char *inFile = NULL; char *kcName = NULL; SecKeychainRef kcRef = NULL; SecExternalFormat externFormat = kSecFormatUnknown; SecExternalItemType itemType = kSecItemTypeUnknown; Boolean wrapped = FALSE; Boolean nonExtractable = FALSE; const char *passphrase = NULL; unsigned char *inFileData = NULL; unsigned inFileLen = 0; CFDataRef inData = NULL; unsigned numExtendedAttributes = 0; char **attrNames = NULL; char **attrValues = NULL; Boolean access_specified = FALSE; Boolean always_allow = FALSE; SecAccessRef access = NULL; CFMutableArrayRef trusted_list = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); if(argc < 2) { result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } inFile = argv[1]; if((argc == 2) && (inFile[0] == '-')) { result = 2; goto cleanup; } optind = 2; while ((ch = getopt(argc, argv, "k:t:f:P:wxa:hAT:")) != -1) { switch (ch) { case 'k': kcName = optarg; break; case 't': if(!strcmp("pub", optarg)) { itemType = kSecItemTypePublicKey; } else if(!strcmp("priv", optarg)) { itemType = kSecItemTypePrivateKey; } else if(!strcmp("session", optarg)) { itemType = kSecItemTypeSessionKey; } else if(!strcmp("cert", optarg)) { itemType = kSecItemTypeCertificate; } else if(!strcmp("agg", optarg)) { itemType = kSecItemTypeAggregate; } else { result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } break; case 'f': if(!strcmp("openssl", optarg)) { externFormat = kSecFormatOpenSSL; } else if(!strcmp("openssh1", optarg)) { externFormat = kSecFormatSSH; } else if(!strcmp("openssh2", optarg)) { externFormat = kSecFormatSSHv2; } else if(!strcmp("bsafe", optarg)) { externFormat = kSecFormatBSAFE; } else if(!strcmp("raw", optarg)) { externFormat = kSecFormatRawKey; } else if(!strcmp("pkcs7", optarg)) { externFormat = kSecFormatPKCS7; } else if(!strcmp("pkcs8", optarg)) { externFormat = kSecFormatWrappedPKCS8; } else if(!strcmp("pkcs12", optarg)) { externFormat = kSecFormatPKCS12; } else if(!strcmp("netscape", optarg)) { externFormat = kSecFormatNetscapeCertSequence; } else if(!strcmp("x509", optarg)) { externFormat = kSecFormatX509Cert; } else if(!strcmp("pemseq", optarg)) { externFormat = kSecFormatPEMSequence; } else { result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } break; case 'w': wrapped = TRUE; break; case 'x': nonExtractable = TRUE; break; case 'P': passphrase = optarg; break; case 'a': /* this takes an additional argument */ if(optind > (argc - 1)) { result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } attrNames = (char **)realloc(attrNames, numExtendedAttributes * sizeof(char *)); attrValues = (char **)realloc(attrValues, numExtendedAttributes * sizeof(char *)); attrNames[numExtendedAttributes] = optarg; attrValues[numExtendedAttributes] = argv[optind]; numExtendedAttributes++; optind++; break; case 'A': always_allow = TRUE; access_specified = TRUE; break; case 'T': if (optarg[0]) { SecTrustedApplicationRef app = NULL; OSStatus status = noErr; /* check whether the argument specifies an application group */ const char *groupPrefix = "group://"; size_t prefixLen = strlen(groupPrefix); if (strlen(optarg) > prefixLen && !memcmp(optarg, groupPrefix, prefixLen)) { const char *groupName = &optarg[prefixLen]; if ((status = SecTrustedApplicationCreateApplicationGroup(groupName, NULL, &app)) != noErr) { sec_error("SecTrustedApplicationCreateApplicationGroup %s: %s", optarg, sec_errstr(status)); } } else { if ((status = SecTrustedApplicationCreateFromPath(optarg, &app)) != noErr) { sec_error("SecTrustedApplicationCreateFromPath %s: %s", optarg, sec_errstr(status)); } } if (status) { result = 1; goto cleanup; } CFArrayAppendValue(trusted_list, app); CFRelease(app); } access_specified = TRUE; break; case '?': default: result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } } if(wrapped) { switch(externFormat) { case kSecFormatOpenSSL: case kSecFormatUnknown: // i.e., use default externFormat = kSecFormatWrappedOpenSSL; break; case kSecFormatSSH: externFormat = kSecFormatWrappedSSH; break; case kSecFormatSSHv2: /* there is no wrappedSSHv2 */ externFormat = kSecFormatWrappedOpenSSL; break; case kSecFormatWrappedPKCS8: /* proceed */ break; default: fprintf(stderr, "Don't know how to wrap in specified format/type\n"); result = 2; /* @@@ Return 2 triggers usage message. */ goto cleanup; } } if(kcName) { kcRef = keychain_open(kcName); if(kcRef == NULL) { return 1; } } if(readFile(inFile, &inFileData, &inFileLen)) { sec_error("Error reading infile %s: %s", inFile, strerror(errno)); result = 1; goto cleanup; } inData = CFDataCreate(NULL, inFileData, inFileLen); if(inData == NULL) { result = 1; goto cleanup; } free(inFileData); if(access_specified) { char *accessName = NULL; CFStringRef fileStr = CFStringCreateWithCString(NULL, inFile, kCFStringEncodingUTF8); if (fileStr) { CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, fileStr, kCFURLPOSIXPathStyle, FALSE); if (fileURL) { CFStringRef nameStr = CFURLCopyLastPathComponent(fileURL); if (nameStr) { CFIndex nameLen = CFStringGetLength(nameStr); CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8); accessName = (char *)malloc(bufLen); if (!CFStringGetCString(nameStr, accessName, bufLen-1, kCFStringEncodingUTF8)) accessName[0]=0; nameLen = strlen(accessName); char *p = &accessName[nameLen]; // initially points to terminating null while (--nameLen > 0) { if (*p == '.') { // strip extension, if any *p = '\0'; break; } p--; } safe_CFRelease(&nameStr); } safe_CFRelease(&fileURL); } safe_CFRelease(&fileStr); } result = create_access(accessName, always_allow, trusted_list, &access); if (accessName) { free(accessName); } if (result != 0) { goto cleanup; } } result = do_keychain_import(kcRef, inData, externFormat, itemType, access, nonExtractable, passphrase, inFile, attrNames, attrValues, numExtendedAttributes); cleanup: safe_CFRelease(&trusted_list); safe_CFRelease(&access); safe_CFRelease(&kcRef); safe_CFRelease(&inData); return result; }
void sec_perror(const char *msg, int err) { sec_error("%s: %s", msg, sec_errstr(err)); }
/* * Generate a key pair using the CSPDL. */ OSStatus generateKeyPair( CSSM_CSP_HANDLE cspHand, CSSM_DL_DB_HANDLE dlDbHand, CSSM_ALGORITHMS keyAlg, // e.g., CSSM_ALGID_RSA uint32 keySizeInBits, const char *keyLabel, // C string CSSM_KEY_PTR *pubKeyPtr, // mallocd, created, RETURNED CSSM_KEY_PTR *privKeyPtr) // mallocd, created, RETURNED { CSSM_KEY_PTR pubKey = (CSSM_KEY_PTR)(APP_MALLOC(sizeof(CSSM_KEY))); CSSM_KEY_PTR privKey = (CSSM_KEY_PTR)(APP_MALLOC(sizeof(CSSM_KEY))); if((pubKey == NULL) || (privKey == NULL)) { return memFullErr; } CSSM_RETURN crtn; CSSM_KEYUSE pubKeyUse; CSSM_KEYUSE privKeyUse; pubKeyUse = CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_WRAP; privKeyUse = CSSM_KEYUSE_SIGN | CSSM_KEYUSE_DECRYPT | CSSM_KEYUSE_UNWRAP; crtn = srCspGenKeyPair(cspHand, &dlDbHand, keyAlg, keyLabel, (int) strlen(keyLabel) + 1, keySizeInBits, pubKey, pubKeyUse, CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_RETURN_REF, privKey, privKeyUse, CSSM_KEYATTR_SENSITIVE | CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_PERMANENT | CSSM_KEYATTR_EXTRACTABLE); if(crtn) { APP_FREE(pubKey); APP_FREE(privKey); return paramErr; } /* bind private key to cert by public key hash */ crtn = setPubKeyHash(cspHand, dlDbHand, pubKey, keyLabel); if(crtn) { sec_error("setPubKeyHash: Error setting public key hash. Continuing at peril: %s", sec_errstr(crtn)); } *pubKeyPtr = pubKey; *privKeyPtr = privKey; return noErr; }
/* * Find private key by label, modify its Label attr to be the * hash of the associated public key. */ static CSSM_RETURN setPubKeyHash( CSSM_CSP_HANDLE cspHand, CSSM_DL_DB_HANDLE dlDbHand, const CSSM_KEY *pubOrPrivKey, // to get hash; raw or ref/CSPDL const char *keyLabel) // look up by this { CSSM_QUERY query; CSSM_SELECTION_PREDICATE predicate; CSSM_DB_UNIQUE_RECORD_PTR record = NULL; CSSM_RETURN crtn; CSSM_DATA labelData; CSSM_HANDLE resultHand; labelData.Data = (uint8 *)keyLabel; labelData.Length = strlen(keyLabel) + 1; // incl. NULL query.RecordType = CSSM_DL_DB_RECORD_PRIVATE_KEY; query.Conjunctive = CSSM_DB_NONE; query.NumSelectionPredicates = 1; predicate.DbOperator = CSSM_DB_EQUAL; predicate.Attribute.Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; predicate.Attribute.Info.Label.AttributeName = "Label"; predicate.Attribute.Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; predicate.Attribute.Value = &labelData; query.SelectionPredicate = &predicate; query.QueryLimits.TimeLimit = 0; query.QueryLimits.SizeLimit = 1; query.QueryFlags = 0; /* build Record attribute with one attr */ CSSM_DB_RECORD_ATTRIBUTE_DATA recordAttrs; CSSM_DB_ATTRIBUTE_DATA attr; attr.Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; attr.Info.Label.AttributeName = "Label"; attr.Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; recordAttrs.DataRecordType = CSSM_DL_DB_RECORD_PRIVATE_KEY; recordAttrs.NumberOfAttributes = 1; recordAttrs.AttributeData = &attr; crtn = CSSM_DL_DataGetFirst(dlDbHand, &query, &resultHand, &recordAttrs, NULL, // hopefully optional ...theData, &record); /* abort only on success */ if(crtn != CSSM_OK) { sec_error("CSSM_DL_DataGetFirst: setPubKeyHash: can't find private key: %s", sec_errstr(crtn)); return crtn; } /* * If specified key is a ref key, do NULL unwrap for use with raw CSP. * If the CSPDL and SecurityServer support the key digest passthrough * this is unnecessary. */ CSSM_KEY rawKeyToDigest; if(pubOrPrivKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) { crtn = refKeyToRaw(cspHand, pubOrPrivKey, &rawKeyToDigest); if(crtn) { sec_error("setPubKeyHash: Error converting public key to raw format: %s", sec_errstr(crtn)); return crtn; } } else { /* use as is */ rawKeyToDigest = *pubOrPrivKey; } /* connect to raw CSP */ CSSM_CSP_HANDLE rawCspHand = srCspStartup(CSSM_TRUE); if(rawCspHand == 0) { printf("***Error connecting to raw CSP; aborting.\n"); return -1; } /* calculate hash of pub key from private or public part */ CSSM_DATA_PTR keyDigest = NULL; CSSM_CC_HANDLE ccHand; crtn = CSSM_CSP_CreatePassThroughContext(rawCspHand, &rawKeyToDigest, &ccHand); if(ccHand == 0) { sec_error("CSSM_CSP_CreatePassThroughContext: Error calculating public key hash. Aborting: %s", sec_errstr(crtn)); return -1; } crtn = CSSM_CSP_PassThrough(ccHand, CSSM_APPLECSP_KEYDIGEST, NULL, (void **)&keyDigest); if(crtn) { sec_error("CSSM_CSP_PassThrough(PUBKEYHASH): Error calculating public key hash. Aborting: %s", sec_errstr(crtn)); return crtn; } if(pubOrPrivKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) { /* created in refKeyToRaw().... */ CSSM_FreeKey(cspHand, NULL, &rawKeyToDigest, CSSM_FALSE); } CSSM_DeleteContext(ccHand); CSSM_ModuleDetach(rawCspHand); /* * Replace Label attr data with hash. * NOTE: the module which allocated this attribute data - a DL - * was loaded and attached by the Sec layer, not by us. Thus * we can't use the memory allocator functions *we* used when * attaching to the CSPDL - we have to use the ones * which the Sec layer registered with the DL. */ CSSM_API_MEMORY_FUNCS memFuncs; crtn = CSSM_GetAPIMemoryFunctions(dlDbHand.DLHandle, &memFuncs); if(crtn) { sec_error("CSSM_GetAPIMemoryFunctions(DLHandle): Error: %s", sec_errstr(crtn)); /* oh well, leak and continue */ } else { memFuncs.free_func(attr.Value->Data, memFuncs.AllocRef); memFuncs.free_func(attr.Value, memFuncs.AllocRef); } attr.Value = keyDigest; /* modify key attributes */ crtn = CSSM_DL_DataModify(dlDbHand, CSSM_DL_DB_RECORD_PRIVATE_KEY, record, &recordAttrs, NULL, // DataToBeModified CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); if(crtn) { sec_error("CSSM_DL_DataModify(PUBKEYHASH): Error setting public key hash. Aborting: %s", sec_errstr(crtn)); return crtn; } crtn = CSSM_DL_DataAbortQuery(dlDbHand, resultHand); if(crtn) { sec_error("CSSM_DL_DataAbortQuery: Error while stopping query: %s", sec_errstr(crtn)); /* let's keep going in this case */ } crtn = CSSM_DL_FreeUniqueRecord(dlDbHand, record); if(crtn) { sec_error("CSSM_DL_FreeUniqueRecord: Error while freeing record: %s", sec_errstr(crtn)); /* let's keep going in this case */ crtn = CSSM_OK; } /* free resources */ if (keyDigest) { srAppFree(keyDigest->Data, NULL); srAppFree(keyDigest, NULL); } return CSSM_OK; }
OSStatus createRootCert( CSSM_TP_HANDLE tpHand, CSSM_CL_HANDLE clHand, CSSM_CSP_HANDLE cspHand, CSSM_KEY_PTR subjPubKey, CSSM_KEY_PTR signerPrivKey, const char *hostName, // CSSMOID_CommonName const char *userName, // CSSMOID_Description CSSM_ALGORITHMS sigAlg, const CSSM_OID *sigOid, CSSM_DATA_PTR certData) // mallocd and RETURNED { CE_DataAndType exts[2]; CE_DataAndType *extp = exts; unsigned numExts; CSSM_DATA refId; // mallocd by // CSSM_TP_SubmitCredRequest CSSM_APPLE_TP_CERT_REQUEST certReq; CSSM_TP_REQUEST_SET reqSet; sint32 estTime; CSSM_BOOL confirmRequired; CSSM_TP_RESULT_SET_PTR resultSet=NULL; CSSM_ENCODED_CERT *encCert=NULL; CSSM_APPLE_TP_NAME_OID subjectNames[2]; CSSM_TP_CALLERAUTH_CONTEXT CallerAuthContext; CSSM_FIELD policyId; numExts = 0; certReq.challengeString = NULL; /* KeyUsage extension */ extp->type = DT_KeyUsage; extp->critical = CSSM_FALSE; extp->extension.keyUsage = CE_KU_DigitalSignature | CE_KU_KeyCertSign | CE_KU_KeyEncipherment | CE_KU_DataEncipherment; extp++; numExts++; /* BasicConstraints */ extp->type = DT_BasicConstraints; extp->critical = CSSM_TRUE; extp->extension.basicConstraints.cA = CSSM_FALSE; extp->extension.basicConstraints.pathLenConstraintPresent = CSSM_FALSE; extp++; numExts++; /* name array */ subjectNames[0].string = hostName; subjectNames[0].oid = &CSSMOID_CommonName; subjectNames[1].string = userName; subjectNames[1].oid = &CSSMOID_Description; /* certReq */ certReq.cspHand = cspHand; certReq.clHand = clHand; randUint32(&certReq.serialNumber); // random serial number certReq.numSubjectNames = 2; certReq.subjectNames = subjectNames; certReq.numIssuerNames = 0; // root for now certReq.issuerNames = NULL; certReq.issuerNameX509 = NULL; certReq.certPublicKey = subjPubKey; certReq.issuerPrivateKey = signerPrivKey; certReq.signatureAlg = sigAlg; certReq.signatureOid = *sigOid; certReq.notBefore = 0; certReq.notAfter = 60 * 60 * 24 * 365; // seconds from now, one year certReq.numExtensions = numExts; certReq.extensions = exts; reqSet.NumberOfRequests = 1; reqSet.Requests = &certReq; /* a CSSM_TP_CALLERAUTH_CONTEXT to specify an OID */ memset(&CallerAuthContext, 0, sizeof(CSSM_TP_CALLERAUTH_CONTEXT)); memset(&policyId, 0, sizeof(CSSM_FIELD)); policyId.FieldOid = CSSMOID_APPLE_TP_LOCAL_CERT_GEN; CallerAuthContext.Policy.NumberOfPolicyIds = 1; CallerAuthContext.Policy.PolicyIds = &policyId; CSSM_RETURN crtn = CSSM_TP_SubmitCredRequest(tpHand, NULL, // PreferredAuthority CSSM_TP_AUTHORITY_REQUEST_CERTISSUE, &reqSet, &CallerAuthContext, &estTime, &refId); if(crtn) { sec_error("CSSM_TP_SubmitCredRequest: %s", sec_errstr(crtn)); goto xit; } crtn = CSSM_TP_RetrieveCredResult(tpHand, &refId, NULL, // CallerAuthCredentials &estTime, &confirmRequired, &resultSet); if(crtn) { sec_error("CSSM_TP_RetrieveCredResult: %s", sec_errstr(crtn)); goto xit; } if(resultSet == NULL) { sec_error("CSSM_TP_RetrieveCredResult: returned NULL result set"); crtn = ioErr; goto xit; } encCert = (CSSM_ENCODED_CERT *)resultSet->Results; certData->Length = encCert->CertBlob.Length; certData->Data = malloc(encCert->CertBlob.Length); if (certData->Data) memcpy(certData->Data, encCert->CertBlob.Data, encCert->CertBlob.Length); crtn = noErr; xit: /* free resources allocated by TP */ APP_FREE(refId.Data); if (encCert) { if (encCert->CertBlob.Data) { APP_FREE(encCert->CertBlob.Data); } APP_FREE(encCert); } APP_FREE(resultSet); return crtn; }
static int do_recode(const char *keychainName1, const char *keychainName2) { SecKeychainRef keychain1 = NULL, keychain2 = NULL; CFMutableArrayRef dbBlobArray = NULL; CFDataRef dbBlob = NULL, extraData = NULL; OSStatus result; if (keychainName1) { keychain1 = keychain_open(keychainName1); if (!keychain1) { result = 1; goto loser; } } keychain2 = keychain_open(keychainName2); if (!keychain2) { result = 1; goto loser; } result = SecKeychainCopyBlob(keychain2, &dbBlob); if (result) { sec_error("SecKeychainCopyBlob %s: %s", keychainName2, sec_errstr(result)); goto loser; } extraData = CFDataCreate(NULL, NULL, 0); dbBlobArray = CFArrayCreateMutable(NULL, 1, &kCFTypeArrayCallBacks); if (dbBlobArray) { CFArrayAppendValue(dbBlobArray, dbBlob); } #if !defined MAC_OS_X_VERSION_10_6 || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 result = SecKeychainRecodeKeychain(keychain1, dbBlob, extraData); #else result = SecKeychainRecodeKeychain(keychain1, dbBlobArray, extraData); #endif if (result) sec_error("SecKeychainRecodeKeychain %s, %s: %s", keychainName1, keychainName2, sec_errstr(result)); loser: if (dbBlobArray) CFRelease(dbBlobArray); if (dbBlob) CFRelease(dbBlob); if (extraData) CFRelease(extraData); if (keychain1) CFRelease(keychain1); if (keychain2) CFRelease(keychain2); return result; }
static int do_keychain_set_password(const char *keychainName, const char* oldPassword, const char* newPassword) { SecKeychainRef keychain = NULL; OSStatus result = 1; UInt32 oldLen = (oldPassword) ? strlen(oldPassword) : 0; UInt32 newLen = (newPassword) ? strlen(newPassword) : 0; char *oldPass = (oldPassword) ? (char*)oldPassword : NULL; char *newPass = (newPassword) ? (char*)newPassword : NULL; char *oldBuf = NULL; char *newBuf = NULL; if (keychainName) { keychain = keychain_open(keychainName); if (!keychain) { result = 1; goto cleanup; } } if (!oldPass) { /* prompt for old password */ char *pBuf = getpass("Old Password: "******"New Password: "******"Retype New Password: "******"try again"); goto cleanup; } /* lock keychain first to remove existing credentials */ (void)SecKeychainLock(keychain); /* change the password */ result = SecKeychainChangePassword(keychain, oldLen, oldPass, newLen, newPass); if (result) { sec_error("error changing password for \"%s\": %s", keychainName ? keychainName : "<NULL>", sec_errstr(result)); } cleanup: /* if we allocated password buffers, zero and free them */ if (oldBuf) { bzero(oldBuf, PW_BUF_SIZE); free(oldBuf); } if (newBuf) { bzero(newBuf, PW_BUF_SIZE); free(newBuf); } if (keychain) { CFRelease(keychain); } return result; }
static int do_keychain_show_info(const char *keychainName) { SecKeychainRef keychain = NULL; SecKeychainSettings keychainSettings = { SEC_KEYCHAIN_SETTINGS_VERS1 }; OSStatus result; if (keychainName) { keychain = keychain_open(keychainName); if (!keychain) { result = 1; goto loser; } } result = SecKeychainCopySettings(keychain, &keychainSettings); if (result) { sec_error("SecKeychainCopySettings %s: %s", keychainName ? keychainName : "<NULL>", sec_errstr(result)); goto loser; } fprintf(stderr,"Keychain \"%s\"%s%s", keychainName ? keychainName : "<NULL>", keychainSettings.lockOnSleep ? " lock-on-sleep" : "", keychainSettings.useLockInterval ? " use-lock-interval" : ""); if (keychainSettings.lockInterval == INT_MAX) fprintf(stderr," no-timeout\n"); else fprintf(stderr," timeout=%ds\n", (int)keychainSettings.lockInterval); loser: if (keychain) CFRelease(keychain); return result; }