]> git.saurik.com Git - apple/security.git/blob - securityd/src/dbcrypto.cpp
Security-57740.31.2.tar.gz
[apple/security.git] / securityd / src / dbcrypto.cpp
1 /*
2 * Copyright (c) 2000-2006,2013 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 //
26 // dbcrypto - cryptographic core for database and key blob cryptography
27 //
28 #include "dbcrypto.h"
29 #include <security_utilities/casts.h>
30 #include <securityd_client/ssblob.h>
31 #include "server.h" // just for Server::csp()
32 #include <security_cdsa_client/genkey.h>
33 #include <security_cdsa_client/cryptoclient.h>
34 #include <security_cdsa_client/keyclient.h>
35 #include <security_cdsa_client/macclient.h>
36 #include <security_cdsa_client/wrapkey.h>
37 #include <security_cdsa_utilities/cssmendian.h>
38
39 using namespace CssmClient;
40 using LowLevelMemoryUtilities::fieldOffsetOf;
41
42
43 //
44 // The CryptoCore constructor doesn't do anything interesting.
45 // It just initializes us to "empty".
46 //
47 DatabaseCryptoCore::DatabaseCryptoCore(uint32 requestedVersion) : mBlobVersion(CommonBlob::version_MacOS_10_0), mHaveMaster(false), mIsValid(false)
48 {
49 // If there's a specific version our callers want, give them that. Otherwise, ask CommonBlob what to do.
50 if(requestedVersion == CommonBlob::version_none) {
51 mBlobVersion = CommonBlob::getCurrentVersion();
52 } else {
53 mBlobVersion = requestedVersion;
54 }
55 }
56
57 DatabaseCryptoCore::~DatabaseCryptoCore()
58 {
59 // key objects take care of themselves
60 }
61
62
63 //
64 // Forget the secrets
65 //
66 void DatabaseCryptoCore::invalidate()
67 {
68 mMasterKey.release();
69 mHaveMaster = false;
70
71 mEncryptionKey.release();
72 mSigningKey.release();
73 mIsValid = false;
74 }
75
76 //
77 // Copy everything from another databasecryptocore
78 //
79 void DatabaseCryptoCore::initializeFrom(DatabaseCryptoCore& core, uint32 requestedVersion) {
80 if(core.hasMaster()) {
81 mMasterKey = core.mMasterKey;
82 memcpy(mSalt, core.mSalt, sizeof(mSalt));
83 mHaveMaster = core.mHaveMaster;
84 } else {
85 mHaveMaster = false;
86 }
87
88 if(core.isValid()) {
89 importSecrets(core);
90 } else {
91 mIsValid = false;
92 }
93
94 // As the last thing we do, check if we should be changing the version of this blob.
95 if(requestedVersion == CommonBlob::version_none) {
96 mBlobVersion = core.mBlobVersion;
97 } else {
98 mBlobVersion = requestedVersion;
99 }
100 }
101
102 //
103 // Generate new secrets for this crypto core.
104 //
105 void DatabaseCryptoCore::generateNewSecrets()
106 {
107 // create a random DES3 key
108 GenerateKey desGenerator(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE, 24 * 8);
109 mEncryptionKey = desGenerator(KeySpec(CSSM_KEYUSE_WRAP | CSSM_KEYUSE_UNWRAP,
110 CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE));
111
112 // create a random 20 byte HMAC/SHA1 signing "key"
113 GenerateKey signGenerator(Server::csp(), CSSM_ALGID_SHA1HMAC,
114 sizeof(DbBlob::PrivateBlob::SigningKey) * 8);
115 mSigningKey = signGenerator(KeySpec(CSSM_KEYUSE_SIGN | CSSM_KEYUSE_VERIFY,
116 CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE));
117
118 // secrets established
119 mIsValid = true;
120 }
121
122
123 CssmClient::Key DatabaseCryptoCore::masterKey()
124 {
125 assert(mHaveMaster);
126 return mMasterKey;
127 }
128
129
130 //
131 // Establish the master secret as derived from a passphrase passed in.
132 // If a DbBlob is passed, take the salt from it and remember it.
133 // If a NULL DbBlob is passed, generate a new (random) salt.
134 // Note that the passphrase is NOT remembered; only the master key.
135 //
136 void DatabaseCryptoCore::setup(const DbBlob *blob, const CssmData &passphrase, bool copyVersion /* = true */)
137 {
138 if (blob) {
139 if(copyVersion) {
140 mBlobVersion = blob->version();
141 }
142 memcpy(mSalt, blob->salt, sizeof(mSalt));
143 } else
144 Server::active().random(mSalt);
145 mMasterKey = deriveDbMasterKey(passphrase);
146 mHaveMaster = true;
147 }
148
149
150 //
151 // Establish the master secret directly from a master key passed in.
152 // We will copy the KeyData (caller still owns its copy).
153 // Blob/salt handling as above.
154 //
155 void DatabaseCryptoCore::setup(const DbBlob *blob, CssmClient::Key master, bool copyVersion /* = true */)
156 {
157 // pre-screen the key
158 CssmKey::Header header = master.header();
159 if (header.keyClass() != CSSM_KEYCLASS_SESSION_KEY)
160 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS);
161 if (header.algorithm() != CSSM_ALGID_3DES_3KEY_EDE)
162 CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM);
163
164 // accept it
165 if (blob) {
166 if(copyVersion) {
167 mBlobVersion = blob->version();
168 }
169 memcpy(mSalt, blob->salt, sizeof(mSalt));
170 } else
171 Server::active().random(mSalt);
172 mMasterKey = master;
173 mHaveMaster = true;
174 }
175
176 bool DatabaseCryptoCore::get_encryption_key(CssmOwnedData &data)
177 {
178 bool result = false;
179 if (isValid()) {
180 data = mEncryptionKey->keyData();
181 result = true;
182 }
183 return result;
184 }
185
186 //
187 // Given a putative passphrase, determine whether that passphrase
188 // properly generates the database's master secret.
189 // Return a boolean accordingly. Do not change our state.
190 // The database must have a master secret (to compare with).
191 // Note that any errors thrown by the cryptography here will actually
192 // throw out of validatePassphrase, since they "should not happen" and
193 // thus indicate a problem *beyond* (just) a bad passphrase.
194 //
195 bool DatabaseCryptoCore::validatePassphrase(const CssmData &passphrase)
196 {
197 CssmClient::Key master = deriveDbMasterKey(passphrase);
198 return validateKey(master);
199 }
200
201 bool DatabaseCryptoCore::validateKey(const CssmClient::Key& master) {
202 assert(hasMaster());
203 // to compare master with mMaster, see if they encrypt alike
204 StringData probe
205 ("Now is the time for all good processes to come to the aid of their kernel.");
206 CssmData noRemainder((void *)1, 0); // no cipher overflow
207 Encrypt cryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
208 cryptor.mode(CSSM_ALGMODE_CBCPadIV8);
209 cryptor.padding(CSSM_PADDING_PKCS1);
210 uint8 iv[8]; // leave uninitialized; pseudo-random is cool
211 cryptor.initVector(CssmData::wrap(iv));
212
213 cryptor.key(master);
214 CssmAutoData cipher1(Server::csp().allocator());
215 cryptor.encrypt(probe, cipher1.get(), noRemainder);
216
217 cryptor.key(mMasterKey);
218 CssmAutoData cipher2(Server::csp().allocator());
219 cryptor.encrypt(probe, cipher2.get(), noRemainder);
220
221 return cipher1 == cipher2;
222 }
223
224
225 //
226 // Encode a database blob from the core.
227 //
228 DbBlob *DatabaseCryptoCore::encodeCore(const DbBlob &blobTemplate,
229 const CssmData &publicAcl, const CssmData &privateAcl) const
230 {
231 assert(isValid()); // must have secrets to work from
232
233 // make a new IV
234 uint8 iv[8];
235 Server::active().random(iv);
236
237 // build the encrypted section blob
238 CssmData &encryptionBits = *mEncryptionKey;
239 CssmData &signingBits = *mSigningKey;
240 CssmData incrypt[3];
241 incrypt[0] = encryptionBits;
242 incrypt[1] = signingBits;
243 incrypt[2] = privateAcl;
244 CssmData cryptoBlob, remData;
245 Encrypt cryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
246 cryptor.mode(CSSM_ALGMODE_CBCPadIV8);
247 cryptor.padding(CSSM_PADDING_PKCS1);
248 cryptor.key(mMasterKey);
249 CssmData ivd(iv, sizeof(iv)); cryptor.initVector(ivd);
250 cryptor.encrypt(incrypt, 3, &cryptoBlob, 1, remData);
251
252 // allocate the final DbBlob, uh, blob
253 size_t length = sizeof(DbBlob) + publicAcl.length() + cryptoBlob.length();
254 DbBlob *blob = Allocator::standard().malloc<DbBlob>(length);
255
256 // assemble the DbBlob
257 memset(blob, 0x7d, sizeof(DbBlob)); // deterministically fill any alignment gaps
258 blob->initialize(mBlobVersion);
259 blob->randomSignature = blobTemplate.randomSignature;
260 blob->sequence = blobTemplate.sequence;
261 blob->params = blobTemplate.params;
262 memcpy(blob->salt, mSalt, sizeof(blob->salt));
263 memcpy(blob->iv, iv, sizeof(iv));
264 memcpy(blob->publicAclBlob(), publicAcl, publicAcl.length());
265 blob->startCryptoBlob = sizeof(DbBlob) + int_cast<size_t, uint32_t>(publicAcl.length());
266 memcpy(blob->cryptoBlob(), cryptoBlob, cryptoBlob.length());
267 blob->totalLength = blob->startCryptoBlob + int_cast<size_t, uint32_t>(cryptoBlob.length());
268
269 // sign the blob
270 CssmData signChunk[] = {
271 CssmData(blob->data(), fieldOffsetOf(&DbBlob::blobSignature)),
272 CssmData(blob->publicAclBlob(), publicAcl.length() + cryptoBlob.length())
273 };
274 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
275
276 CSSM_ALGORITHMS signingAlgorithm = CSSM_ALGID_SHA1HMAC;
277 #if defined(COMPAT_OSX_10_0)
278 if (blob->version() == blob->version_MacOS_10_0)
279 signingAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
280 #endif
281 GenerateMac signer(Server::csp(), signingAlgorithm);
282 signer.key(mSigningKey);
283 signer.sign(signChunk, 2, signature);
284 assert(signature.length() == sizeof(blob->blobSignature));
285
286 // all done. Clean up
287 Server::csp()->allocator().free(cryptoBlob);
288 return blob;
289 }
290
291
292 //
293 // Decode a database blob into the core.
294 // Throws exceptions if decoding fails.
295 // Memory returned in privateAclBlob is allocated and becomes owned by caller.
296 //
297 void DatabaseCryptoCore::decodeCore(const DbBlob *blob, void **privateAclBlob)
298 {
299 assert(mHaveMaster); // must have master key installed
300
301 // try to decrypt the cryptoblob section
302 Decrypt decryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
303 decryptor.mode(CSSM_ALGMODE_CBCPadIV8);
304 decryptor.padding(CSSM_PADDING_PKCS1);
305 decryptor.key(mMasterKey);
306 CssmData ivd = CssmData::wrap(blob->iv); decryptor.initVector(ivd);
307 CssmData cryptoBlob = CssmData::wrap(blob->cryptoBlob(), blob->cryptoBlobLength());
308 CssmData decryptedBlob, remData;
309 decryptor.decrypt(cryptoBlob, decryptedBlob, remData);
310 DbBlob::PrivateBlob *privateBlob = decryptedBlob.interpretedAs<DbBlob::PrivateBlob>();
311
312 // tentatively establish keys
313 mEncryptionKey = makeRawKey(privateBlob->encryptionKey,
314 sizeof(privateBlob->encryptionKey), CSSM_ALGID_3DES_3KEY_EDE,
315 CSSM_KEYUSE_WRAP | CSSM_KEYUSE_UNWRAP);
316 mSigningKey = makeRawKey(privateBlob->signingKey,
317 sizeof(privateBlob->signingKey), CSSM_ALGID_SHA1HMAC,
318 CSSM_KEYUSE_SIGN | CSSM_KEYUSE_VERIFY);
319
320 // verify signature on the whole blob
321 CssmData signChunk[] = {
322 CssmData::wrap(blob->data(), fieldOffsetOf(&DbBlob::blobSignature)),
323 CssmData::wrap(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
324 };
325 CSSM_ALGORITHMS verifyAlgorithm = CSSM_ALGID_SHA1HMAC;
326 #if defined(COMPAT_OSX_10_0)
327 if (blob->version() == blob->version_MacOS_10_0)
328 verifyAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
329 #endif
330 VerifyMac verifier(Server::csp(), verifyAlgorithm);
331 verifier.key(mSigningKey);
332 verifier.verify(signChunk, 2, CssmData::wrap(blob->blobSignature));
333
334 // all checks out; start extracting fields
335 if (privateAclBlob) {
336 // extract private ACL blob as a separately allocated area
337 uint32 blobLength = (uint32) decryptedBlob.length() - sizeof(DbBlob::PrivateBlob);
338 *privateAclBlob = Allocator::standard().malloc(blobLength);
339 memcpy(*privateAclBlob, privateBlob->privateAclBlob(), blobLength);
340 }
341
342 // secrets have been established
343 mBlobVersion = blob->version();
344 mIsValid = true;
345 Allocator::standard().free(privateBlob);
346 }
347
348
349 //
350 // Make another DatabaseCryptoCore's operational secrets our own.
351 // Intended for keychain synchronization.
352 //
353 void DatabaseCryptoCore::importSecrets(const DatabaseCryptoCore &src)
354 {
355 assert(src.isValid()); // must have called src.decodeCore() first
356 assert(hasMaster());
357 mEncryptionKey = src.mEncryptionKey;
358 mSigningKey = src.mSigningKey;
359 mBlobVersion = src.mBlobVersion; // make sure we copy over all state
360 mIsValid = true;
361 }
362
363 //
364 // Encode a key blob
365 //
366 KeyBlob *DatabaseCryptoCore::encodeKeyCore(const CssmKey &inKey,
367 const CssmData &publicAcl, const CssmData &privateAcl,
368 bool inTheClear) const
369 {
370 CssmKey key = inKey;
371 uint8 iv[8];
372 CssmKey wrappedKey;
373
374 if(inTheClear && (privateAcl.Length != 0)) {
375 /* can't store private ACL component in the clear */
376 CssmError::throwMe(CSSMERR_DL_INVALID_ACCESS_CREDENTIALS);
377 }
378
379 // extract and hold some header bits the CSP does not want to see
380 uint32 heldAttributes = key.attributes() & managedAttributes;
381 key.clearAttribute(managedAttributes);
382 key.setAttribute(forcedAttributes);
383
384 if(inTheClear) {
385 /* NULL wrap of public key */
386 WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
387 wrap(key, wrappedKey, NULL);
388 }
389 else {
390 assert(isValid()); // need our database secrets
391
392 // create new IV
393 Server::active().random(iv);
394
395 // use a CMS wrap to encrypt the key
396 WrapKey wrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
397 wrap.key(mEncryptionKey);
398 wrap.mode(CSSM_ALGMODE_CBCPadIV8);
399 wrap.padding(CSSM_PADDING_PKCS1);
400 CssmData ivd(iv, sizeof(iv)); wrap.initVector(ivd);
401 wrap.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT,
402 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM));
403 wrap(key, wrappedKey, &privateAcl);
404 }
405
406 // stick the held attribute bits back in
407 key.clearAttribute(forcedAttributes);
408 key.setAttribute(heldAttributes);
409
410 // allocate the final KeyBlob, uh, blob
411 size_t length = sizeof(KeyBlob) + publicAcl.length() + wrappedKey.length();
412 KeyBlob *blob = Allocator::standard().malloc<KeyBlob>(length);
413
414 // assemble the KeyBlob
415 memset(blob, 0, sizeof(KeyBlob)); // fill alignment gaps
416 blob->initialize(mBlobVersion);
417 if(!inTheClear) {
418 memcpy(blob->iv, iv, sizeof(iv));
419 }
420 blob->header = key.header();
421 h2ni(blob->header); // endian-correct the header
422 blob->wrappedHeader.blobType = wrappedKey.blobType();
423 blob->wrappedHeader.blobFormat = wrappedKey.blobFormat();
424 blob->wrappedHeader.wrapAlgorithm = wrappedKey.wrapAlgorithm();
425 blob->wrappedHeader.wrapMode = wrappedKey.wrapMode();
426 memcpy(blob->publicAclBlob(), publicAcl, publicAcl.length());
427 blob->startCryptoBlob = sizeof(KeyBlob) + int_cast<size_t, uint32_t>(publicAcl.length());
428 memcpy(blob->cryptoBlob(), wrappedKey.data(), wrappedKey.length());
429 blob->totalLength = blob->startCryptoBlob + int_cast<size_t, uint32_t>(wrappedKey.length());
430
431 if(inTheClear) {
432 /* indicate that this is cleartext for decoding */
433 blob->setClearTextSignature();
434 }
435 else {
436 // sign the blob
437 CssmData signChunk[] = {
438 CssmData(blob->data(), fieldOffsetOf(&KeyBlob::blobSignature)),
439 CssmData(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
440 };
441 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
442
443 CSSM_ALGORITHMS signingAlgorithm = CSSM_ALGID_SHA1HMAC;
444 #if defined(COMPAT_OSX_10_0)
445 if (blob->version() == blob->version_MacOS_10_0)
446 signingAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
447 #endif
448 GenerateMac signer(Server::csp(), signingAlgorithm);
449 signer.key(mSigningKey);
450 signer.sign(signChunk, 2, signature);
451 assert(signature.length() == sizeof(blob->blobSignature));
452 }
453
454 // all done. Clean up
455 Server::csp()->allocator().free(wrappedKey);
456 return blob;
457 }
458
459
460 //
461 // Decode a key blob
462 //
463 void DatabaseCryptoCore::decodeKeyCore(KeyBlob *blob,
464 CssmKey &key, void * &pubAcl, void * &privAcl) const
465 {
466 // Note that we can't do anything with this key's version().
467
468 // Assemble the encrypted blob as a CSSM "wrapped key"
469 CssmKey wrappedKey;
470 wrappedKey.KeyHeader = blob->header;
471 h2ni(wrappedKey.KeyHeader);
472 wrappedKey.blobType(blob->wrappedHeader.blobType);
473 wrappedKey.blobFormat(blob->wrappedHeader.blobFormat);
474 wrappedKey.wrapAlgorithm(blob->wrappedHeader.wrapAlgorithm);
475 wrappedKey.wrapMode(blob->wrappedHeader.wrapMode);
476 wrappedKey.KeyData = CssmData(blob->cryptoBlob(), blob->cryptoBlobLength());
477
478 bool inTheClear = blob->isClearText();
479 if(!inTheClear) {
480 // verify signature (check against corruption)
481 assert(isValid()); // need our database secrets
482 CssmData signChunk[] = {
483 CssmData::wrap(blob, fieldOffsetOf(&KeyBlob::blobSignature)),
484 CssmData(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
485 };
486 CSSM_ALGORITHMS verifyAlgorithm = CSSM_ALGID_SHA1HMAC;
487 #if defined(COMPAT_OSX_10_0)
488 if (blob->version() == blob->version_MacOS_10_0)
489 verifyAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
490 #endif
491 VerifyMac verifier(Server::csp(), verifyAlgorithm);
492 verifier.key(mSigningKey);
493 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
494 verifier.verify(signChunk, 2, signature);
495 }
496 /* else signature indicates cleartext */
497
498 // extract and hold some header bits the CSP does not want to see
499 uint32 heldAttributes = n2h(blob->header.attributes()) & managedAttributes;
500
501 CssmData privAclData;
502 if(inTheClear) {
503 /* NULL unwrap */
504 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_NONE);
505 wrappedKey.clearAttribute(managedAttributes); //@@@ shouldn't be needed(?)
506 unwrap(wrappedKey,
507 KeySpec(n2h(blob->header.usage()),
508 (n2h(blob->header.attributes()) & ~managedAttributes) | forcedAttributes),
509 key, &privAclData);
510 }
511 else {
512 // decrypt the key using an unwrapping operation
513 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
514 unwrap.key(mEncryptionKey);
515 unwrap.mode(CSSM_ALGMODE_CBCPadIV8);
516 unwrap.padding(CSSM_PADDING_PKCS1);
517 CssmData ivd(blob->iv, sizeof(blob->iv)); unwrap.initVector(ivd);
518 unwrap.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT,
519 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM));
520 wrappedKey.clearAttribute(managedAttributes); //@@@ shouldn't be needed(?)
521 unwrap(wrappedKey,
522 KeySpec(n2h(blob->header.usage()),
523 (n2h(blob->header.attributes()) & ~managedAttributes) | forcedAttributes),
524 key, &privAclData);
525 }
526
527 // compare retrieved key headers with blob headers (sanity check)
528 // @@@ this should probably be checked over carefully
529 CssmKey::Header &real = key.header();
530 CssmKey::Header &incoming = blob->header;
531 n2hi(incoming);
532
533 if (real.HeaderVersion != incoming.HeaderVersion ||
534 real.cspGuid() != incoming.cspGuid())
535 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
536 if (real.algorithm() != incoming.algorithm())
537 CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM);
538
539 // re-insert held bits
540 key.header().KeyAttr |= heldAttributes;
541
542 if(inTheClear && (real.keyClass() != CSSM_KEYCLASS_PUBLIC_KEY)) {
543 /* Spoof - cleartext KeyBlob passed off as private key */
544 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
545 }
546
547 // got a valid key: return the pieces
548 pubAcl = blob->publicAclBlob(); // points into blob (shared)
549 privAcl = privAclData; // was allocated by CSP decrypt, else NULL for
550 // cleatext keys
551 // key was set by unwrap operation
552 }
553
554
555 //
556 // Derive the blob-specific database blob encryption key from the passphrase and the salt.
557 //
558 CssmClient::Key DatabaseCryptoCore::deriveDbMasterKey(const CssmData &passphrase) const
559 {
560 // derive an encryption key and IV from passphrase and salt
561 CssmClient::DeriveKey makeKey(Server::csp(),
562 CSSM_ALGID_PKCS5_PBKDF2, CSSM_ALGID_3DES_3KEY_EDE, 24 * 8);
563 makeKey.iterationCount(1000);
564 CssmData salt = CssmData::wrap(mSalt);
565 makeKey.salt(salt);
566 CSSM_PKCS5_PBKDF2_PARAMS params;
567 params.Passphrase = passphrase;
568 params.PseudoRandomFunction = CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1;
569 CssmData paramData = CssmData::wrap(params);
570 return makeKey(&paramData, KeySpec(CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
571 CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE));
572 }
573
574
575 //
576 // Turn raw keybits into a symmetric key in the CSP
577 //
578 CssmClient::Key DatabaseCryptoCore::makeRawKey(void *data, size_t length,
579 CSSM_ALGORITHMS algid, CSSM_KEYUSE usage)
580 {
581 // build a fake key
582 CssmKey key;
583 key.header().BlobType = CSSM_KEYBLOB_RAW;
584 key.header().Format = CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING;
585 key.header().AlgorithmId = algid;
586 key.header().KeyClass = CSSM_KEYCLASS_SESSION_KEY;
587 key.header().KeyUsage = usage;
588 key.header().KeyAttr = 0;
589 key.KeyData = CssmData(data, length);
590
591 // unwrap it into the CSP (but keep it raw)
592 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_NONE);
593 CssmKey unwrappedKey;
594 CssmData descriptiveData;
595 unwrap(key,
596 KeySpec(CSSM_KEYUSE_ANY, CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE),
597 unwrappedKey, &descriptiveData, NULL);
598 return CssmClient::Key(Server::csp(), unwrappedKey);
599 }