]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/TokenLogin.cpp
Security-58286.260.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.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 os_log(TL_LOG, "secinfo TokenLoginGetLoginData");
301 secinfo("TokenLogin", "secinfo TokenLoginGetLoginData");
302
303 os_log(TL_LOG, "secerror");
304 secerror("secerror");
305
306 os_log(TL_LOG, "secwarning");
307 secwarning("secwarning");
308
309 if (!loginData || !context) {
310 os_log_error(TL_LOG, "Get login data - wrong params");
311 return errSecParam;
312 }
313
314 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(getPubKeyHash(context));
315 os_log(TL_LOG, "pubkeyhash %@", pubKeyHashHex.get());
316
317 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
318 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
319 os_log(TL_LOG, "stored data %@", storedData.get());
320
321 if (!storedData) {
322 os_log_debug(TL_LOG, "Failed to read token login plist");
323 os_log(TL_LOG, "Failed to read token login plist");
324 return errSecIO;
325 }
326
327 CFRef<CFErrorRef> error;
328 *loginData = (CFDictionaryRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
329 storedData,
330 kCFPropertyListImmutable,
331 NULL,
332 error.take());
333 if (!*loginData || CFGetTypeID(*loginData) != CFDictionaryGetTypeID()) {
334 os_log_error(TL_LOG, "Failed to deserialize unlock key data: %@", error.get());
335 return errSecParam;
336 }
337
338 return errSecSuccess;
339 }
340
341 OSStatus TokenLoginGetPin(CFDictionaryRef context, CFStringRef *pin)
342 {
343 if (!pin || !context) {
344 return errSecParam;
345 }
346 *pin = getPin(context);
347
348 return errSecSuccess;
349 }
350
351 OSStatus TokenLoginUpdateUnlockData(CFDictionaryRef context, CFStringRef password)
352 {
353 if (!context) {
354 os_log_error(TL_LOG, "Updating unlock data - wrong params");
355 return errSecParam;
356 }
357
358 CFRef<SecKeychainRef> loginKeychain;
359 OSStatus result = SecKeychainCopyLogin(loginKeychain.take());
360 if (result != errSecSuccess) {
361 os_log_error(TL_LOG, "Failed to get user keychain: %d", (int) result);
362 return result;
363 }
364
365 return SecKeychainStoreUnlockKeyWithPubKeyHash(getPubKeyHash(context), getTokenId(context), getPubKeyHashWrap(context), loginKeychain, password);
366 }
367
368 OSStatus TokenLoginCreateLoginData(CFStringRef tokenId, CFDataRef pubKeyHash, CFDataRef pubKeyHashWrap, CFDataRef unlockKey, CFDataRef scBlob)
369 {
370 if (!tokenId || !pubKeyHash || !pubKeyHashWrap || !unlockKey || !scBlob) {
371 os_log_error(TL_LOG, "Create login data - wrong params");
372 return errSecParam;
373 }
374
375 CFRef<CFDictionaryRef> ctx = makeCFDictionary(3,
376 kSecAttrTokenID, tokenId,
377 kSecAttrPublicKeyHash, pubKeyHash,
378 kSecAttrAccount, pubKeyHashWrap
379 );
380 CFRef<SecKeyRef> privKey;
381 OSStatus result = privKeyForPubKeyHash(ctx, privKey.take(), NULL);
382 if (result != errSecSuccess) {
383 os_log_error(TL_LOG, "Failed to get private key for public key hash: %d", (int) result);
384 return result;
385 }
386
387 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
388 if (!pubKey) {
389 os_log_error(TL_LOG, "Failed to get public key from private key");
390 return errSecParam;
391 }
392
393 SecKeyAlgorithm algorithms[] = {
394 kSecKeyAlgorithmECIESEncryptionStandardX963SHA512AESGCM,
395 kSecKeyAlgorithmECIESEncryptionStandardX963SHA384AESGCM,
396 kSecKeyAlgorithmECIESEncryptionStandardX963SHA256AESGCM,
397 kSecKeyAlgorithmECIESEncryptionStandardX963SHA224AESGCM,
398 kSecKeyAlgorithmECIESEncryptionStandardX963SHA1AESGCM,
399 kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM,
400 kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM,
401 kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM,
402 kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM,
403 kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM
404 };
405
406 SecKeyAlgorithm algorithm = NULL;
407 for (size_t i = 0; i < sizeof(algorithms) / sizeof(*algorithms); i++) {
408 if (SecKeyIsAlgorithmSupported(pubKey, kSecKeyOperationTypeEncrypt, algorithms[i])
409 && SecKeyIsAlgorithmSupported(privKey, kSecKeyOperationTypeDecrypt, algorithms[i])) {
410 algorithm = algorithms[i];
411 break;
412 }
413 }
414 if (algorithm == NULL) {
415 os_log_error(TL_LOG, "Failed to find supported wrap algorithm");
416 return errSecParam;
417 }
418
419 CFRef<CFErrorRef> error;
420 CFRef<CFDataRef> wrappedUnlockKey = SecKeyCreateEncryptedData(pubKey, algorithm, unlockKey, error.take());
421 if (!wrappedUnlockKey) {
422 os_log_error(TL_LOG, "Failed to wrap unlock key: %@", error.get());
423 return errSecParam;
424 }
425
426 CFRef<CFDictionaryRef> loginData = makeCFDictionary(4,
427 kSecAttrService, algorithm,
428 kSecAttrPublicKeyHash, pubKeyHashWrap,
429 kSecValueData, wrappedUnlockKey.get(),
430 kSecClassKey, scBlob
431 );
432 return TokenLoginStoreUnlockData(ctx, loginData);
433 }
434
435 OSStatus TokenLoginStoreUnlockData(CFDictionaryRef context, CFDictionaryRef loginData)
436 {
437 os_log(TL_LOG, "Storing unlock data");
438
439 CFRef<CFErrorRef> error;
440 CFRef<CFDataRef> data = CFPropertyListCreateData(kCFAllocatorDefault,
441 loginData,
442 kCFPropertyListBinaryFormat_v1_0,
443 0,
444 error.take());
445 if (!data) {
446 os_log_error(TL_LOG, "Failed to create unlock data: %@", error.get());
447 return errSecInternal;
448 }
449 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(getPubKeyHash(context));
450 os_log(TL_LOG, "Pubkeyhash %@", pubKeyHashHex.get());
451
452 CFPreferencesSetValue(pubKeyHashHex, data, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
453 os_log(TL_LOG, "Pubkeyhash %@", pubKeyHashHex.get());
454
455 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
456 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
457 os_log(TL_LOG, "Stored data %@", storedData.get());
458
459 if (!storedData || !CFEqual(storedData, data)) {
460 os_log_error(TL_LOG, "Failed to write token login plist");
461 return errSecIO;
462 }
463 os_log(TL_LOG, "Original data %@. Everything is OK", data.get());
464
465 return errSecSuccess;
466 }
467
468 OSStatus TokenLoginDeleteUnlockData(CFDataRef pubKeyHash)
469 {
470 CFRef<CFStringRef> pubKeyHashHex = cfDataToHex(pubKeyHash);
471 CFPreferencesSetValue(pubKeyHashHex, NULL, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
472 CFPreferencesSynchronize(kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
473 CFRef<CFDataRef> storedData = (CFDataRef)CFPreferencesCopyValue(pubKeyHashHex, kSecTokenLoginDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
474
475 if (storedData) {
476 os_log_error(TL_LOG, "Failed to remove unlock data");
477 return errSecIO;
478 }
479
480 return errSecSuccess;
481 }
482
483 OSStatus TokenLoginGetScBlob(CFDataRef pubKeyHashWrap, CFStringRef tokenId, CFStringRef password, CFDataRef *scBlob)
484 {
485 if (scBlob == NULL || password == NULL || pubKeyHashWrap == NULL || tokenId == NULL) {
486 os_log_error(TL_LOG, "TokenLoginGetScBlob wrong params");
487 return errSecParam;
488 }
489
490 CFRef<CFDictionaryRef> ctx = makeCFDictionary(2,
491 kSecAttrTokenID, tokenId,
492 kSecAttrAccount, pubKeyHashWrap
493 );
494
495 CFRef<SecKeyRef> privKey;
496 OSStatus retval = privKeyForPubKeyHash(ctx, privKey.take(), NULL);
497 if (retval != errSecSuccess) {
498 os_log_error(TL_LOG, "TokenLoginGetScBlob failed to get private key for public key hash: %d", (int) retval);
499 return retval;
500 }
501
502 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
503 if (!pubKey) {
504 os_log_error(TL_LOG, "TokenLoginGetScBlob no pubkey");
505 return errSecInternal;
506 }
507
508 CFRef<CFDictionaryRef> attributes = SecKeyCopyAttributes(pubKey);
509 if (!attributes) {
510 os_log_error(TL_LOG, "TokenLoginGetScBlob no attributes");
511 return errSecInternal;
512 }
513
514 aks_smartcard_mode_t mode;
515 CFRef<CFStringRef> type = (CFStringRef)CFDictionaryGetValue(attributes, kSecAttrKeyType);
516 if (CFEqual(type, kSecAttrKeyTypeRSA))
517 mode = AKS_SMARTCARD_MODE_RSA;
518 else if (CFEqual(type, kSecAttrKeyTypeEC))
519 mode = AKS_SMARTCARD_MODE_ECDH;
520 else {
521 os_log_error(TL_LOG, "TokenLoginGetScBlob bad type");
522 return errSecNotAvailable;
523 }
524
525 CFRef<CFDataRef> publicBytes = SecKeyCopyExternalRepresentation(pubKey, NULL);
526 if (!publicBytes) {
527 os_log_error(TL_LOG, "TokenLoginGetScBlob cannot get public bytes");
528 return retval;
529 }
530
531 CFIndex maxLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(password), kCFStringEncodingUTF8) + 1;
532 char* buf = (char*)malloc(maxLength);
533 if (buf == NULL) {
534 os_log_error(TL_LOG, "TokenLoginGetScBlob no mem for buffer");
535 return retval;
536 }
537
538 if (CFStringGetCString(password, buf, maxLength, kCFStringEncodingUTF8) == FALSE) {
539 os_log_error(TL_LOG, "TokenLoginGetScBlob no pwd cstr");
540 free(buf);
541 return retval;
542 }
543
544 void *sc_blob = NULL;
545 size_t sc_len = 0;
546 aks_smartcard_unregister(session_keybag_handle); // just to be sure no previous registration exist
547 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);
548 free(buf);
549 os_log_debug(TL_LOG, "TokenLoginGetScBlob register result %d", aks_retval);
550
551 if (sc_blob) {
552 *scBlob = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)sc_blob, (CFIndex)sc_len);
553 free(sc_blob);
554 }
555 return aks_retval;
556 }
557
558 // context = data wrapped in password variable, loginData = dictionary from stored plist
559 OSStatus TokenLoginUnlockKeybag(CFDictionaryRef context, CFDictionaryRef loginData)
560 {
561 if (!loginData || !context) {
562 return errSecParam;
563 }
564
565 CFDataRef scBlob = (CFDataRef)CFDictionaryGetValue(loginData, kSecClassKey);
566 if (scBlob == NULL) {
567 os_log_error(TL_LOG, "Failed to get scblob");
568 return errSecInternal;
569 }
570
571 CFDataRef pubKeyWrapFromPlist = (CFDataRef)CFDictionaryGetValue(loginData, kSecAttrPublicKeyHash);
572 if (pubKeyWrapFromPlist == NULL) {
573 os_log_error(TL_LOG, "Failed to get wrapkey");
574 return errSecInternal;
575 }
576
577 CFRef<CFDictionaryRef> ctx = makeCFDictionary(4,
578 kSecAttrTokenID, getTokenId(context),
579 kSecAttrService, getPin(context),
580 kSecAttrPublicKeyHash, getPubKeyHash(context),
581 kSecAttrAccount, pubKeyWrapFromPlist
582 );
583
584 CFRef<CFErrorRef> error;
585 CFRef<SecKeyRef> privKey;
586 CFRef<CFTypeRef> LAContext;
587 OSStatus retval = privKeyForPubKeyHash(ctx, privKey.take(), LAContext.take());
588 if (retval != errSecSuccess) {
589 os_log_error(TL_LOG, "Failed to get private key for public key hash: %d", (int) retval);
590 return retval;
591 }
592
593 CFRef<SecKeyRef> pubKey = SecKeyCopyPublicKey(privKey);
594 if (!pubKey) {
595 os_log_error(TL_LOG, "Failed to get pubkey");
596 return retval;
597 }
598
599 CFRef<CFDictionaryRef> attributes = SecKeyCopyAttributes(pubKey);
600 if (!attributes) {
601 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no attributes");
602 return errSecInternal;
603 }
604
605 aks_smartcard_mode_t mode;
606 CFStringRef type = (CFStringRef)CFDictionaryGetValue(attributes, kSecAttrKeyType);
607 if (CFEqual(type, kSecAttrKeyTypeRSA))
608 mode = AKS_SMARTCARD_MODE_RSA;
609 else if (CFEqual(type, kSecAttrKeyTypeEC))
610 mode = AKS_SMARTCARD_MODE_ECDH;
611 else {
612 os_log_error(TL_LOG, "TokenLoginUnlockKeybag bad type");
613 return errSecNotAvailable;
614 }
615
616 void *scChallenge = NULL;
617 size_t scChallengeLen = 0;
618 int res = aks_smartcard_request_unlock(session_keybag_handle, (uint8_t *)CFDataGetBytePtr(scBlob), (size_t)CFDataGetLength(scBlob), &scChallenge, &scChallengeLen);
619 if (res != 0) {
620 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot request unlock: %x", res);
621 return errSecInternal;
622 }
623 const void *scUsk = NULL;
624 size_t scUskLen = 0;
625 res = aks_smartcard_get_sc_usk(scChallenge, scChallengeLen, &scUsk, &scUskLen);
626
627 if (res != 0 || scUsk == NULL) {
628 free(scChallenge);
629 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot get usk: %x", res);
630 return errSecInternal;
631 }
632
633 CFRef<CFTypeRef> wrappedUsk;
634 if (mode == AKS_SMARTCARD_MODE_ECDH) {
635 const void *ecPub = NULL;
636 size_t ecPubLen = 0;
637 res = aks_smartcard_get_ec_pub(scChallenge, scChallengeLen, &ecPub, &ecPubLen);
638 if (res != 0 || ecPub == NULL) {
639 free(scChallenge);
640 os_log_error(TL_LOG, "TokenLoginUnlockKeybag cannot get ecpub: %x", res);
641 return errSecInternal;
642 }
643 wrappedUsk = CFDataCreateMutable(kCFAllocatorDefault, ecPubLen + scUskLen);
644 if (!wrappedUsk) {
645 free(scChallenge);
646 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no mem for ecpubusk");
647 return errSecInternal;
648 }
649 CFDataAppendBytes((CFMutableDataRef)wrappedUsk.get(), (const UInt8 *)ecPub, (CFIndex)ecPubLen);
650 CFDataAppendBytes((CFMutableDataRef)wrappedUsk.get(), (const UInt8 *)scUsk, (CFIndex)scUskLen);
651 } else {
652 wrappedUsk = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)scUsk, (CFIndex)scUskLen);
653 }
654 free(scChallenge);
655 // decrypt Usk with SC
656 CFRef<CFDataRef> unwrappedUsk = SecKeyCreateDecryptedData(privKey,
657 mode == AKS_SMARTCARD_MODE_RSA ? kSecKeyAlgorithmRSAEncryptionOAEPSHA256 : kSecKeyAlgorithmECIESEncryptionAKSSmartCard,
658 (CFDataRef)wrappedUsk.get(),
659 error.take());
660 if (!unwrappedUsk) {
661 os_log_error(TL_LOG, "TokenLoginUnlockKeybag failed to unwrap blob: %{public}@", error.get());
662 return errSecInternal;
663 }
664
665 void *scNewBlob = NULL;
666 size_t scNewLen = 0;
667 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);
668 if (scNewBlob) {
669 CFRef<CFDataRef> newBlobData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)scNewBlob, (CFIndex)scNewLen);
670 free(scNewBlob);
671 CFRef<CFMutableDictionaryRef> newDict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 4, loginData);
672 if (newDict) {
673 CFDictionarySetValue(newDict, kSecClassKey, newBlobData.get());
674 TokenLoginStoreUnlockData(context, newDict);
675 }
676 } else {
677 os_log_error(TL_LOG, "TokenLoginUnlockKeybag no new scblob received: %d", res);
678 }
679 return res;
680 }