2 * Copyright (c) 2000-2004 Apple Computer, Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
26 // dbcrypto - cryptographic core for database and key blob cryptography
29 #include <securityd_client/ssblob.h>
30 #include "server.h" // just for Server::csp()
31 #include <security_cdsa_client/genkey.h>
32 #include <security_cdsa_client/cryptoclient.h>
33 #include <security_cdsa_client/keyclient.h>
34 #include <security_cdsa_client/macclient.h>
35 #include <security_cdsa_client/wrapkey.h>
36 #include <security_cdsa_utilities/cssmendian.h>
38 using namespace CssmClient
;
39 using LowLevelMemoryUtilities::fieldOffsetOf
;
43 // The CryptoCore constructor doesn't do anything interesting.
44 // It just initializes us to "empty".
46 DatabaseCryptoCore::DatabaseCryptoCore() : mHaveMaster(false), mIsValid(false)
50 DatabaseCryptoCore::~DatabaseCryptoCore()
52 // key objects take care of themselves
59 void DatabaseCryptoCore::invalidate()
64 mEncryptionKey
.release();
65 mSigningKey
.release();
71 // Generate new secrets for this crypto core.
73 void DatabaseCryptoCore::generateNewSecrets()
75 // create a random DES3 key
76 GenerateKey
desGenerator(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
, 24 * 8);
77 mEncryptionKey
= desGenerator(KeySpec(CSSM_KEYUSE_WRAP
| CSSM_KEYUSE_UNWRAP
,
78 CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
));
80 // create a random 20 byte HMAC/SHA1 signing "key"
81 GenerateKey
signGenerator(Server::csp(), CSSM_ALGID_SHA1HMAC
,
82 sizeof(DbBlob::PrivateBlob::SigningKey
) * 8);
83 mSigningKey
= signGenerator(KeySpec(CSSM_KEYUSE_SIGN
| CSSM_KEYUSE_VERIFY
,
84 CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
));
86 // secrets established
91 CssmClient::Key
DatabaseCryptoCore::masterKey()
99 // Establish the master secret as derived from a passphrase passed in.
100 // If a DbBlob is passed, take the salt from it and remember it.
101 // If a NULL DbBlob is passed, generate a new (random) salt.
102 // Note that the passphrase is NOT remembered; only the master key.
104 void DatabaseCryptoCore::setup(const DbBlob
*blob
, const CssmData
&passphrase
)
107 memcpy(mSalt
, blob
->salt
, sizeof(mSalt
));
109 Server::active().random(mSalt
);
110 mMasterKey
= deriveDbMasterKey(passphrase
);
116 // Establish the master secret directly from a master key passed in.
117 // We will copy the KeyData (caller still owns its copy).
118 // Blob/salt handling as above.
120 void DatabaseCryptoCore::setup(const DbBlob
*blob
, CssmClient::Key master
)
122 // pre-screen the key
123 CssmKey::Header header
= master
.header();
124 if (header
.keyClass() != CSSM_KEYCLASS_SESSION_KEY
)
125 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
126 if (header
.algorithm() != CSSM_ALGID_3DES_3KEY_EDE
)
127 CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM
);
131 memcpy(mSalt
, blob
->salt
, sizeof(mSalt
));
133 Server::active().random(mSalt
);
140 // Given a putative passphrase, determine whether that passphrase
141 // properly generates the database's master secret.
142 // Return a boolean accordingly. Do not change our state.
143 // The database must have a master secret (to compare with).
144 // Note that any errors thrown by the cryptography here will actually
145 // throw out of validatePassphrase, since they "should not happen" and
146 // thus indicate a problem *beyond* (just) a bad passphrase.
148 bool DatabaseCryptoCore::validatePassphrase(const CssmData
&passphrase
)
151 CssmClient::Key master
= deriveDbMasterKey(passphrase
);
153 // to compare master with mMaster, see if they encrypt alike
155 ("Now is the time for all good processes to come to the aid of their kernel.");
156 CssmData
noRemainder((void *)1, 0); // no cipher overflow
157 Encrypt
cryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
);
158 cryptor
.mode(CSSM_ALGMODE_CBCPadIV8
);
159 cryptor
.padding(CSSM_PADDING_PKCS1
);
160 uint8 iv
[8]; // leave uninitialized; pseudo-random is cool
161 cryptor
.initVector(CssmData::wrap(iv
));
164 CssmAutoData
cipher1(Server::csp().allocator());
165 cryptor
.encrypt(probe
, cipher1
.get(), noRemainder
);
167 cryptor
.key(mMasterKey
);
168 CssmAutoData
cipher2(Server::csp().allocator());
169 cryptor
.encrypt(probe
, cipher2
.get(), noRemainder
);
171 return cipher1
== cipher2
;
176 // Encode a database blob from the core.
178 DbBlob
*DatabaseCryptoCore::encodeCore(const DbBlob
&blobTemplate
,
179 const CssmData
&publicAcl
, const CssmData
&privateAcl
) const
181 assert(isValid()); // must have secrets to work from
185 Server::active().random(iv
);
187 // build the encrypted section blob
188 CssmData
&encryptionBits
= *mEncryptionKey
;
189 CssmData
&signingBits
= *mSigningKey
;
191 incrypt
[0] = encryptionBits
;
192 incrypt
[1] = signingBits
;
193 incrypt
[2] = privateAcl
;
194 CssmData cryptoBlob
, remData
;
195 Encrypt
cryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
);
196 cryptor
.mode(CSSM_ALGMODE_CBCPadIV8
);
197 cryptor
.padding(CSSM_PADDING_PKCS1
);
198 cryptor
.key(mMasterKey
);
199 CssmData
ivd(iv
, sizeof(iv
)); cryptor
.initVector(ivd
);
200 cryptor
.encrypt(incrypt
, 3, &cryptoBlob
, 1, remData
);
202 // allocate the final DbBlob, uh, blob
203 size_t length
= sizeof(DbBlob
) + publicAcl
.length() + cryptoBlob
.length();
204 DbBlob
*blob
= Allocator::standard().malloc
<DbBlob
>(length
);
206 // assemble the DbBlob
207 memset(blob
, 0x7d, sizeof(DbBlob
)); // deterministically fill any alignment gaps
209 blob
->randomSignature
= blobTemplate
.randomSignature
;
210 blob
->sequence
= blobTemplate
.sequence
;
211 blob
->params
= blobTemplate
.params
;
212 memcpy(blob
->salt
, mSalt
, sizeof(blob
->salt
));
213 memcpy(blob
->iv
, iv
, sizeof(iv
));
214 memcpy(blob
->publicAclBlob(), publicAcl
, publicAcl
.length());
215 blob
->startCryptoBlob
= sizeof(DbBlob
) + publicAcl
.length();
216 memcpy(blob
->cryptoBlob(), cryptoBlob
, cryptoBlob
.length());
217 blob
->totalLength
= blob
->startCryptoBlob
+ cryptoBlob
.length();
220 CssmData signChunk
[] = {
221 CssmData(blob
->data(), fieldOffsetOf(&DbBlob::blobSignature
)),
222 CssmData(blob
->publicAclBlob(), publicAcl
.length() + cryptoBlob
.length())
224 CssmData
signature(blob
->blobSignature
, sizeof(blob
->blobSignature
));
225 GenerateMac
signer(Server::csp(), CSSM_ALGID_SHA1HMAC_LEGACY
);
226 signer
.key(mSigningKey
);
227 signer
.sign(signChunk
, 2, signature
);
228 assert(signature
.length() == sizeof(blob
->blobSignature
));
230 // all done. Clean up
231 Server::csp()->allocator().free(cryptoBlob
);
237 // Decode a database blob into the core.
238 // Throws exceptions if decoding fails.
239 // Memory returned in privateAclBlob is allocated and becomes owned by caller.
241 void DatabaseCryptoCore::decodeCore(const DbBlob
*blob
, void **privateAclBlob
)
243 assert(mHaveMaster
); // must have master key installed
245 // try to decrypt the cryptoblob section
246 Decrypt
decryptor(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
);
247 decryptor
.mode(CSSM_ALGMODE_CBCPadIV8
);
248 decryptor
.padding(CSSM_PADDING_PKCS1
);
249 decryptor
.key(mMasterKey
);
250 CssmData ivd
= CssmData::wrap(blob
->iv
); decryptor
.initVector(ivd
);
251 CssmData cryptoBlob
= CssmData::wrap(blob
->cryptoBlob(), blob
->cryptoBlobLength());
252 CssmData decryptedBlob
, remData
;
253 decryptor
.decrypt(cryptoBlob
, decryptedBlob
, remData
);
254 DbBlob::PrivateBlob
*privateBlob
= decryptedBlob
.interpretedAs
<DbBlob::PrivateBlob
>();
256 // tentatively establish keys
257 mEncryptionKey
= makeRawKey(privateBlob
->encryptionKey
,
258 sizeof(privateBlob
->encryptionKey
), CSSM_ALGID_3DES_3KEY_EDE
,
259 CSSM_KEYUSE_WRAP
| CSSM_KEYUSE_UNWRAP
);
260 mSigningKey
= makeRawKey(privateBlob
->signingKey
,
261 sizeof(privateBlob
->signingKey
), CSSM_ALGID_SHA1HMAC
,
262 CSSM_KEYUSE_SIGN
| CSSM_KEYUSE_VERIFY
);
264 // verify signature on the whole blob
265 CssmData signChunk
[] = {
266 CssmData::wrap(blob
->data(), fieldOffsetOf(&DbBlob::blobSignature
)),
267 CssmData::wrap(blob
->publicAclBlob(), blob
->publicAclBlobLength() + blob
->cryptoBlobLength())
269 CSSM_ALGORITHMS verifyAlgorithm
= CSSM_ALGID_SHA1HMAC
;
270 #if defined(COMPAT_OSX_10_0)
271 if (blob
->version() == blob
->version_MacOS_10_0
)
272 verifyAlgorithm
= CSSM_ALGID_SHA1HMAC_LEGACY
; // BSafe bug compatibility
274 VerifyMac
verifier(Server::csp(), verifyAlgorithm
);
275 verifier
.key(mSigningKey
);
276 verifier
.verify(signChunk
, 2, CssmData::wrap(blob
->blobSignature
));
278 // all checks out; start extracting fields
279 if (privateAclBlob
) {
280 // extract private ACL blob as a separately allocated area
281 uint32 blobLength
= decryptedBlob
.length() - sizeof(DbBlob::PrivateBlob
);
282 *privateAclBlob
= Allocator::standard().malloc(blobLength
);
283 memcpy(*privateAclBlob
, privateBlob
->privateAclBlob(), blobLength
);
286 // secrets have been established
288 Allocator::standard().free(privateBlob
);
293 // Make another DatabaseCryptoCore's operational secrets our own.
294 // Intended for keychain synchronization.
296 void DatabaseCryptoCore::importSecrets(const DatabaseCryptoCore
&src
)
298 assert(src
.isValid()); // must have called src.decodeCore() first
300 mEncryptionKey
= src
.mEncryptionKey
;
301 mSigningKey
= src
.mSigningKey
;
308 KeyBlob
*DatabaseCryptoCore::encodeKeyCore(const CssmKey
&inKey
,
309 const CssmData
&publicAcl
, const CssmData
&privateAcl
) const
311 assert(isValid()); // need our database secrets
315 Server::active().random(iv
);
317 // extract and hold some header bits the CSP does not want to see
319 uint32 heldAttributes
= key
.attributes() & managedAttributes
;
320 key
.clearAttribute(managedAttributes
);
321 key
.setAttribute(forcedAttributes
);
323 // use a CMS wrap to encrypt the key
324 WrapKey
wrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
);
325 wrap
.key(mEncryptionKey
);
326 wrap
.mode(CSSM_ALGMODE_CBCPadIV8
);
327 wrap
.padding(CSSM_PADDING_PKCS1
);
328 CssmData
ivd(iv
, sizeof(iv
)); wrap
.initVector(ivd
);
329 wrap
.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT
,
330 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM
));
332 wrap(key
, wrappedKey
, &privateAcl
);
334 // stick the held attribute bits back in
335 key
.clearAttribute(forcedAttributes
);
336 key
.setAttribute(heldAttributes
);
338 // allocate the final KeyBlob, uh, blob
339 size_t length
= sizeof(KeyBlob
) + publicAcl
.length() + wrappedKey
.length();
340 KeyBlob
*blob
= Allocator::standard().malloc
<KeyBlob
>(length
);
342 // assemble the KeyBlob
343 memset(blob
, 0, sizeof(KeyBlob
)); // fill alignment gaps
345 memcpy(blob
->iv
, iv
, sizeof(iv
));
346 blob
->header
= key
.header();
347 h2ni(blob
->header
); // endian-correct the header
348 blob
->wrappedHeader
.blobType
= wrappedKey
.blobType();
349 blob
->wrappedHeader
.blobFormat
= wrappedKey
.blobFormat();
350 blob
->wrappedHeader
.wrapAlgorithm
= wrappedKey
.wrapAlgorithm();
351 blob
->wrappedHeader
.wrapMode
= wrappedKey
.wrapMode();
352 memcpy(blob
->publicAclBlob(), publicAcl
, publicAcl
.length());
353 blob
->startCryptoBlob
= sizeof(KeyBlob
) + publicAcl
.length();
354 memcpy(blob
->cryptoBlob(), wrappedKey
.data(), wrappedKey
.length());
355 blob
->totalLength
= blob
->startCryptoBlob
+ wrappedKey
.length();
358 CssmData signChunk
[] = {
359 CssmData(blob
->data(), fieldOffsetOf(&KeyBlob::blobSignature
)),
360 CssmData(blob
->publicAclBlob(), blob
->publicAclBlobLength() + blob
->cryptoBlobLength())
362 CssmData
signature(blob
->blobSignature
, sizeof(blob
->blobSignature
));
363 GenerateMac
signer(Server::csp(), CSSM_ALGID_SHA1HMAC_LEGACY
); //@@@!!! CRUD
364 signer
.key(mSigningKey
);
365 signer
.sign(signChunk
, 2, signature
);
366 assert(signature
.length() == sizeof(blob
->blobSignature
));
368 // all done. Clean up
369 Server::csp()->allocator().free(wrappedKey
);
377 void DatabaseCryptoCore::decodeKeyCore(KeyBlob
*blob
,
378 CssmKey
&key
, void * &pubAcl
, void * &privAcl
) const
380 assert(isValid()); // need our database secrets
382 // Assemble the encrypted blob as a CSSM "wrapped key"
384 wrappedKey
.KeyHeader
= blob
->header
;
385 h2ni(wrappedKey
.KeyHeader
);
386 wrappedKey
.blobType(blob
->wrappedHeader
.blobType
);
387 wrappedKey
.blobFormat(blob
->wrappedHeader
.blobFormat
);
388 wrappedKey
.wrapAlgorithm(blob
->wrappedHeader
.wrapAlgorithm
);
389 wrappedKey
.wrapMode(blob
->wrappedHeader
.wrapMode
);
390 wrappedKey
.KeyData
= CssmData(blob
->cryptoBlob(), blob
->cryptoBlobLength());
392 // verify signature (check against corruption)
393 CssmData signChunk
[] = {
394 CssmData::wrap(blob
, fieldOffsetOf(&KeyBlob::blobSignature
)),
395 CssmData(blob
->publicAclBlob(), blob
->publicAclBlobLength() + blob
->cryptoBlobLength())
397 CSSM_ALGORITHMS verifyAlgorithm
= CSSM_ALGID_SHA1HMAC
;
398 #if defined(COMPAT_OSX_10_0)
399 if (blob
->version() == blob
->version_MacOS_10_0
)
400 verifyAlgorithm
= CSSM_ALGID_SHA1HMAC_LEGACY
; // BSafe bug compatibility
402 VerifyMac
verifier(Server::csp(), verifyAlgorithm
);
403 verifier
.key(mSigningKey
);
404 CssmData
signature(blob
->blobSignature
, sizeof(blob
->blobSignature
));
405 verifier
.verify(signChunk
, 2, signature
);
407 // extract and hold some header bits the CSP does not want to see
408 uint32 heldAttributes
= n2h(blob
->header
.attributes()) & managedAttributes
;
410 // decrypt the key using an unwrapping operation
411 UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_3DES_3KEY_EDE
);
412 unwrap
.key(mEncryptionKey
);
413 unwrap
.mode(CSSM_ALGMODE_CBCPadIV8
);
414 unwrap
.padding(CSSM_PADDING_PKCS1
);
415 CssmData
ivd(blob
->iv
, sizeof(blob
->iv
)); unwrap
.initVector(ivd
);
416 unwrap
.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT
,
417 uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_APPLE_CUSTOM
));
418 CssmData privAclData
;
419 wrappedKey
.clearAttribute(managedAttributes
); //@@@ shouldn't be needed(?)
421 KeySpec(n2h(blob
->header
.usage()),
422 (n2h(blob
->header
.attributes()) & ~managedAttributes
) | forcedAttributes
),
425 // compare retrieved key headers with blob headers (sanity check)
426 // @@@ this should probably be checked over carefully
427 CssmKey::Header
&real
= key
.header();
428 CssmKey::Header
&incoming
= blob
->header
;
431 if (real
.HeaderVersion
!= incoming
.HeaderVersion
||
432 real
.cspGuid() != incoming
.cspGuid())
433 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
434 if (real
.algorithm() != incoming
.algorithm())
435 CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM
);
437 // re-insert held bits
438 key
.header().KeyAttr
|= heldAttributes
;
440 // got a valid key: return the pieces
441 pubAcl
= blob
->publicAclBlob(); // points into blob (shared)
442 privAcl
= privAclData
; // was allocated by CSP decrypt
443 // key was set by unwrap operation
448 // Derive the blob-specific database blob encryption key from the passphrase and the salt.
450 CssmClient::Key
DatabaseCryptoCore::deriveDbMasterKey(const CssmData
&passphrase
) const
452 // derive an encryption key and IV from passphrase and salt
453 CssmClient::DeriveKey
makeKey(Server::csp(),
454 CSSM_ALGID_PKCS5_PBKDF2
, CSSM_ALGID_3DES_3KEY_EDE
, 24 * 8);
455 makeKey
.iterationCount(1000);
456 CssmData salt
= CssmData::wrap(mSalt
);
458 CSSM_PKCS5_PBKDF2_PARAMS params
;
459 params
.Passphrase
= passphrase
;
460 params
.PseudoRandomFunction
= CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1
;
461 CssmData paramData
= CssmData::wrap(params
);
462 return makeKey(¶mData
, KeySpec(CSSM_KEYUSE_ENCRYPT
| CSSM_KEYUSE_DECRYPT
,
463 CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
));
468 // Turn raw keybits into a symmetric key in the CSP
470 CssmClient::Key
DatabaseCryptoCore::makeRawKey(void *data
, size_t length
,
471 CSSM_ALGORITHMS algid
, CSSM_KEYUSE usage
)
475 key
.header().BlobType
= CSSM_KEYBLOB_RAW
;
476 key
.header().Format
= CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
;
477 key
.header().AlgorithmId
= algid
;
478 key
.header().KeyClass
= CSSM_KEYCLASS_SESSION_KEY
;
479 key
.header().KeyUsage
= usage
;
480 key
.header().KeyAttr
= 0;
481 key
.KeyData
= CssmData(data
, length
);
483 // unwrap it into the CSP (but keep it raw)
484 UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
);
485 CssmKey unwrappedKey
;
486 CssmData descriptiveData
;
488 KeySpec(CSSM_KEYUSE_ANY
, CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
),
489 unwrappedKey
, &descriptiveData
, NULL
);
490 return CssmClient::Key(Server::csp(), unwrappedKey
);