]> git.saurik.com Git - apple/security.git/blob - securityd/src/dbcrypto.cpp
Security-58286.1.32.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 CssmData ivData = CssmData::wrap(iv);
212 cryptor.initVector(ivData);
213
214 cryptor.key(master);
215 CssmAutoData cipher1(Server::csp().allocator());
216 cryptor.encrypt(probe, cipher1.get(), noRemainder);
217
218 cryptor.key(mMasterKey);
219 CssmAutoData cipher2(Server::csp().allocator());
220 cryptor.encrypt(probe, cipher2.get(), noRemainder);
221
222 return cipher1 == cipher2;
223 }
224
225
226 //
227 // Encode a database blob from the core.
228 //
229 DbBlob *DatabaseCryptoCore::encodeCore(const DbBlob &blobTemplate,
230 const CssmData &publicAcl, const CssmData &privateAcl) const
231 {
232 assert(isValid()); // must have secrets to work from
233
234 // make a new IV
235 uint8 iv[8];
236 Server::active().random(iv);
237
238 // build the encrypted section blob
239 CssmData &encryptionBits = *mEncryptionKey;
240 CssmData &signingBits = *mSigningKey;
241 CssmData incrypt[3];
242 incrypt[0] = encryptionBits;
243 incrypt[1] = signingBits;
244 incrypt[2] = privateAcl;
245 CssmData cryptoBlob, remData;
246 Encrypt cryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
247 cryptor.mode(CSSM_ALGMODE_CBCPadIV8);
248 cryptor.padding(CSSM_PADDING_PKCS1);
249 cryptor.key(mMasterKey);
250 CssmData ivd(iv, sizeof(iv)); cryptor.initVector(ivd);
251 cryptor.encrypt(incrypt, 3, &cryptoBlob, 1, remData);
252
253 // allocate the final DbBlob, uh, blob
254 size_t length = sizeof(DbBlob) + publicAcl.length() + cryptoBlob.length();
255 DbBlob *blob = Allocator::standard().malloc<DbBlob>(length);
256
257 // assemble the DbBlob
258 memset(blob, 0x7d, sizeof(DbBlob)); // deterministically fill any alignment gaps
259 blob->initialize(mBlobVersion);
260 blob->randomSignature = blobTemplate.randomSignature;
261 blob->sequence = blobTemplate.sequence;
262 blob->params = blobTemplate.params;
263 memcpy(blob->salt, mSalt, sizeof(blob->salt));
264 memcpy(blob->iv, iv, sizeof(iv));
265 memcpy(blob->publicAclBlob(), publicAcl, publicAcl.length());
266 blob->startCryptoBlob = sizeof(DbBlob) + int_cast<size_t, uint32_t>(publicAcl.length());
267 memcpy(blob->cryptoBlob(), cryptoBlob, cryptoBlob.length());
268 blob->totalLength = blob->startCryptoBlob + int_cast<size_t, uint32_t>(cryptoBlob.length());
269
270 // sign the blob
271 CssmData signChunk[] = {
272 CssmData(blob->data(), fieldOffsetOf(&DbBlob::blobSignature)),
273 CssmData(blob->publicAclBlob(), publicAcl.length() + cryptoBlob.length())
274 };
275 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
276
277 CSSM_ALGORITHMS signingAlgorithm = CSSM_ALGID_SHA1HMAC;
278 #if defined(COMPAT_OSX_10_0)
279 if (blob->version() == blob->version_MacOS_10_0)
280 signingAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
281 #endif
282 GenerateMac signer(Server::csp(), signingAlgorithm);
283 signer.key(mSigningKey);
284 signer.sign(signChunk, 2, signature);
285 assert(signature.length() == sizeof(blob->blobSignature));
286
287 // all done. Clean up
288 Server::csp()->allocator().free(cryptoBlob);
289 return blob;
290 }
291
292
293 //
294 // Decode a database blob into the core.
295 // Throws exceptions if decoding fails.
296 // Memory returned in privateAclBlob is allocated and becomes owned by caller.
297 //
298 void DatabaseCryptoCore::decodeCore(const DbBlob *blob, void **privateAclBlob)
299 {
300 assert(mHaveMaster); // must have master key installed
301
302 // try to decrypt the cryptoblob section
303 Decrypt decryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
304 decryptor.mode(CSSM_ALGMODE_CBCPadIV8);
305 decryptor.padding(CSSM_PADDING_PKCS1);
306 decryptor.key(mMasterKey);
307 CssmData ivd = CssmData::wrap(blob->iv); decryptor.initVector(ivd);
308 CssmData cryptoBlob = CssmData::wrap(blob->cryptoBlob(), blob->cryptoBlobLength());
309 CssmData decryptedBlob, remData;
310 decryptor.decrypt(cryptoBlob, decryptedBlob, remData);
311 DbBlob::PrivateBlob *privateBlob = decryptedBlob.interpretedAs<DbBlob::PrivateBlob>();
312
313 // tentatively establish keys
314 mEncryptionKey = makeRawKey(privateBlob->encryptionKey,
315 sizeof(privateBlob->encryptionKey), CSSM_ALGID_3DES_3KEY_EDE,
316 CSSM_KEYUSE_WRAP | CSSM_KEYUSE_UNWRAP);
317 mSigningKey = makeRawKey(privateBlob->signingKey,
318 sizeof(privateBlob->signingKey), CSSM_ALGID_SHA1HMAC,
319 CSSM_KEYUSE_SIGN | CSSM_KEYUSE_VERIFY);
320
321 // verify signature on the whole blob
322 CssmData signChunk[] = {
323 CssmData::wrap(blob->data(), fieldOffsetOf(&DbBlob::blobSignature)),
324 CssmData::wrap(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
325 };
326 CSSM_ALGORITHMS verifyAlgorithm = CSSM_ALGID_SHA1HMAC;
327 #if defined(COMPAT_OSX_10_0)
328 if (blob->version() == blob->version_MacOS_10_0)
329 verifyAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
330 #endif
331 VerifyMac verifier(Server::csp(), verifyAlgorithm);
332 verifier.key(mSigningKey);
333 verifier.verify(signChunk, 2, CssmData::wrap(blob->blobSignature));
334
335 // all checks out; start extracting fields
336 if (privateAclBlob) {
337 // extract private ACL blob as a separately allocated area
338 uint32 blobLength = (uint32) decryptedBlob.length() - sizeof(DbBlob::PrivateBlob);
339 *privateAclBlob = Allocator::standard().malloc(blobLength);
340 memcpy(*privateAclBlob, privateBlob->privateAclBlob(), blobLength);
341 }
342
343 // secrets have been established
344 mBlobVersion = blob->version();
345 mIsValid = true;
346 Allocator::standard().free(privateBlob);
347 }
348
349
350 //
351 // Make another DatabaseCryptoCore's operational secrets our own.
352 // Intended for keychain synchronization.
353 //
354 void DatabaseCryptoCore::importSecrets(const DatabaseCryptoCore &src)
355 {
356 assert(src.isValid()); // must have called src.decodeCore() first
357 assert(hasMaster());
358 mEncryptionKey = src.mEncryptionKey;
359 mSigningKey = src.mSigningKey;
360 mBlobVersion = src.mBlobVersion; // make sure we copy over all state
361 mIsValid = true;
362 }
363
364 //
365 // Encode a key blob
366 //
367 KeyBlob *DatabaseCryptoCore::encodeKeyCore(const CssmKey &inKey,
368 const CssmData &publicAcl, const CssmData &privateAcl,
369 bool inTheClear) const
370 {
371 CssmKey key = inKey;
372 uint8 iv[8];
373 CssmKey wrappedKey;
374
375 if(inTheClear && (privateAcl.Length != 0)) {
376 /* can't store private ACL component in the clear */
377 CssmError::throwMe(CSSMERR_DL_INVALID_ACCESS_CREDENTIALS);
378 }
379
380 // extract and hold some header bits the CSP does not want to see
381 uint32 heldAttributes = key.attributes() & managedAttributes;
382 key.clearAttribute(managedAttributes);
383 key.setAttribute(forcedAttributes);
384
385 if(inTheClear) {
386 /* NULL wrap of public key */
387 WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
388 wrap(key, wrappedKey, NULL);
389 }
390 else {
391 assert(isValid()); // need our database secrets
392
393 // create new IV
394 Server::active().random(iv);
395
396 // use a CMS wrap to encrypt the key
397 WrapKey wrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
398 wrap.key(mEncryptionKey);
399 wrap.mode(CSSM_ALGMODE_CBCPadIV8);
400 wrap.padding(CSSM_PADDING_PKCS1);
401 CssmData ivd(iv, sizeof(iv)); wrap.initVector(ivd);
402 wrap.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT,
403 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM));
404 wrap(key, wrappedKey, &privateAcl);
405 }
406
407 // stick the held attribute bits back in
408 key.clearAttribute(forcedAttributes);
409 key.setAttribute(heldAttributes);
410
411 // allocate the final KeyBlob, uh, blob
412 size_t length = sizeof(KeyBlob) + publicAcl.length() + wrappedKey.length();
413 KeyBlob *blob = Allocator::standard().malloc<KeyBlob>(length);
414
415 // assemble the KeyBlob
416 memset(blob, 0, sizeof(KeyBlob)); // fill alignment gaps
417 blob->initialize(mBlobVersion);
418 if(!inTheClear) {
419 memcpy(blob->iv, iv, sizeof(iv));
420 }
421 blob->header = key.header();
422 h2ni(blob->header); // endian-correct the header
423 blob->wrappedHeader.blobType = wrappedKey.blobType();
424 blob->wrappedHeader.blobFormat = wrappedKey.blobFormat();
425 blob->wrappedHeader.wrapAlgorithm = wrappedKey.wrapAlgorithm();
426 blob->wrappedHeader.wrapMode = wrappedKey.wrapMode();
427 memcpy(blob->publicAclBlob(), publicAcl, publicAcl.length());
428 blob->startCryptoBlob = sizeof(KeyBlob) + int_cast<size_t, uint32_t>(publicAcl.length());
429 memcpy(blob->cryptoBlob(), wrappedKey.data(), wrappedKey.length());
430 blob->totalLength = blob->startCryptoBlob + int_cast<size_t, uint32_t>(wrappedKey.length());
431
432 if(inTheClear) {
433 /* indicate that this is cleartext for decoding */
434 blob->setClearTextSignature();
435 }
436 else {
437 // sign the blob
438 CssmData signChunk[] = {
439 CssmData(blob->data(), fieldOffsetOf(&KeyBlob::blobSignature)),
440 CssmData(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
441 };
442 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
443
444 CSSM_ALGORITHMS signingAlgorithm = CSSM_ALGID_SHA1HMAC;
445 #if defined(COMPAT_OSX_10_0)
446 if (blob->version() == blob->version_MacOS_10_0)
447 signingAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
448 #endif
449 GenerateMac signer(Server::csp(), signingAlgorithm);
450 signer.key(mSigningKey);
451 signer.sign(signChunk, 2, signature);
452 assert(signature.length() == sizeof(blob->blobSignature));
453 }
454
455 // all done. Clean up
456 Server::csp()->allocator().free(wrappedKey);
457 return blob;
458 }
459
460
461 //
462 // Decode a key blob
463 //
464 void DatabaseCryptoCore::decodeKeyCore(KeyBlob *blob,
465 CssmKey &key, void * &pubAcl, void * &privAcl) const
466 {
467 // Note that we can't do anything with this key's version().
468
469 // Assemble the encrypted blob as a CSSM "wrapped key"
470 CssmKey wrappedKey;
471 wrappedKey.KeyHeader = blob->header;
472 h2ni(wrappedKey.KeyHeader);
473 wrappedKey.blobType(blob->wrappedHeader.blobType);
474 wrappedKey.blobFormat(blob->wrappedHeader.blobFormat);
475 wrappedKey.wrapAlgorithm(blob->wrappedHeader.wrapAlgorithm);
476 wrappedKey.wrapMode(blob->wrappedHeader.wrapMode);
477 wrappedKey.KeyData = CssmData(blob->cryptoBlob(), blob->cryptoBlobLength());
478
479 bool inTheClear = blob->isClearText();
480 if(!inTheClear) {
481 // verify signature (check against corruption)
482 assert(isValid()); // need our database secrets
483 CssmData signChunk[] = {
484 CssmData::wrap(blob, fieldOffsetOf(&KeyBlob::blobSignature)),
485 CssmData(blob->publicAclBlob(), blob->publicAclBlobLength() + blob->cryptoBlobLength())
486 };
487 CSSM_ALGORITHMS verifyAlgorithm = CSSM_ALGID_SHA1HMAC;
488 #if defined(COMPAT_OSX_10_0)
489 if (blob->version() == blob->version_MacOS_10_0)
490 verifyAlgorithm = CSSM_ALGID_SHA1HMAC_LEGACY; // BSafe bug compatibility
491 #endif
492 VerifyMac verifier(Server::csp(), verifyAlgorithm);
493 verifier.key(mSigningKey);
494 CssmData signature(blob->blobSignature, sizeof(blob->blobSignature));
495 verifier.verify(signChunk, 2, signature);
496 }
497 /* else signature indicates cleartext */
498
499 // extract and hold some header bits the CSP does not want to see
500 uint32 heldAttributes = n2h(blob->header.attributes()) & managedAttributes;
501
502 CssmData privAclData;
503 if(inTheClear) {
504 /* NULL unwrap */
505 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_NONE);
506 wrappedKey.clearAttribute(managedAttributes); //@@@ shouldn't be needed(?)
507 unwrap(wrappedKey,
508 KeySpec(n2h(blob->header.usage()),
509 (n2h(blob->header.attributes()) & ~managedAttributes) | forcedAttributes),
510 key, &privAclData);
511 }
512 else {
513 // decrypt the key using an unwrapping operation
514 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE);
515 unwrap.key(mEncryptionKey);
516 unwrap.mode(CSSM_ALGMODE_CBCPadIV8);
517 unwrap.padding(CSSM_PADDING_PKCS1);
518 CssmData ivd(blob->iv, sizeof(blob->iv)); unwrap.initVector(ivd);
519 unwrap.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT,
520 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM));
521 wrappedKey.clearAttribute(managedAttributes); //@@@ shouldn't be needed(?)
522 unwrap(wrappedKey,
523 KeySpec(n2h(blob->header.usage()),
524 (n2h(blob->header.attributes()) & ~managedAttributes) | forcedAttributes),
525 key, &privAclData);
526 }
527
528 // compare retrieved key headers with blob headers (sanity check)
529 // @@@ this should probably be checked over carefully
530 CssmKey::Header &real = key.header();
531 CssmKey::Header &incoming = blob->header;
532 n2hi(incoming);
533
534 if (real.HeaderVersion != incoming.HeaderVersion ||
535 real.cspGuid() != incoming.cspGuid())
536 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
537 if (real.algorithm() != incoming.algorithm())
538 CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM);
539
540 // re-insert held bits
541 key.header().KeyAttr |= heldAttributes;
542
543 if(inTheClear && (real.keyClass() != CSSM_KEYCLASS_PUBLIC_KEY)) {
544 /* Spoof - cleartext KeyBlob passed off as private key */
545 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
546 }
547
548 // got a valid key: return the pieces
549 pubAcl = blob->publicAclBlob(); // points into blob (shared)
550 privAcl = privAclData; // was allocated by CSP decrypt, else NULL for
551 // cleatext keys
552 // key was set by unwrap operation
553 }
554
555
556 //
557 // Derive the blob-specific database blob encryption key from the passphrase and the salt.
558 //
559 CssmClient::Key DatabaseCryptoCore::deriveDbMasterKey(const CssmData &passphrase) const
560 {
561 // derive an encryption key and IV from passphrase and salt
562 CssmClient::DeriveKey makeKey(Server::csp(),
563 CSSM_ALGID_PKCS5_PBKDF2, CSSM_ALGID_3DES_3KEY_EDE, 24 * 8);
564 makeKey.iterationCount(1000);
565 CssmData salt = CssmData::wrap(mSalt);
566 makeKey.salt(salt);
567 CSSM_PKCS5_PBKDF2_PARAMS params;
568 params.Passphrase = passphrase;
569 params.PseudoRandomFunction = CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1;
570 CssmData paramData = CssmData::wrap(params);
571 return makeKey(&paramData, KeySpec(CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
572 CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE));
573 }
574
575
576 //
577 // Turn raw keybits into a symmetric key in the CSP
578 //
579 CssmClient::Key DatabaseCryptoCore::makeRawKey(void *data, size_t length,
580 CSSM_ALGORITHMS algid, CSSM_KEYUSE usage)
581 {
582 // build a fake key
583 CssmKey key;
584 key.header().BlobType = CSSM_KEYBLOB_RAW;
585 key.header().Format = CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING;
586 key.header().AlgorithmId = algid;
587 key.header().KeyClass = CSSM_KEYCLASS_SESSION_KEY;
588 key.header().KeyUsage = usage;
589 key.header().KeyAttr = 0;
590 key.KeyData = CssmData(data, length);
591
592 // unwrap it into the CSP (but keep it raw)
593 UnwrapKey unwrap(Server::csp(), CSSM_ALGID_NONE);
594 CssmKey unwrappedKey;
595 CssmData descriptiveData;
596 unwrap(key,
597 KeySpec(CSSM_KEYUSE_ANY, CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE),
598 unwrappedKey, &descriptiveData, NULL);
599 return CssmClient::Key(Server::csp(), unwrappedKey);
600 }