]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/TokenLogin.cpp
Security-59306.11.20.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / lib / TokenLogin.cpp
1 /*
2 * Copyright (c) 2016 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 #include "TokenLogin.h"
25
26 #include <Security/SecItem.h>
27 #include <Security/SecItemPriv.h>
28 #include <Security/SecKeyPriv.h>
29 #include "SecBase64P.h"
30 #include <Security/SecIdentity.h>
31 #include <Security/SecCertificatePriv.h>
32 #include <Security/SecKeychainPriv.h>
33 #include <security_utilities/cfutilities.h>
34 #include <libaks.h>
35 #include <libaks_smartcard.h>
36
37 extern "C" {
38 #include <ctkclient/ctkclient.h>
39 #include <coreauthd_spi.h>
40 }
41
42 static os_log_t TOKEN_LOG_DEFAULT() {
43 static dispatch_once_t once;
44 static os_log_t log;
45 dispatch_once(&once, ^{ log = os_log_create("com.apple.security", "tokenlogin"); });
46 return log;
47 };
48 #define TL_LOG TOKEN_LOG_DEFAULT()
49
50 #define kSecTokenLoginDomain CFSTR("com.apple.security.tokenlogin")
51
52 static CFStringRef CF_RETURNS_RETAINED cfDataToHex(CFDataRef bin)
53 {
54 size_t len = CFDataGetLength(bin) * 2;
55 CFMutableStringRef str = CFStringCreateMutable(NULL, len);
56
57 static const char* digits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
58
59 const uint8_t* data = CFDataGetBytePtr(bin);
60 for (size_t i = 0; i < CFDataGetLength(bin); i++) {
61 CFStringAppendCString(str, digits[data[i] >> 4], 1);
62 CFStringAppendCString(str, digits[data[i] & 0xf], 1);
63 }
64 return str;
65 }
66
67 static CFStringRef getPin(CFDictionaryRef context)
68 {
69 if (!context) {
70 return NULL;
71 }
72
73 CFStringRef pin = (CFStringRef)CFDictionaryGetValue(context, kSecAttrService);
74 if (!pin || CFGetTypeID(pin) != CFStringGetTypeID()) {
75 return NULL;
76 }
77 return pin;
78 }
79
80 static CFStringRef getTokenId(CFDictionaryRef context)
81 {
82 if (!context) {
83 return NULL;
84 }
85
86 CFStringRef tokenId = (CFStringRef)CFDictionaryGetValue(context, kSecAttrTokenID);
87 if (!tokenId || CFGetTypeID(tokenId) != CFStringGetTypeID()) {
88 os_log_debug(TL_LOG, "Invalid tokenId");
89 return NULL;
90 }
91 return tokenId;
92 }
93
94 static CFDataRef getPubKeyHash(CFDictionaryRef context)
95 {
96 if (!context) {
97 return NULL;
98 }
99
100 CFDataRef pubKeyHash = (CFDataRef)CFDictionaryGetValue(context, kSecAttrPublicKeyHash);
101 if (!pubKeyHash || CFGetTypeID(pubKeyHash) != CFDataGetTypeID()) {
102 os_log_debug(TL_LOG, "Invalid pubkeyhash");
103 return NULL;
104 }
105 return pubKeyHash;
106 }
107
108 static CFDataRef getPubKeyHashWrap(CFDictionaryRef context)
109 {
110 if (!context) {
111 return NULL;
112 }
113
114 CFDataRef pubKeyHashWrap = (CFDataRef)CFDictionaryGetValue(context, kSecAttrAccount);
115 if (!pubKeyHashWrap || CFGetTypeID(pubKeyHashWrap) != CFDataGetTypeID()) {
116 os_log_debug(TL_LOG, "Invalid pubkeyhashwrap");
117 return NULL;
118 }
119 return pubKeyHashWrap;
120 }
121
122 static OSStatus privKeyForPubKeyHash(CFDictionaryRef context, SecKeyRef *privKey, CFTypeRef *laCtx)
123 {
124 if (!context) {
125 os_log_error(TL_LOG, "private key for pubkeyhash wrong params");
126 return errSecParam;
127 }
128
129 CFRef<CFMutableDictionaryRef> tokenAttributes = makeCFMutableDictionary(1, kSecAttrTokenID, getTokenId(context));
130 CFRef<CFErrorRef> error;
131
132 CFStringRef pin = getPin(context);
133 if (pin) {
134 CFRef<CFTypeRef> LAContext = LACreateNewContextWithACMContext(NULL, error.take());
135 if (!LAContext) {
136 os_log_error(TL_LOG, "Failed to LA Context: %@", error.get());
137 return errSecParam;
138 }
139 if (laCtx)
140 *laCtx = (CFTypeRef)CFRetain(LAContext);
141 CFRef<CFDataRef> externalizedContext = LACopyACMContext(LAContext, error.take());
142 if (!externalizedContext) {
143 os_log_error(TL_LOG, "Failed to get externalized context: %@", error.get());
144 return errSecParam;
145 }
146 CFDictionarySetValue(tokenAttributes, kSecUseCredentialReference, externalizedContext.get());
147 CFDictionarySetValue(tokenAttributes, CFSTR("PIN"), pin);
148 }
149
150 CFRef<TKTokenRef> token = TKTokenCreate(tokenAttributes, error.take());
151 if (!token) {
152 os_log_error(TL_LOG, "Failed to create token: %@", error.get());
153 return errSecParam;
154 }
155
156 CFRef<CFArrayRef> identities = TKTokenCopyIdentities(token, TKTokenKeyUsageAny, error.take());
157 if (!identities || !CFArrayGetCount(identities)) {
158 os_log_error(TL_LOG, "No identities found for token: %@", error.get());
159 return errSecParam;
160 }
161
162 CFDataRef desiredHash = getPubKeyHashWrap(context);
163 if (!desiredHash) {
164 os_log_error(TL_LOG, "No wrap key in context");
165 return errSecParam;
166 }
167
168 CFIndex idx, count = CFArrayGetCount(identities);
169 for (idx = 0; idx < count; ++idx) {
170 SecIdentityRef identity = (SecIdentityRef)CFArrayGetValueAtIndex(identities, idx);
171 CFRef<SecCertificateRef> certificate;
172 OSStatus result = SecIdentityCopyCertificate(identity, certificate.take());
173 if (result != errSecSuccess) {
174 os_log_error(TL_LOG, "Failed to get certificate for identity: %d", (int) result);
175 continue;
176 }
177
178 CFRef<CFDataRef> identityHash = SecCertificateCopyPublicKeySHA1Digest(certificate);
179 if (identityHash && CFEqual(desiredHash, identityHash)) {
180 result = SecIdentityCopyPrivateKey(identity, privKey);
181 if (result != errSecSuccess) {
182 os_log_error(TL_LOG, "Failed to get identity private key: %d", (int) result);
183 }
184 return result;
185 }
186 }
187
188 return errSecParam;
189 }
190
191 OSStatus TokenLoginGetContext(const void *base64TokenLoginData, UInt32 base64TokenLoginDataLength, CFDictionaryRef *context)
192 {
193 if (!base64TokenLoginData || !context) {
194 os_log_error(TL_LOG, "Get login context - wrong params");
195 return errSecParam;
196 }
197
198 // Token data are base64 encoded in password.
199 size_t dataLen = SecBase64Decode((const char *)base64TokenLoginData, base64TokenLoginDataLength, NULL, 0);
200 if (!dataLen) {
201 os_log_debug(TL_LOG, "Invalid base64 encoded token data");
202 return errSecParam;
203 }
204
205 CFRef<CFMutableDataRef> data = CFDataCreateMutable(kCFAllocatorDefault, dataLen);
206 dataLen = SecBase64Decode((const char *)base64TokenLoginData, base64TokenLoginDataLength, CFDataGetMutableBytePtr(data), dataLen);
207 if (!dataLen) {
208 os_log_error(TL_LOG, "Invalid base64 encoded token data");
209 return errSecParam;
210 }
211 CFDataSetLength(data, dataLen);
212
213 // Content of the password consists of a serialized dictionary containing token ID, PIN, wrap key hash etc.
214 CFRef<CFErrorRef> error;
215 *context = (CFDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
216 data,
217 kCFPropertyListImmutable,
218 NULL,
219 error.take());
220 if (!*context || CFGetTypeID(*context) != CFDictionaryGetTypeID()) {
221 os_log_error(TL_LOG, "Invalid token login data property list, %@", error.get());
222 return errSecParam;
223 }
224
225 if (!getPin(*context) || !getTokenId(*context) || !getPubKeyHash(*context) || !getPubKeyHashWrap(*context)) {
226 os_log_error(TL_LOG, "Invalid token login data context, %@", error.get());
227 return errSecParam;
228 }
229
230 return errSecSuccess;
231 }
232
233 OSStatus TokenLoginGetUnlockKey(CFDictionaryRef context, CFDataRef *unlockKey)
234 {
235 if (!context || !unlockKey) {
236 os_log_error(TL_LOG, "Get unlock key - wrong params");
237 return errSecParam;
238 }
239
240 CFRef<CFDictionaryRef> loginData;
241 OSStatus result = TokenLoginGetLoginData(context, loginData.take());
242 if (result != errSecSuccess) {
243 os_log_error(TL_LOG, "Failed to get login data: %d", (int)result);
244 return result;
245 }
246
247 CFDataRef wrappedUnlockKey = (CFDataRef)CFDictionaryGetValue(loginData, kSecValueData);
248 if (!wrappedUnlockKey) {
249 os_log_error(TL_LOG, "Wrapped unlock key not found in unlock key data");
250 return errSecParam;
251 }
252 SecKeyAlgorithm algorithm = (SecKeyAlgorithm)CFDictionaryGetValue(loginData, kSecAttrService);
253 if (!algorithm) {
254 os_log_error(TL_LOG, "Algorithm not found in unlock key data");
255 return errSecParam;
256 }
257
258 CFRef<SecKeyRef> privKey;
259 CFRef<CFTypeRef> LAContext;
260 result = privKeyForPubKeyHash(context, privKey.take(), LAContext.take());
261 if (result != errSecSuccess) {
262 os_log_error(TL_LOG, "Failed to get private key for public key hash: %d", (int)result);
263 return result;
264 }
265
266 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
267 if (!pubKey) {
268 os_log_error(TL_LOG, "Failed to get public key from private key");
269 return errSecParam;
270 }
271 CFRef<CFErrorRef> error;
272 *unlockKey = SecKeyCreateDecryptedData(privKey,
273 algorithm,
274 wrappedUnlockKey,
275 error.take());
276 if (!*unlockKey) {
277 os_log_error(TL_LOG, "Failed to unwrap unlock key: %@", error.get());
278 return errSecDecode;
279 }
280
281 // we need to re-wrap already unwrapped data to avoid capturing and reusing communication with the smartcard
282 CFRef<CFDataRef> reWrappedUnlockKey = SecKeyCreateEncryptedData(pubKey, algorithm, *unlockKey, error.take());
283 if (!reWrappedUnlockKey) {
284 os_log_error(TL_LOG, "Failed to rewrap unlock key: %@", error.get());
285 TokenLoginDeleteUnlockData(getPubKeyHash(context));
286 return errSecParam;
287 }
288
289 CFRef<CFMutableDictionaryRef> newDict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 4, loginData);
290 if (newDict) {
291 CFDictionarySetValue(newDict, kSecValueData, reWrappedUnlockKey);
292 TokenLoginStoreUnlockData(context, newDict);
293 }
294
295 return errSecSuccess;
296 }
297
298 OSStatus TokenLoginGetLoginData(CFDictionaryRef context, CFDictionaryRef *loginData)
299 {
300 if (!loginData || !context) {
301 os_log_error(TL_LOG, "Get login data - wrong params");
302 return errSecParam;
303 }
304
305 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(getPubKeyHash(context));
306
307 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
308 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
309 if (!storedData) {
310 // this is not an error, might be a normal situation if the value does not exist
311 os_log_debug(TL_LOG, "Failed to read token login plist");
312 return errSecIO;
313 }
314
315 CFRef<CFErrorRef> error;
316 *loginData = (CFDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
317 storedData,
318 kCFPropertyListImmutable,
319 NULL,
320 error.take());
321 if (!*loginData || CFGetTypeID(*loginData) != CFDictionaryGetTypeID()) {
322 os_log_error(TL_LOG, "Failed to deserialize unlock key data: %@", error.get());
323 return errSecParam;
324 }
325
326 return errSecSuccess;
327 }
328
329 OSStatus TokenLoginGetPin(CFDictionaryRef context, CFStringRef *pin)
330 {
331 if (!pin || !context) {
332 return errSecParam;
333 }
334 *pin = getPin(context);
335
336 return errSecSuccess;
337 }
338
339 OSStatus TokenLoginUpdateUnlockData(CFDictionaryRef context, CFStringRef password)
340 {
341 if (!context) {
342 os_log_error(TL_LOG, "Updating unlock data - wrong params");
343 return errSecParam;
344 }
345
346 CFRef<SecKeychainRef> loginKeychain;
347 OSStatus result = SecKeychainCopyLogin(loginKeychain.take());
348 if (result != errSecSuccess) {
349 os_log_error(TL_LOG, "Failed to get user keychain: %d", (int) result);
350 return result;
351 }
352
353 return SecKeychainStoreUnlockKeyWithPubKeyHash(getPubKeyHash(context), getTokenId(context), getPubKeyHashWrap(context), loginKeychain, password);
354 }
355
356 OSStatus TokenLoginCreateLoginData(CFStringRef tokenId, CFDataRef pubKeyHash, CFDataRef pubKeyHashWrap, CFDataRef unlockKey, CFDataRef scBlob)
357 {
358 if (!tokenId || !pubKeyHash || !pubKeyHashWrap || !unlockKey || !scBlob) {
359 os_log_error(TL_LOG, "Create login data - wrong params");
360 return errSecParam;
361 }
362
363 CFRef<CFDictionaryRef> ctx = makeCFDictionary(3,
364 kSecAttrTokenID, tokenId,
365 kSecAttrPublicKeyHash, pubKeyHash,
366 kSecAttrAccount, pubKeyHashWrap
367 );
368 CFRef<SecKeyRef> privKey;
369 OSStatus result = privKeyForPubKeyHash(ctx, privKey.take(), NULL);
370 if (result != errSecSuccess) {
371 os_log_error(TL_LOG, "Failed to get private key for public key hash: %d", (int) result);
372 return result;
373 }
374
375 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
376 if (!pubKey) {
377 os_log_error(TL_LOG, "Failed to get public key from private key");
378 return errSecParam;
379 }
380
381 SecKeyAlgorithm algorithms[] = {
382 kSecKeyAlgorithmECIESEncryptionStandardX963SHA512AESGCM,
383 kSecKeyAlgorithmECIESEncryptionStandardX963SHA384AESGCM,
384 kSecKeyAlgorithmECIESEncryptionStandardX963SHA256AESGCM,
385 kSecKeyAlgorithmECIESEncryptionStandardX963SHA224AESGCM,
386 kSecKeyAlgorithmECIESEncryptionStandardX963SHA1AESGCM,
387 kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM,
388 kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM,
389 kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM,
390 kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM,
391 kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM
392 };
393
394 SecKeyAlgorithm algorithm = NULL;
395 for (size_t i = 0; i < sizeof(algorithms) / sizeof(*algorithms); i++) {
396 if (SecKeyIsAlgorithmSupported(pubKey, kSecKeyOperationTypeEncrypt, algorithms[i])
397 && SecKeyIsAlgorithmSupported(privKey, kSecKeyOperationTypeDecrypt, algorithms[i])) {
398 algorithm = algorithms[i];
399 break;
400 }
401 }
402 if (algorithm == NULL) {
403 os_log_error(TL_LOG, "Failed to find supported wrap algorithm");
404 return errSecParam;
405 }
406
407 CFRef<CFErrorRef> error;
408 CFRef<CFDataRef> wrappedUnlockKey = SecKeyCreateEncryptedData(pubKey, algorithm, unlockKey, error.take());
409 if (!wrappedUnlockKey) {
410 os_log_error(TL_LOG, "Failed to wrap unlock key: %@", error.get());
411 return errSecParam;
412 }
413
414 CFRef<CFDictionaryRef> loginData = makeCFDictionary(4,
415 kSecAttrService, algorithm,
416 kSecAttrPublicKeyHash, pubKeyHashWrap,
417 kSecValueData, wrappedUnlockKey.get(),
418 kSecClassKey, scBlob
419 );
420 return TokenLoginStoreUnlockData(ctx, loginData);
421 }
422
423 OSStatus TokenLoginStoreUnlockData(CFDictionaryRef context, CFDictionaryRef loginData)
424 {
425 os_log(TL_LOG, "Storing unlock data");
426
427 CFRef<CFErrorRef> error;
428 CFRef<CFDataRef> data = CFPropertyListCreateData(kCFAllocatorDefault,
429 loginData,
430 kCFPropertyListBinaryFormat_v1_0,
431 0,
432 error.take());
433 if (!data) {
434 os_log_error(TL_LOG, "Failed to create unlock data: %@", error.get());
435 return errSecInternal;
436 }
437 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(getPubKeyHash(context));
438 os_log(TL_LOG, "Pubkeyhash %@", pubKeyHashHex.get());
439
440 CFPreferencesSetValue(pubKeyHashHex, data, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
441 os_log(TL_LOG, "Pubkeyhash %@", pubKeyHashHex.get());
442
443 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
444 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
445 os_log(TL_LOG, "Stored data %@", storedData.get());
446
447 if (!storedData || !CFEqual(storedData, data)) {
448 os_log_error(TL_LOG, "Failed to write token login plist");
449 return errSecIO;
450 }
451 os_log(TL_LOG, "Original data %@. Everything is OK", data.get());
452
453 return errSecSuccess;
454 }
455
456 OSStatus TokenLoginDeleteUnlockData(CFDataRef pubKeyHash)
457 {
458 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(pubKeyHash);
459 CFPreferencesSetValue(pubKeyHashHex, NULL, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
460 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
461 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
462
463 if (storedData) {
464 os_log_error(TL_LOG, "Failed to remove unlock data");
465 return errSecIO;
466 }
467
468 return errSecSuccess;
469 }
470
471 OSStatus TokenLoginGetScBlob(CFDataRef pubKeyHashWrap, CFStringRef tokenId, CFStringRef password, CFDataRef *scBlob)
472 {
473 if (scBlob == NULL || password == NULL || pubKeyHashWrap == NULL || tokenId == NULL) {
474 os_log_error(TL_LOG, "TokenLoginGetScBlob wrong params");
475 return errSecParam;
476 }
477
478 CFRef<CFDictionaryRef> ctx = makeCFDictionary(2,
479 kSecAttrTokenID, tokenId,
480 kSecAttrAccount, pubKeyHashWrap
481 );
482
483 CFRef<SecKeyRef> privKey;
484 OSStatus retval = privKeyForPubKeyHash(ctx, privKey.take(), NULL);
485 if (retval != errSecSuccess) {
486 os_log_error(TL_LOG, "TokenLoginGetScBlob failed to get private key for public key hash: %d", (int) retval);
487 return retval;
488 }
489
490 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
491 if (!pubKey) {
492 os_log_error(TL_LOG, "TokenLoginGetScBlob no pubkey");
493 return errSecInternal;
494 }
495
496 CFRef<CFDictionaryRef> attributes = SecKeyCopyAttributes(pubKey);
497 if (!attributes) {
498 os_log_error(TL_LOG, "TokenLoginGetScBlob no attributes");
499 return errSecInternal;
500 }
501
502 aks_smartcard_mode_t mode;
503 CFRef<CFStringRef> type = (CFStringRef)CFDictionaryGetValue(attributes, kSecAttrKeyType);
504 if (CFEqual(type, kSecAttrKeyTypeRSA))
505 mode = AKS_SMARTCARD_MODE_RSA;
506 else if (CFEqual(type, kSecAttrKeyTypeEC))
507 mode = AKS_SMARTCARD_MODE_ECDH;
508 else {
509 os_log_error(TL_LOG, "TokenLoginGetScBlob bad type");
510 return errSecNotAvailable;
511 }
512
513 CFRef<CFDataRef> publicBytes = SecKeyCopyExternalRepresentation(pubKey, NULL);
514 if (!publicBytes) {
515 os_log_error(TL_LOG, "TokenLoginGetScBlob cannot get public bytes");
516 return retval;
517 }
518
519 CFIndex maxLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(password), kCFStringEncodingUTF8) + 1;
520 char* buf = (char*)malloc(maxLength);
521 if (buf == NULL) {
522 os_log_error(TL_LOG, "TokenLoginGetScBlob no mem for buffer");
523 return retval;
524 }
525
526 if (CFStringGetCString(password, buf, maxLength, kCFStringEncodingUTF8) == FALSE) {
527 os_log_error(TL_LOG, "TokenLoginGetScBlob no pwd cstr");
528 free(buf);
529 return retval;
530 }
531
532 void *sc_blob = NULL;
533 size_t sc_len = 0;
534 aks_smartcard_unregister(session_keybag_handle); // just to be sure no previous registration exist
535 kern_return_t aks_retval = aks_smartcard_register(session_keybag_handle, (uint8_t *)buf, strlen(buf), mode, (uint8_t *)CFDataGetBytePtr(publicBytes), (size_t)CFDataGetLength(publicBytes), &sc_blob, &sc_len);
536 free(buf);
537 os_log_debug(TL_LOG, "TokenLoginGetScBlob register result %d", aks_retval);
538
539 if (sc_blob) {
540 *scBlob = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)sc_blob, (CFIndex)sc_len);
541 free(sc_blob);
542 }
543 return aks_retval;
544 }
545
546 // context = data wrapped in password variable, loginData = dictionary from stored plist
547 OSStatus TokenLoginUnlockKeybag(CFDictionaryRef context, CFDictionaryRef loginData)
548 {
549 if (!loginData || !context) {
550 return errSecParam;
551 }
552
553 CFDataRef scBlob = (CFDataRef)CFDictionaryGetValue(loginData, kSecClassKey);
554 if (scBlob == NULL) {
555 os_log_error(TL_LOG, "Failed to get scblob");
556 return errSecInternal;
557 }
558
559 CFDataRef pubKeyWrapFromPlist = (CFDataRef)CFDictionaryGetValue(loginData, kSecAttrPublicKeyHash);
560 if (pubKeyWrapFromPlist == NULL) {
561 os_log_error(TL_LOG, "Failed to get wrapkey");
562 return errSecInternal;
563 }
564
565 CFRef<CFDictionaryRef> ctx = makeCFDictionary(4,
566 kSecAttrTokenID, getTokenId(context),
567 kSecAttrService, getPin(context),
568 kSecAttrPublicKeyHash, getPubKeyHash(context),
569 kSecAttrAccount, pubKeyWrapFromPlist
570 );
571
572 CFRef<CFErrorRef> error;
573 CFRef<SecKeyRef> privKey;
574 CFRef<CFTypeRef> LAContext;
575 OSStatus retval = privKeyForPubKeyHash(ctx, privKey.take(), LAContext.take());
576 if (retval != errSecSuccess) {
577 os_log_error(TL_LOG, "Failed to get private key for public key hash: %d", (int) retval);
578 return retval;
579 }
580
581 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
582 if (!pubKey) {
583 os_log_error(TL_LOG, "Failed to get pubkey");
584 return retval;
585 }
586
587 CFRef<CFDictionaryRef> attributes = SecKeyCopyAttributes(pubKey);
588 if (!attributes) {
589 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no attributes");
590 return errSecInternal;
591 }
592
593 aks_smartcard_mode_t mode;
594 CFStringRef type = (CFStringRef)CFDictionaryGetValue(attributes, kSecAttrKeyType);
595 if (CFEqual(type, kSecAttrKeyTypeRSA))
596 mode = AKS_SMARTCARD_MODE_RSA;
597 else if (CFEqual(type, kSecAttrKeyTypeEC))
598 mode = AKS_SMARTCARD_MODE_ECDH;
599 else {
600 os_log_error(TL_LOG, "TokenLoginUnlockKeybag bad type");
601 return errSecNotAvailable;
602 }
603
604 void *scChallenge = NULL;
605 size_t scChallengeLen = 0;
606 int res = aks_smartcard_request_unlock(session_keybag_handle, (uint8_t *)CFDataGetBytePtr(scBlob), (size_t)CFDataGetLength(scBlob), &scChallenge, &scChallengeLen);
607 if (res != 0) {
608 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot request unlock: %x", res);
609 return errSecInternal;
610 }
611 const void *scUsk = NULL;
612 size_t scUskLen = 0;
613 res = aks_smartcard_get_sc_usk(scChallenge, scChallengeLen, &scUsk, &scUskLen);
614
615 if (res != 0 || scUsk == NULL) {
616 free(scChallenge);
617 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot get usk: %x", res);
618 return errSecInternal;
619 }
620
621 CFRef<CFTypeRef> wrappedUsk;
622 if (mode == AKS_SMARTCARD_MODE_ECDH) {
623 const void *ecPub = NULL;
624 size_t ecPubLen = 0;
625 res = aks_smartcard_get_ec_pub(scChallenge, scChallengeLen, &ecPub, &ecPubLen);
626 if (res != 0 || ecPub == NULL) {
627 free(scChallenge);
628 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot get ecpub: %x", res);
629 return errSecInternal;
630 }
631 wrappedUsk = CFDataCreateMutable(kCFAllocatorDefault, ecPubLen + scUskLen);
632 if (!wrappedUsk) {
633 free(scChallenge);
634 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no mem for ecpubusk");
635 return errSecInternal;
636 }
637 CFDataAppendBytes((CFMutableDataRef)wrappedUsk.get(), (const UInt8 *)ecPub, (CFIndex)ecPubLen);
638 CFDataAppendBytes((CFMutableDataRef)wrappedUsk.get(), (const UInt8 *)scUsk, (CFIndex)scUskLen);
639 } else {
640 wrappedUsk = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)scUsk, (CFIndex)scUskLen);
641 }
642 free(scChallenge);
643 // decrypt Usk with SC
644 CFRef<CFDataRef> unwrappedUsk = SecKeyCreateDecryptedData(privKey,
645 mode == AKS_SMARTCARD_MODE_RSA ? kSecKeyAlgorithmRSAEncryptionOAEPSHA256 : kSecKeyAlgorithmECIESEncryptionAKSSmartCard,
646 (CFDataRef)wrappedUsk.get(),
647 error.take());
648 if (!unwrappedUsk) {
649 os_log_error(TL_LOG, "TokenLoginUnlockKeybag failed to unwrap blob: %{public}@", error.get());
650 return errSecInternal;
651 }
652
653 void *scNewBlob = NULL;
654 size_t scNewLen = 0;
655 res = aks_smartcard_unlock(session_keybag_handle, (uint8_t *)CFDataGetBytePtr(scBlob), (size_t)CFDataGetLength(scBlob), (uint8_t *)CFDataGetBytePtr(unwrappedUsk), (size_t)CFDataGetLength(unwrappedUsk), &scNewBlob, &scNewLen);
656 if (scNewBlob) {
657 CFRef<CFDataRef> newBlobData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)scNewBlob, (CFIndex)scNewLen);
658 free(scNewBlob);
659 CFRef<CFMutableDictionaryRef> newDict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 4, loginData);
660 if (newDict) {
661 CFDictionarySetValue(newDict, kSecClassKey, newBlobData.get());
662 TokenLoginStoreUnlockData(context, newDict);
663 }
664 } else {
665 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no new scblob received: %d", res);
666 }
667 return res;
668 }