General:
Apple Platform Security support document
Security Overview
Cryptography:
DevForums tags: Security, Apple CryptoKit
Security framework documentation
Apple CryptoKit framework documentation
Common Crypto man pages — For the full list of pages, run:
% man -k 3cc
For more information about man pages, see Reading UNIX Manual Pages.
On Cryptographic Key Formats DevForums post
SecItem attributes for keys DevForums post
CryptoCompatibility sample code
Keychain:
DevForums tags: Security
Security > Keychain Items documentation
TN3137 On Mac keychain APIs and implementations
SecItem Fundamentals DevForums post
SecItem Pitfalls and Best Practices DevForums post
Investigating hard-to-reproduce keychain problems DevForums post
Smart cards and other secure tokens:
DevForums tag: CryptoTokenKit
CryptoTokenKit framework documentation
Mac-specific resources:
DevForums tags: Security Foundation, Security Interface
Security Foundation framework documentation
Security Interface framework documentation
BSD Privilege Escalation on macOS
Related:
Networking Resources — This covers high-level network security, including HTTPS and TLS.
Network Extension Resources — This covers low-level network security, including VPN and content filters.
Code Signing Resources
Notarisation Resources
Trusted Execution Resources — This includes Gatekeeper.
App Sandbox Resources
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
CryptoTokenKit
RSS for tagAccess security tokens and the cryptographic assets they store using CryptoTokenKit.
Posts under CryptoTokenKit tag
25 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hi,
when creating a CryptoTokenKit extension according to https://developer.apple.com/documentation/cryptotokenkit/authenticating-users-with-a-cryptographic-token, it is neccessary to register it under the securityagent in order to make the CTK usable before login. i.e. we want to run
sudo -u _securityagent /Applications/HostApp.app/Contents/MacOS/HostApp
However, even with the empty application the command fails with
illegal hardware instruction sudo -u _securityagent /Applications/HostApp.app/Contents/MacOS/HostApp
I see that it always crashes when the HostApp is sandboxed, but it does not work even without sandboxing (i am sharing the error report message below).
i actually noticed that when the HostApp is sandboxed and I run the above command, the extension starts to be usable even before login, even though i see the HostApp crash. The same does not happen without the sandbox
So I am curious how to in fact properly register the CTK extension under security agent? Also am not sure how to unregister it from the _securityagent
thank you for your help
Version: 1.0 (1)
Code Type: X86-64 (Native)
Parent Process: Exited process [9395]
Responsible: Terminal [399]
User ID: 92
Date/Time: 2025-03-21 18:54:03.0684 +0100
OS Version: macOS 15.3.2 (24D81)
Report Version: 12
Bridge OS Version: 9.3 (22P3060)
Anonymous UUID: 41F9918C-5BCA-01C7-59C2-3E8CFC3F8653
Sleep/Wake UUID: 8AB66C75-3C32-41D4-9BD4-887B0FB468FE
Time Awake Since Boot: 4300 seconds
Time Since Wake: 1369 seconds
System Integrity Protection: enabled
Crashed Thread: 0 Dispatch queue: WMClientWindowManager
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process: exc handler [9396]
Application Specific Signatures:
API Misuse
Thread 0 Crashed:: Dispatch queue: WMClientWindowManager
0 libxpc.dylib 0x7ff80667b2bd _xpc_api_misuse + 113
1 libxpc.dylib 0x7ff80665f0e4 xpc_connection_set_target_uid + 187
2 WindowManagement 0x7ffd0b946693 -[WMClientWindowManager _createXPCConnection] + 1011
3 WindowManagement 0x7ffd0b947361 -[WMClientWindowManager _xpcConnection] + 65
4 WindowManagement 0x7ffd0b9447c9 __31-[WMClientWindowManager stages]_block_invoke + 41
5 libdispatch.dylib 0x7ff8067af7e2 _dispatch_client_callout + 8
6 libdispatch.dylib 0x7ff8067bca2c _dispatch_lane_barrier_sync_invoke_and_complete + 60
7 WindowManagement 0x7ffd0b9446fc -[WMClientWindowManager stages] + 268
8 AppKit 0x7ff80b1fd0b7 __54-[NSWMWindowCoordinator initializeStageFramesIfNeeded]_block_invoke + 30
9 libdispatch.dylib 0x7ff8067af7e2 _dispatch_client_callout + 8
10 libdispatch.dylib 0x7ff8067b0aa2 _dispatch_once_callout + 20
11 AppKit 0x7ff80b1fd060 -[NSWMWindowCoordinator initializeStageFramesIfNeeded] + 296
12 AppKit 0x7ff80a3b3701 -[NSWindow _commonInitFrame:styleMask:backing:defer:] + 888
13 AppKit 0x7ff80a3b2f77 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1222
14 AppKit 0x7ff80a3b2aa9 -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42
15 SwiftUI 0x7ff917f321e0 0x7ff91776f000 + 8139232
16 SwiftUI 0x7ff917a8e2f2 0x7ff91776f000 + 3273458
17 SwiftUI 0x7ff917bccfba 0x7ff91776f000 + 4579258
18 SwiftUI 0x7ff917f2ca8e 0x7ff91776f000 + 8116878
19 SwiftUI 0x7ff917f24a65 0x7ff91776f000 + 8084069
20 SwiftUI 0x7ff917f21540 0x7ff91776f000 + 8070464
21 SwiftUI 0x7ff91849e9f1 0x7ff91776f000 + 13826545
22 SwiftUICore 0x7ffb13103ea5 0x7ffb12c81000 + 4730533
23 SwiftUICore 0x7ffb13102e0f 0x7ffb12c81000 + 4726287
24 SwiftUI 0x7ff91849e903 0x7ff91776f000 + 13826307
25 SwiftUI 0x7ff91849bc1c 0x7ff91776f000 + 13814812
26 AppKit 0x7ff80a54f191 -[NSApplication _doOpenUntitled] + 422
27 AppKit 0x7ff80a4efc59 __58-[NSApplication(NSAppleEventHandling) _handleAEOpenEvent:]_block_invoke + 237
28 AppKit 0x7ff80a963818 __102-[NSApplication _reopenWindowsAsNecessaryIncludingRestorableState:withFullFidelity:completionHandler:]_block_invoke + 101
29 AppKit 0x7ff80a4ef6fa __97-[NSDocumentController(NSInternal) _autoreopenDocumentsIgnoringExpendable:withCompletionHandler:]_block_invoke_3 + 148
30 AppKit 0x7ff80a4eee8f -[NSDocumentController(NSInternal) _autoreopenDocumentsIgnoringExpendable:withCompletionHandler:] + 635
31 AppKit 0x7ff80a96373d -[NSApplication _reopenWindowsAsNecessaryIncludingRestorableState:withFullFidelity:completionHandler:] + 269
32 AppKit 0x7ff80a3a6259 -[NSApplication(NSAppleEventHandling) _handleAEOpenEvent:] + 529
33 AppKit 0x7ff80a3a5eb9 -[NSApplication(NSAppleEventHandling) _handleCoreEvent:withReplyEvent:] + 679
34 Foundation 0x7ff807a4b471 -[NSAppleEventManager dispatchRawAppleEvent:withRawReply:handlerRefCon:] + 307
35 Foundation 0x7ff807a4b285 _NSAppleEventManagerGenericHandler + 80
36 AE 0x7ff80e0e4e95 0x7ff80e0da000 + 44693
37 AE 0x7ff80e0e4723 0x7ff80e0da000 + 42787
38 AE 0x7ff80e0de028 aeProcessAppleEvent + 409
39 HIToolbox 0x7ff81217b836 AEProcessAppleEvent + 55
40 AppKit 0x7ff80a39ee6a _DPSNextEvent + 1725
41 AppKit 0x7ff80adf38b8 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1290
42 AppKit 0x7ff80a38faa9 -[NSApplication run] + 610
43 AppKit 0x7ff80a362d34 NSApplicationMain + 823
44 SwiftUI 0x7ff9177a7da1 0x7ff91776f000 + 232865
45 SwiftUI 0x7ff917af0d40 0x7ff91776f000 + 3677504
46 SwiftUI 0x7ff917d8fef8 0x7ff91776f000 + 6426360
47 Crescendo CryptoTokenKit 0x10b1baf6e static HostApp.$main() + 30
48 Crescendo CryptoTokenKit 0x10b1bd2f9 main + 9 (HostApp.swift:24)
49 dyld 0x7ff8065c82cd start + 1805
During SmartCard pairing the PIN prompt enables the OK button only on user provides a PIN of 6 digits. Is there a way to submit the empty PIN in this flow, where the custom CTK is used here (the custom CTK would take care of the PIN from the custom ctk code). I was able to do an empty PIN submit once the I've paired the user successfully at login, unlock and other cli tools. Is there a way to do the same during the pairing?
Once the user has successfully paired with the SmartCard authentication with PIN, I was able to see most of the authentication flows was prompting for the PIN authentication like login, unlock, CLI tools like ssh, su etc., perhaps at few apps where it is still prompted with the Password instead of PIN examples, when I tried to launch Keychain Access app or Add a user from users&groups system setting.
Is this expected behaviour?
I'd like to implement unit tests that exercise keys made available via a persistent token interface. However, when attempting to list available tokens by passing kSecAttrAccessGroupToken as the kSecAttrAccessGroup to SecItemCopyMatching from a unit test, -34018 is returned. It succeeds without the kSecAttrAccessGroup, which makes sense given the unit test binary does not have com.apple.token Keychain Group. The Xcode UI indicates "Capabilities are not supported" for the unit test binary when attempting to add a Keychain Sharing capability to enable use of persistent tokens. This feels like a dead end but begs the question is there any way to implement unit tests to exercise a persistent token interface? It seems like the only path may be write unit tests that drive an independent app that handles the interactions with the persistent token.
I am building a MAC app using crypto token. I have previously done this successfully for iPhone.
In iPhone we found if something crashed on the token session while performing a sign (meaning the function wasn't able to return a value) the token or the keychain freezes and stopped returning keychain items at the query for keychain items it will return status 0. The only way to solve this was to reboot the iphone.
In Mac something similar is happening, a crash at internet connection level made the extension get stuck and now event after restarting the mac it does not allow connection
this query
let query: [String:Any] = [kSecAttrAccessGroup as String: kSecAttrAccessGroupToken, kSecAttrKeyClass as String : kSecAttrKeyClassPrivate,kSecClass as String : kSecClassIdentity, kSecReturnAttributes as String : kCFBooleanTrue as Any, kSecReturnRef as String: kCFBooleanTrue as Any, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnPersistentRef as String: kCFBooleanTrue as Any]
let status = SecItemCopyMatching(query as CFDictionary, &item)
print("Status: (status.description)")
This generates:
Unable to connect to com.intereidas.dniMac.mac.TKExt:DniMac even after retries.
Status: 0
Found items: 0
This does not get fixed after mac restart, how can we make the token extension work again?
When an app is trying to access identities put in the keychain by cryptotokenkit extension, the user gets asked a permission pop-up
which reads
'Token Access Request"
would like access a token provided by: "
with 2 options 'Don't allow' and 'OK'
I accidently clicked "Don't allow" and now can't access identities put in crypto token kit.
How can I reset the preference?
I try to send apdu command via smartcard with Cryptotokenkit on IOS application but got some error
in debug log
[smartcard] slot refused to allocate exclusive session for the card
"error domain=cryptotokenkit code=-2 "(null)""
for my code please see below code
// connect to the card
mngr?.getSlot(withName: slotName, reply: {
(slot:TKSmartCardSlot?) in
let card = slot?.makeSmartCard()
if card != nil {
// begin session
card?.beginSession{
( success:Bool,error:Error?) in
if success {
// Send 1st APDU
card?.send(ins: 0x84, p1: 0x00, p2: 0x00,le:8){
(data:Data?,sw:UInt16,error:Error?) in
if error != nil {
print("sendIns error:",error!)
}else{
print("Response:",data!,String(sw,radix: 16))
//String(format: "%02X", data! as CVarArg)
}
}
}else{
print("Session error:",error!)
}
}
}else{
print("No card found")
}
})
So i'm not sure what i do wrong on this
Hi Guys I try to use smart card reader with my ipad project and after trying to make init session with the card got error from cryptotokenkit
Message from debug log :
[smartcard] slot refused to allocate exclusive session for the card
"Session error: Error Domain=CryptoTokenKit Code=-2 "(null)""
// connect to the card
mngr?.getSlot(withName: slotName, reply: {
(slot:TKSmartCardSlot?) in
let card = slot?.makeSmartCard()
if card != nil {
// begin session
card?.beginSession{
( success:Bool,error:Error?) in
if success {
// Send 1st APDU
card?.send(ins: 0x84, p1: 0x00, p2: 0x00,le:8){
(data:Data?,sw:UInt16,error:Error?) in
if error != nil {
print("sendIns error:",error!)
}else{
print("Response:",data!,String(sw,radix: 16))
//String(format: "%02X", data! as CVarArg)
}
}
}else{
print("Session error:",error!)
}
}
}else{
print("No card found")
}
})
Hi,
I’m currently working on an app that uses a third-party SDK to perform smart card authentication via PKCS#11 APIs. Specifically, the app interacts with the smart card to retrieve certificates, detect the card reader, and perform encryption and decryption operations on provided data.
I’m wondering if it's possible to replace the PKCS#11 APIs and the third-party SDK with Apple's CryptoTokenKit framework. Does CryptoTokenKit provide equivalent functionality for smart card authentication, certificate management, and encryption/decryption operations?
Additionally, I’ve come across the following CryptoTokenKit documentation:
CryptoTokenKit API - TKSmartCardSlotManager Could you provide an example code or any guidance on how to implement this functionality using CryptoTokenKit, particularly for interacting with smart cards, managing certificates, and performing cryptographic operations?
Thank you for your assistance.
Hi, team.
I am exploring and learning about CryptoTokenKit's capabilities.
I would like to understand better what it means when the documentation says hardware tokens can be accessible through a network.
How would that work? Is there an example?
Is there more documentation about it available?
What is the flow?
Do we make a regular network request to fetch the keys, then create a Certificate or Password object, then store it with the regular persistence extension of CTK?
So, it would be like using CryptoKit and the keychain but using hardware's security layer?
I'm currently exploring Apple's Auth-Plugin extension and have modified the authdb to log in to a Mac device without using the default login password.
Specifically,I am replacing builtin:authenticate,privileged with a custom privileged mechanism that authenticates the user and grants desktop access based on our custom logic.
However, this approach does not unlock the user's Keychain. Since I'm bypassing the login password, the Keychain remains locked. I'm considering whether a certificate-based persistent token could be used to unlock the Keychain.
Is this approach recommended, or is there a more suitable solution, such as using CryptoTokenKit or another available API?
On macOS OS updates/reboot, CryptoTokenKit extension doesn't get loaded automatically when the system boots back. It needs another reboot to get the extension loaded and working.
After update:
% security list-smartcards
<No smart cards>
.. and there is a crash for authorizationhosthelper.arm64 in keychain layer
Thread 2 Crashed:: Dispatch queue: com.apple.security.keychain-cache-queue
0 libdispatch.dylib 0x18e2e499c dispatch_channel_cancel + 12
1 Security 0x1914ccfd0 invocation function for block in Security::KeychainCore::StorageManager::tickleKeychain(Security::KeychainCore::KeychainImpl*) + 44
2 libdispatch.dylib 0x18e2ce3e8 _dispatch_client_callout + 20
3 libdispatch.dylib 0x18e2d18ec _dispatch_continuation_pop + 600
4 libdispatch.dylib 0x18e2e57f0 _dispatch_source_latch_and_call + 420
5 libdispatch.dylib 0x18e2e43b4 _dispatch_source_invoke + 832
6 libdispatch.dylib 0x18e2d5898 _dispatch_lane_serial_drain + 368
7 libdispatch.dylib 0x18e2d6544 _dispatch_lane_invoke + 380
8 libdispatch.dylib 0x18e2e12d0 _dispatch_root_queue_drain_deferred_wlh + 288
9 libdispatch.dylib 0x18e2e0b44 _dispatch_workloop_worker_thread + 404
10 libsystem_pthread.dylib 0x18e47b00c _pthread_wqthread + 288
11 libsystem_pthread.dylib 0x18e479d28 start_wqthread + 8
Opening the parent app bundle as a Login item does not help.
A reboot sometimes fixes it but this happens frequently and causes lot of enterprise endpoints not able to authenticate.
After reboot:
% security list-smartcards
com.foo.tech.mac-device-check.SecureEnclaveTokenExtension:700D6B7E8943B529569D9CC81AC6F930
Please provide and prioritize a permanent fix/workaround for this issue. We have already reported this issue with crash and sysdiagnose logs in FB13622281 earlier this year.
Hello,
We have an application which gets our HSM certificates via TKTokenWatcher, there is a snippet:
let tokens = TKTokenWatcher()
for token in tokens.tokenIDs {
// Use our HSM certs
if token.contains("SPECIFIC_IDENTIFIER") {
let tokenQuery = [kSecClass as String: kSecClassIdentity,
kSecAttrTokenID as String: token,
kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
kSecReturnRef as String: true] as CFDictionary
var item: CFTypeRef?
let result = SecItemCopyMatching(tokenQuery as CFDictionary, &item)
if result == noErr....
Normally, result is all right, but problem occurred when we added "App Groups" entitlement. This application has to share some Defaults with other app, so they need to be in the same App Group.
So, when we added this App Group entitlement, result from the code snippet is -34018, which according to OSStatus means errSecMissingEntitlement.
Does anybody know, which entitlement has to be added, so app can be in the App Group, and at the same time it is able to get certificates?
Thank you.
I'm encountering an issue related to PCSC (PC/SC) smart card interactions on macOS 14 that I haven't experienced on earlier versions of macOS.
When sending an APDU command to generate a key pair on a smart card:
On macOS 12: The operation works as expected.
On macOS 14: The card responds with an error 66 02.
Are there any any changes to PCSC implementation in macOS 14 that might affect smart card operations?
I recently discovered that CryptokenKit (TKSmartCard.transmit) throws an ObjC exception, and thus crashes a Swift app using TKSmartCard (absent an ObjC wrapper to handle the Objc exception explicitly).
That was surprising, as there was no documentation indicating that TKSmartCard needs to be wrapped in ObjC instead being used directly from Swift. (See https://developer.apple.com/documentation/cryptotokenkit/tksmartcard/1390161-transmit) - the exception is a NSInternalInconsistencyException, which is thrown when certain codepaths are executed in a certain sequence (which indeed, leaves a TKSmartCard in an inconsistent state).
Is there a list of Frameworks that throw ObjC exceptions (and therefore need special handling by Swift when invoking methods/functions)?
I am using the CryptoTokenKit functionality to be able to perform validations on web pages that use digital certificates to ensure the user's identity, using the digital certificates included in the Spanish national electronic identity document.
I manage to use it correctly in most cases, but sometimes I get an error when trying to retrieve the previously created token. This error is fixed by restarting the phone.
I had create the Feedback Assistant with number FB14095789.
Is it possible to get the process (name, executable location) that triggers CryptoTokenKit extension security operation, such as signData or decryptData?
We are developing smart card middleware, for both Windows (minidriver) and macOS (CryptoTokenKit extension). We would like the possibility to configure various parts of our implementation based on the calling process. For example, we would like to cache PIN code in memory for particular amount of time, that is different for web browser and email client.
On Windows it can be done, since minidriver dll is loaded into the calling application process. By calling GetCurrentProcess() inside our minidriver, we can figure out what application is using it. On macOS, however, there is a single process that handles all requests from the apps, using smart cards. So getting current process info does not help. Is there a way to get calling application somehow?
Hi Team,
I have developed a smartcard driver which is working fine when inserting USB mouse, So here is the process I followed for smartcard driver:
Smartcard driver(IFdHandler) has info.plist which contains vendor Id and product ID attributes
Mentioned vendor Id and product ID of USB mouse which one is going to be connected to device(Mac) in info.plist, Build the IFDdriver and replace it to path - /usr/local/libexec/SmartCardServices/drivers/
Once Inserting USB mouse I am getting smart card pairing notification on Mac
This scenario is working fine and able to achieve following changes on Mac device -
Getting Smart card notification for pairing on Mac device
After Pairing , Password field on Login Screen changes to PIN field
But I want smartcard driver(IFDHandler) to be trigger via bluetooth connection from iPhone or android instead via USB
Is there any way to achieve This?
Reference for USB driver smart card driver - https://github.com/frankmorgner/vsmartcard/blob/master/virtualsmartcard/src/ifd-vpcd/ifd-vpcd.c
Hi Team, I have developed a smartcard driver which is working fine when inserting USB mouse,
So here is the process I followed for smartcard driver
Smartcard driver(IFdHandler) has info.plist which contains vendor Id and product ID attributes
Mentioned vendor Id and product ID of USB mouse which one is going to be connected to device(Mac) in info.plist, Build the IFDdriver and replace it to path - /usr/local/libexec/SmartCardServices/drivers/
Once Inserting USB mouse I am getting smart card pairing notification on Mac
This scenario is working fine and able to achieve following changes on Mac device -
Getting Smart card notification for pairing on Mac device
After Pairing , Password field on Login Screen changes to PIN field
But I want smartcard driver(IFDHandler) to be trigger via bluetooth connection from iPhone or android instead via USB
Is there any way to achieve This?
Reference for USB driver smart card driver - https://github.com/frankmorgner/vsmartcard/blob/master/virtualsmartcard/src/ifd-vpcd/ifd-vpcd.c
I am trying to pass smart card PIN from a custom auth plugin with tag kAuthorizationEnvironmentPassword. I added pam_smartcard.so to login stack (\etc\pam.d\login) but the changes do not take place.
# login: auth account password session
auth sufficient pam_smartcard.so
auth optional pam_krb5.so use_kcminit
auth optional pam_ntlm.so try_first_pass
auth optional pam_mount.so try_first_pass
auth required pam_opendirectory.so try_first_pass
account required pam_nologin.so
account required pam_opendirectory.so
password required pam_opendirectory.so
session required pam_launchd.so
session required pam_uwtmp.so
session optional pam_mount.so
What could possible be going wrong in this ? Also is there an API to trigger authorization_ctk from a custom auth plugin to work with smart card ?
Hello All,
I am new to iOS development and would like to detect the smart card readers connected to USB-C port on iOS (16+) devices. The smart card reader is a custom hardware and not MFi certified. So as per my understanding, I cannot use ExternalAccessory.framework without MFi certification. Correct?
How else can I achieve this? Does TKSmartCardSlotManager works for this purpose (or is it only for NFC devices?)? Is there any example for how to use this interface? I couldn't find any example for this as a starting point...
Thanks in advance.