2 * Copyright (c) 2016 Apple 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@
24 #include "TokenLogin.h"
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>
35 #include <libaks_smartcard.h>
38 #include <ctkclient.h>
39 #include <coreauthd_spi.h>
42 static os_log_t
TOKEN_LOG_DEFAULT() {
43 static dispatch_once_t once
;
45 dispatch_once(&once
, ^{ log
= os_log_create("com.apple.security", "tokenlogin"); });
48 #define TL_LOG TOKEN_LOG_DEFAULT()
50 #define kSecTokenLoginDomain CFSTR("com.apple.security.tokenlogin")
52 static CFStringRef CF_RETURNS_RETAINED
cfDataToHex(CFDataRef bin
)
54 size_t len
= CFDataGetLength(bin
) * 2;
55 CFMutableStringRef str
= CFStringCreateMutable(NULL
, len
);
57 static const char* digits
[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
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);
67 static CFStringRef
getPin(CFDictionaryRef context
)
73 CFStringRef pin
= (CFStringRef
)CFDictionaryGetValue(context
, kSecAttrService
);
74 if (!pin
|| CFGetTypeID(pin
) != CFStringGetTypeID()) {
80 static CFStringRef
getTokenId(CFDictionaryRef context
)
86 CFStringRef tokenId
= (CFStringRef
)CFDictionaryGetValue(context
, kSecAttrTokenID
);
87 if (!tokenId
|| CFGetTypeID(tokenId
) != CFStringGetTypeID()) {
88 os_log_debug(TL_LOG
, "Invalid tokenId");
94 static CFDataRef
getPubKeyHash(CFDictionaryRef context
)
100 CFDataRef pubKeyHash
= (CFDataRef
)CFDictionaryGetValue(context
, kSecAttrPublicKeyHash
);
101 if (!pubKeyHash
|| CFGetTypeID(pubKeyHash
) != CFDataGetTypeID()) {
102 os_log_debug(TL_LOG
, "Invalid pubkeyhash");
108 static CFDataRef
getPubKeyHashWrap(CFDictionaryRef context
)
114 CFDataRef pubKeyHashWrap
= (CFDataRef
)CFDictionaryGetValue(context
, kSecAttrAccount
);
115 if (!pubKeyHashWrap
|| CFGetTypeID(pubKeyHashWrap
) != CFDataGetTypeID()) {
116 os_log_debug(TL_LOG
, "Invalid pubkeyhashwrap");
119 return pubKeyHashWrap
;
122 static OSStatus
privKeyForPubKeyHash(CFDictionaryRef context
, SecKeyRef
*privKey
, CFTypeRef
*laCtx
)
125 os_log_error(TL_LOG
, "private key for pubkeyhash wrong params");
129 CFRef
<CFMutableDictionaryRef
> tokenAttributes
= makeCFMutableDictionary(1, kSecAttrTokenID
, getTokenId(context
));
130 CFRef
<CFErrorRef
> error
;
132 CFStringRef pin
= getPin(context
);
134 CFRef
<CFTypeRef
> LAContext
= LACreateNewContextWithACMContext(NULL
, error
.take());
136 os_log_error(TL_LOG
, "Failed to LA Context: %@", error
.get());
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());
146 CFDictionarySetValue(tokenAttributes
, kSecUseCredentialReference
, externalizedContext
.get());
147 CFDictionarySetValue(tokenAttributes
, CFSTR("PIN"), pin
);
150 CFRef
<TKTokenRef
> token
= TKTokenCreate(tokenAttributes
, error
.take());
152 os_log_error(TL_LOG
, "Failed to create token: %@", error
.get());
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());
162 CFDataRef desiredHash
= getPubKeyHashWrap(context
);
164 os_log_error(TL_LOG
, "No wrap key in context");
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
);
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
);
191 OSStatus
TokenLoginGetContext(const void *base64TokenLoginData
, UInt32 base64TokenLoginDataLength
, CFDictionaryRef
*context
)
193 if (!base64TokenLoginData
|| !context
) {
194 os_log_error(TL_LOG
, "Get login context - wrong params");
198 // Token data are base64 encoded in password.
199 size_t dataLen
= SecBase64Decode((const char *)base64TokenLoginData
, base64TokenLoginDataLength
, NULL
, 0);
201 os_log_debug(TL_LOG
, "Invalid base64 encoded token data");
205 CFRef
<CFMutableDataRef
> data
= CFDataCreateMutable(kCFAllocatorDefault
, dataLen
);
206 dataLen
= SecBase64Decode((const char *)base64TokenLoginData
, base64TokenLoginDataLength
, CFDataGetMutableBytePtr(data
), dataLen
);
208 os_log_error(TL_LOG
, "Invalid base64 encoded token data");
211 CFDataSetLength(data
, dataLen
);
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
,
217 kCFPropertyListImmutable
,
220 if (!*context
|| CFGetTypeID(*context
) != CFDictionaryGetTypeID()) {
221 os_log_error(TL_LOG
, "Invalid token login data property list, %@", error
.get());
225 if (!getPin(*context
) || !getTokenId(*context
) || !getPubKeyHash(*context
) || !getPubKeyHashWrap(*context
)) {
226 os_log_error(TL_LOG
, "Invalid token login data context, %@", error
.get());
230 return errSecSuccess
;
233 OSStatus
TokenLoginGetUnlockKey(CFDictionaryRef context
, CFDataRef
*unlockKey
)
235 if (!context
|| !unlockKey
) {
236 os_log_error(TL_LOG
, "Get unlock key - wrong params");
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
);
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");
252 SecKeyAlgorithm algorithm
= (SecKeyAlgorithm
)CFDictionaryGetValue(loginData
, kSecAttrService
);
254 os_log_error(TL_LOG
, "Algorithm not found in unlock key data");
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
);
266 CFRef
<SecKeyRef
> pubKey
= SecKeyCopyPublicKey(privKey
);
268 os_log_error(TL_LOG
, "Failed to get public key from private key");
271 CFRef
<CFErrorRef
> error
;
272 *unlockKey
= SecKeyCreateDecryptedData(privKey
,
277 os_log_error(TL_LOG
, "Failed to unwrap unlock key: %@", error
.get());
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
));
289 CFRef
<CFMutableDictionaryRef
> newDict
= CFDictionaryCreateMutableCopy(kCFAllocatorDefault
, 4, loginData
);
291 CFDictionarySetValue(newDict
, kSecValueData
, reWrappedUnlockKey
);
292 TokenLoginStoreUnlockData(context
, newDict
);
295 return errSecSuccess
;
298 OSStatus
TokenLoginGetLoginData(CFDictionaryRef context
, CFDictionaryRef
*loginData
)
300 os_log(TL_LOG
, "secinfo TokenLoginGetLoginData");
301 secinfo("TokenLogin", "secinfo TokenLoginGetLoginData");
303 os_log(TL_LOG
, "secerror");
304 secerror("secerror");
306 os_log(TL_LOG
, "secwarning");
307 secwarning("secwarning");
309 if (!loginData
|| !context
) {
310 os_log_error(TL_LOG
, "Get login data - wrong params");
314 CFRef
<CFStringRef
> pubKeyHashHex
= cfDataToHex(getPubKeyHash(context
));
315 os_log(TL_LOG
, "pubkeyhash %@", pubKeyHashHex
.get());
317 CFPreferencesSynchronize(kSecTokenLoginDomain
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
318 CFRef
<CFDataRef
> storedData
= (CFDataRef
)CFPreferencesCopyValue(pubKeyHashHex
, kSecTokenLoginDomain
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
319 os_log(TL_LOG
, "stored data %@", storedData
.get());
322 os_log_debug(TL_LOG
, "Failed to read token login plist");
323 os_log(TL_LOG
, "Failed to read token login plist");
327 CFRef
<CFErrorRef
> error
;
328 *loginData
= (CFDictionaryRef
)CFPropertyListCreateWithData(kCFAllocatorDefault
,
330 kCFPropertyListImmutable
,
333 if (!*loginData
|| CFGetTypeID(*loginData
) != CFDictionaryGetTypeID()) {
334 os_log_error(TL_LOG
, "Failed to deserialize unlock key data: %@", error
.get());
338 return errSecSuccess
;
341 OSStatus
TokenLoginGetPin(CFDictionaryRef context
, CFStringRef
*pin
)
343 if (!pin
|| !context
) {
346 *pin
= getPin(context
);
348 return errSecSuccess
;
351 OSStatus
TokenLoginUpdateUnlockData(CFDictionaryRef context
, CFStringRef password
)
354 os_log_error(TL_LOG
, "Updating unlock data - wrong params");
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
);
365 return SecKeychainStoreUnlockKeyWithPubKeyHash(getPubKeyHash(context
), getTokenId(context
), getPubKeyHashWrap(context
), loginKeychain
, password
);
368 OSStatus
TokenLoginCreateLoginData(CFStringRef tokenId
, CFDataRef pubKeyHash
, CFDataRef pubKeyHashWrap
, CFDataRef unlockKey
, CFDataRef scBlob
)
370 if (!tokenId
|| !pubKeyHash
|| !pubKeyHashWrap
|| !unlockKey
|| !scBlob
) {
371 os_log_error(TL_LOG
, "Create login data - wrong params");
375 CFRef
<CFDictionaryRef
> ctx
= makeCFDictionary(3,
376 kSecAttrTokenID
, tokenId
,
377 kSecAttrPublicKeyHash
, pubKeyHash
,
378 kSecAttrAccount
, pubKeyHashWrap
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
);
387 CFRef
<SecKeyRef
> pubKey
= SecKeyCopyPublicKey(privKey
);
389 os_log_error(TL_LOG
, "Failed to get public key from private key");
393 SecKeyAlgorithm algorithms
[] = {
394 kSecKeyAlgorithmECIESEncryptionStandardX963SHA512AESGCM
,
395 kSecKeyAlgorithmECIESEncryptionStandardX963SHA384AESGCM
,
396 kSecKeyAlgorithmECIESEncryptionStandardX963SHA256AESGCM
,
397 kSecKeyAlgorithmECIESEncryptionStandardX963SHA224AESGCM
,
398 kSecKeyAlgorithmECIESEncryptionStandardX963SHA1AESGCM
,
399 kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM
,
400 kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM
,
401 kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM
,
402 kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM
,
403 kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM
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
];
414 if (algorithm
== NULL
) {
415 os_log_error(TL_LOG
, "Failed to find supported wrap algorithm");
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());
426 CFRef
<CFDictionaryRef
> loginData
= makeCFDictionary(4,
427 kSecAttrService
, algorithm
,
428 kSecAttrPublicKeyHash
, pubKeyHashWrap
,
429 kSecValueData
, wrappedUnlockKey
.get(),
432 return TokenLoginStoreUnlockData(ctx
, loginData
);
435 OSStatus
TokenLoginStoreUnlockData(CFDictionaryRef context
, CFDictionaryRef loginData
)
437 os_log(TL_LOG
, "Storing unlock data");
439 CFRef
<CFErrorRef
> error
;
440 CFRef
<CFDataRef
> data
= CFPropertyListCreateData(kCFAllocatorDefault
,
442 kCFPropertyListBinaryFormat_v1_0
,
446 os_log_error(TL_LOG
, "Failed to create unlock data: %@", error
.get());
447 return errSecInternal
;
449 CFRef
<CFStringRef
> pubKeyHashHex
= cfDataToHex(getPubKeyHash(context
));
450 os_log(TL_LOG
, "Pubkeyhash %@", pubKeyHashHex
.get());
452 CFPreferencesSetValue(pubKeyHashHex
, data
, kSecTokenLoginDomain
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
453 os_log(TL_LOG
, "Pubkeyhash %@", pubKeyHashHex
.get());
455 CFPreferencesSynchronize(kSecTokenLoginDomain
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
456 CFRef
<CFDataRef
> storedData
= (CFDataRef
)CFPreferencesCopyValue(pubKeyHashHex
, kSecTokenLoginDomain
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
457 os_log(TL_LOG
, "Stored data %@", storedData
.get());
459 if (!storedData
|| !CFEqual(storedData
, data
)) {
460 os_log_error(TL_LOG
, "Failed to write token login plist");
463 os_log(TL_LOG
, "Original data %@. Everything is OK", data
.get());
465 return errSecSuccess
;
468 OSStatus
TokenLoginDeleteUnlockData(CFDataRef pubKeyHash
)
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
);
476 os_log_error(TL_LOG
, "Failed to remove unlock data");
480 return errSecSuccess
;
483 OSStatus
TokenLoginGetScBlob(CFDataRef pubKeyHashWrap
, CFStringRef tokenId
, CFStringRef password
, CFDataRef
*scBlob
)
485 if (scBlob
== NULL
|| password
== NULL
|| pubKeyHashWrap
== NULL
|| tokenId
== NULL
) {
486 os_log_error(TL_LOG
, "TokenLoginGetScBlob wrong params");
490 CFRef
<CFDictionaryRef
> ctx
= makeCFDictionary(2,
491 kSecAttrTokenID
, tokenId
,
492 kSecAttrAccount
, pubKeyHashWrap
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
);
502 CFRef
<SecKeyRef
> pubKey
= SecKeyCopyPublicKey(privKey
);
504 os_log_error(TL_LOG
, "TokenLoginGetScBlob no pubkey");
505 return errSecInternal
;
508 CFRef
<CFDictionaryRef
> attributes
= SecKeyCopyAttributes(pubKey
);
510 os_log_error(TL_LOG
, "TokenLoginGetScBlob no attributes");
511 return errSecInternal
;
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
;
521 os_log_error(TL_LOG
, "TokenLoginGetScBlob bad type");
522 return errSecNotAvailable
;
525 CFRef
<CFDataRef
> publicBytes
= SecKeyCopyExternalRepresentation(pubKey
, NULL
);
527 os_log_error(TL_LOG
, "TokenLoginGetScBlob cannot get public bytes");
531 CFIndex maxLength
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(password
), kCFStringEncodingUTF8
) + 1;
532 char* buf
= (char*)malloc(maxLength
);
534 os_log_error(TL_LOG
, "TokenLoginGetScBlob no mem for buffer");
538 if (CFStringGetCString(password
, buf
, maxLength
, kCFStringEncodingUTF8
) == FALSE
) {
539 os_log_error(TL_LOG
, "TokenLoginGetScBlob no pwd cstr");
544 void *sc_blob
= NULL
;
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
);
549 os_log_debug(TL_LOG
, "TokenLoginGetScBlob register result %d", aks_retval
);
552 *scBlob
= CFDataCreate(kCFAllocatorDefault
, (const UInt8
*)sc_blob
, (CFIndex
)sc_len
);
558 // context = data wrapped in password variable, loginData = dictionary from stored plist
559 OSStatus
TokenLoginUnlockKeybag(CFDictionaryRef context
, CFDictionaryRef loginData
)
561 if (!loginData
|| !context
) {
565 CFDataRef scBlob
= (CFDataRef
)CFDictionaryGetValue(loginData
, kSecClassKey
);
566 if (scBlob
== NULL
) {
567 os_log_error(TL_LOG
, "Failed to get scblob");
568 return errSecInternal
;
571 CFDataRef pubKeyWrapFromPlist
= (CFDataRef
)CFDictionaryGetValue(loginData
, kSecAttrPublicKeyHash
);
572 if (pubKeyWrapFromPlist
== NULL
) {
573 os_log_error(TL_LOG
, "Failed to get wrapkey");
574 return errSecInternal
;
577 CFRef
<CFDictionaryRef
> ctx
= makeCFDictionary(4,
578 kSecAttrTokenID
, getTokenId(context
),
579 kSecAttrService
, getPin(context
),
580 kSecAttrPublicKeyHash
, getPubKeyHash(context
),
581 kSecAttrAccount
, pubKeyWrapFromPlist
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
);
593 CFRef
<SecKeyRef
> pubKey
= SecKeyCopyPublicKey(privKey
);
595 os_log_error(TL_LOG
, "Failed to get pubkey");
599 CFRef
<CFDictionaryRef
> attributes
= SecKeyCopyAttributes(pubKey
);
601 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag no attributes");
602 return errSecInternal
;
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
;
612 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag bad type");
613 return errSecNotAvailable
;
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
);
620 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag cannot request unlock: %x", res
);
621 return errSecInternal
;
623 const void *scUsk
= NULL
;
625 res
= aks_smartcard_get_sc_usk(scChallenge
, scChallengeLen
, &scUsk
, &scUskLen
);
627 if (res
!= 0 || scUsk
== NULL
) {
629 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag cannot get usk: %x", res
);
630 return errSecInternal
;
633 CFRef
<CFTypeRef
> wrappedUsk
;
634 if (mode
== AKS_SMARTCARD_MODE_ECDH
) {
635 const void *ecPub
= NULL
;
637 res
= aks_smartcard_get_ec_pub(scChallenge
, scChallengeLen
, &ecPub
, &ecPubLen
);
638 if (res
!= 0 || ecPub
== NULL
) {
640 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag cannot get ecpub: %x", res
);
641 return errSecInternal
;
643 wrappedUsk
= CFDataCreateMutable(kCFAllocatorDefault
, ecPubLen
+ scUskLen
);
646 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag no mem for ecpubusk");
647 return errSecInternal
;
649 CFDataAppendBytes((CFMutableDataRef
)wrappedUsk
.get(), (const UInt8
*)ecPub
, (CFIndex
)ecPubLen
);
650 CFDataAppendBytes((CFMutableDataRef
)wrappedUsk
.get(), (const UInt8
*)scUsk
, (CFIndex
)scUskLen
);
652 wrappedUsk
= CFDataCreate(kCFAllocatorDefault
, (const UInt8
*)scUsk
, (CFIndex
)scUskLen
);
655 // decrypt Usk with SC
656 CFRef
<CFDataRef
> unwrappedUsk
= SecKeyCreateDecryptedData(privKey
,
657 mode
== AKS_SMARTCARD_MODE_RSA
? kSecKeyAlgorithmRSAEncryptionOAEPSHA256
: kSecKeyAlgorithmECIESEncryptionAKSSmartCard
,
658 (CFDataRef
)wrappedUsk
.get(),
661 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag failed to unwrap blob: %{public}@", error
.get());
662 return errSecInternal
;
665 void *scNewBlob
= NULL
;
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
);
669 CFRef
<CFDataRef
> newBlobData
= CFDataCreate(kCFAllocatorDefault
, (const UInt8
*)scNewBlob
, (CFIndex
)scNewLen
);
671 CFRef
<CFMutableDictionaryRef
> newDict
= CFDictionaryCreateMutableCopy(kCFAllocatorDefault
, 4, loginData
);
673 CFDictionarySetValue(newDict
, kSecClassKey
, newBlobData
.get());
674 TokenLoginStoreUnlockData(context
, newDict
);
677 os_log_error(TL_LOG
, "TokenLoginUnlockKeybag no new scblob received: %d", res
);