CryptoTokenKit

RSS for tag

Access security tokens and the cryptographic assets they store using CryptoTokenKit.

CryptoTokenKit Documentation

Pinned Posts

Posts under CryptoTokenKit tag

22 Posts
Sort by:
Post not yet marked as solved
9 Replies
660 Views
Hello, We already submitted a feedback through the assistant about that, but I'm not sure we will ever get an answer, and it might be interesting for other people as well. On MacOS Ventura, It seems like applications using the KeyChain services are unable to see certificates provided by CryptoTokenKit smart card token drivers. In order to reproduce, you need a CryptotokenKit smart card driver appex working under Big Sur or Monterey. Install the same appex on Ventura. You'll see that Safari does not see the certificates provided by the appex, and cannot perform SSL/TLS client authentications with them. Similar symptoms can be seen with other apps (Chrome, mail clients, or even custom apps that directly use the Keychain API: token instances cannot be obtained from the app). We tested with both our own CryptoTokenKit driver (a TKSmartCard driver, which worked well with all previous MacOS versions), and the CryptoTokenKit driver from another company (Yubico). Both work on older MacOS, but not on Ventura. Has something changed in the security framework between Monterey and Ventura? Do we need to change something in our CryptoTokenKit, or is it a bug from MacOS? If it's a bug, is Apple aware of it, and will it be fixed? This is a functionality that is largely used in enterprise environments.
Posted
by idopte.
Last updated
.
Post not yet marked as solved
1 Replies
130 Views
Call to endSession() after smartcard was physically removed from device leads to application crash: terminating with uncaught exception of type NSException *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bad endSession' I think you could reproduce this with any smartCard: card.beginSession { [unowned self] isStarted, err in card.transmit(apdu) { [unowned self] response, err in card.endSession() // <- set breakpoint here } } steps to reproduce: - start application - set the breakpoint - remove device - continue
Posted
by kamenov.
Last updated
.
Post not yet marked as solved
2 Replies
956 Views
Hi, I'm trying to send commands to an external smart card reader connected to my iOS device. The first step is to get the corresponding smart card slot via TKSmartCardSlotManager. I've added the com.apple.security.smartcard entitlement but still get nil when trying to access the manager object. The console logs an error "The connection to service on pid 0 named com.apple.ctkd.slot-client was invalidated". Has anyone successfully tried this on iOS?
Posted
by oschaefer.
Last updated
.
Post not yet marked as solved
9 Replies
2.8k Views
Hi, allAccessing USB device on MAC OSX platform, the “App Sandbox”=YES and”com.apple.security.device.usb”=YES Must be increased to entitlents file.How to Implement USB Access in iOS Platform?
Posted Last updated
.
Post not yet marked as solved
0 Replies
195 Views
Hello everyone. iOS 16 added ability to connect usb devices. TKSmartCard works well with just a fast command, but if it takes more than 600ms TKSmartCard.transmit fails with communication error -2. Is there a workaround or am I use it wrong? Usage looks like that: import CryptoTokenKit func foo() { guard let manager = TKSmartCardSlotManager.default else { return } let names = manager.slotNames let smartCards = names.compactMap { manager.slotNamed($0) } .filter { $0.state == .validCard } .compactMap { $0.makeSmartCard() } guard let card = smartCards.first else { return } let apdu = Data([/*command that lasts longer than 600 ms*/]) Task { do { guard try await card.beginSession() else { print("beginSession failed") return } let res = try await card.transmit(apdu) print(res.map { String(format: "0x%02X", $0) }.joined(separator: ", ")) } catch { print(error) } } }
Posted
by kamenov.
Last updated
.
Post not yet marked as solved
1 Replies
1.1k Views
I am developing a Java app that integrates with SmartCard reader. One of the features that I try to implement is reading/setting terminal (card reader) configuration without a tag being present on the reader. This can be done by sending so called escape codes. But to enable these escape codes we need to enable them in the driver. In case of macOS this will be SmartCardServices and the file that I should edit is: /usr/libexec/SmartCardServices/drivers/ifd-ccid.bundle/Contents/Info.plist I need to set ifdDriverOptions property to 0x0001. This procedure was described in this helpful GitHub comment https://github.com/pokusew/nfc-pcsc/issues/13 I tried to follow other instructions provided there but I hit the wall with read-only file system error. I wonder if there is an idiomatic way to change these settings. Why this is important? Sending new configuration via escape command is the only way to un-brick terminal that was (by mistake) wrongly configured.
Posted
by 0xmarcin.
Last updated
.
Post not yet marked as solved
5 Replies
1.1k Views
Hi all, I have try to use CryptoTokenKit library to use my private key in Smartcard to sign data. I can find Smartcard's tokenId by using class CryptoTokenKit But I don't know how to list all items in the SmartCard and use private key in the Smartcard to sign data. And I have try use command line interface: "security". I can list smartcards by command: security list-smartcard I can list all items in smartcard by command: security export-smartcard OR command: system_profiler SPSmartCardsDataType BUT I don't know how to use private key in the smartcard to sign data by the command interface "security" Very difficult to find document about interact with SmartCard on MacOS, so please help me! Can you share document to find items in SmartCard, use private key to sign data. Thanks all!
Posted
by tuantag.
Last updated
.
Post not yet marked as solved
3 Replies
509 Views
Hi there! I am developing a PersistentToken Extension to work in iOS > 14.0. The goal is to bring Digital Certificates (Personal identities to authenticate and digital sign) to the iPhone from external HSM. I Have created an iOS app that recover certificates from the device, insert them into the keychain   let tokenDriverConfiguration = TKTokenDriver.Configuration.driverConfigurations[TokenConfigurationName]   let tokenConfiguration:TKToken.Configuration! = tokenDriverConfiguration!.addTokenConfiguration(for: TokenName)   let elems: NSMutableArray = []   for (certid,certdata) in certs {     let certificate:SecCertificate = CreateCert(str: certdata.b64)!     let tokenKeychainCertificate:TKTokenKeychainCertificate! = TKTokenKeychainCertificate(certificate:certificate, objectID:certid)     tokenKeychainCertificate.setName(name: certdata.descr)     tokenKeychainCertificate.label=certdata.certname     elems.add(tokenKeychainCertificate!)           let tokenKeychainKey:TKTokenKeychainKey! = TKTokenKeychainKey(certificate:certificate, objectID:certid)     tokenKeychainKey.setName(name: certdata.descr)     tokenKeychainKey.canSign = true     tokenKeychainKey.label=certdata.certname     tokenKeychainKey.isSuitableForLogin = true     tokenKeychainKey.keyType = kSecAttrKeyTypeRSA as String     tokenKeychainKey.canDecrypt = true     tokenKeychainKey.canPerformKeyExchange = false     elems.add(tokenKeychainKey!)   }   tokenConfiguration.keychainItems = elems as! [TKTokenKeychainItem]; } That present the certificates to other applications. I also have created the Persistent Token Extension, but when trying to use the certificates to authenticate (in a webpage por example) the breakpoints set in xcode do not work. I have set a logger that works in the application, but no log in the token section In the entitlements, I have this: <dict> <key>keychain-access-groups</key> <array> <string>com.apple.token</string> <string>com.company.test.Token</string> </array> </dict> </plist> When I try to debug with Safari, I get this error multiple times: 2022-08-12 13:14:50.616916+0200 MobileSafari[4092:8702247] [client] authentication failed repeatedly: tkid=com.company.test.Token:Token:Token, ac=<SecAccessControlRef: tkid(com.company.test.Token:Token);od(true);osgn(true)>, op=osgn I also have readed the post https://developer.apple.com/forums/thread/705433 where you tells Aekold to use a test app, but I cannot find any example or guide on the web about how to do it, may be, you can guide me. Thanks for all!
Posted
by Ivnosys.
Last updated
.
Post not yet marked as solved
3 Replies
346 Views
Good morning, I have a problem when packaging the application, the CTK (crypto token kit) is not detected by the system. If I compile in debug, it works perfectly. That could be happening? Thanks greetings
Posted
by Aekold.
Last updated
.
Post not yet marked as solved
0 Replies
421 Views
Can CTKToken framework handle mixed RSA / EC certificate chains? When using a CTKToken implementation to use certificates on a smartcard, the CTK Framework comes with strange “”supportsOperation Requests when the certificate contains an RSA key, but is signed by the EC key of the parent certificate. It basically asks if the CTKToken implementation can sign using some ECC algorithms, while using an RSA key. (No RSA algo’s are checked, so in the end no supported algorithm is found). The CTK function that is being called: (BOOL)tokenSession:(TKTokenSession *)session supportsOperation:(TKTokenOperation)operation usingKey:(TKTokenObjectID)keyObjectID algorithm:(TKTokenKeyAlgorithm *)algorithm { Shows during debugging that keyItem.keyType isEqual:(id)kSecAttrKeyTypeRSA, but only asks if we support some EC algorithm. When using a pkcs#11 implementation in stead of a CTKToken implementation with the same card, we are able to create a digital signature with Acrobat reader, with the CTKToken we are not able. We expected the CTK Framework to ask us if we can sign with the RSA key, while using some RSA algorithms. This behaviour is followed when using a certificate with RSA key that is signed by a parent certificate with RSA key This has been tested while using Belgian eID testcards with mixed RSA/EC keychain. https://github.com/Fedict/eid-mw/blob/master/cardcomm/ctkToken/BEIDToken/TokenSession.m
Posted Last updated
.
Post not yet marked as solved
7 Replies
877 Views
Buenas tardes, I have a problem with a control inside an nsalert from a thread calling it on the main thread. Everything works fine but the textfield does not respond, you write or delete and it has no response. dispatch_sync(dispatch_get_main_queue(), ^{ NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Enter PIN"]; [alert addButtonWithTitle:@"OK"]; [alert addButtonWithTitle:@"Cancel"]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alertsetAccessoryView:input]; [inputsetEditable:true]; NSInteger button = [alert runModal]; if (button == NSAlertFirstButtonReturn) { self.pin = [input stringValue]; [self.wait signal]; }else if (button == NSAlertSecondButtonReturn) { [Utils Log:@"Pin canceled!"]; [alert.window close]; [self.wait signal]; } }); If I try to create an NSWindow, it comes out as disabled and the controls can't be used either. Thanks greetings
Posted
by Aekold.
Last updated
.
Post not yet marked as solved
1 Replies
660 Views
Hello! Got some troubles with pcsc framework on Monterey 12.2.1 makavity@makbook ~ $ system_profiler SPSmartCardsDataType SmartCards:     Readers:       #01: NXP PN7462AU CCID (ATR:{length = 15, bytes = 0x3b8a800180641211111073c0c1801f})     Reader Drivers:       #01: fr.apdu.ccid.smartcardccid:1.4.34 (/usr/libexec/SmartCardServices/drivers/ifd-ccid.bundle)       #02: fr.apdu.ccid.smartcardccid:1.5.0 (/usr/local/libexec/SmartCardServices/drivers/ifd-ccid.bundle)     SmartCard Drivers:       #01: com.apple.CryptoTokenKit.pivtoken:1.0(disabled) (/System/Library/Frameworks/CryptoTokenKit.framework/PlugIns/pivtoken.appex)     Available SmartCards (keychain):         com.apple.setoken:         com.apple.setoken:aks:     Available SmartCards (token):         com.apple.setoken:         com.apple.setoken:aks: Have tried 1.5.0 version of CCID, and default version. No luck. Trying to get binary data from my smartcard, and some bytes are truncated: [16] -> [04, CB, 51, 10, 0A, 8E, 08, 5D, 7D, 90, 12, 55, 1C, DF, F6, 00] [252] <- [87, 81, F3, 02, BF, 95, CD, 53, 2B, 9C, 40, 16, B3, 1E, 32, EF, 63, 9C, F9, 63, E9, FD, C8, 77, C0, 70, 71, F5, E3, B0, B6, 6D, 4D, 41, B4, 4F, 89, C0, D2, C4, 96, 0E, 4E, 4E, BA, A8, DB, 99, D5, 47, FF, 1A, BB, D3, DF, 64, B2, 0D, D2, 92, 4C, 1A, 7F, 53, 16, 68, EF, A2, C0, 53, D9, 01, CF, 82, E0, 2D, 1D, DC, 66, 5D, CF, E7, 97, 94, B6, A5, 06, 8F, 12, 3A, B4, B5, BF, D9, 2D, 99, 8A, 57, 21, 2A, C3, 51, D2, 3F, 80, 3B, A7, 16, C2, 21, 56, 12, BE, 2D, EF, 91, 7A, D8, E6, 80, 1E, 3D, 86, 5A, 2A, 7B, 70, D0, B5, 11, 76, 5B, 6C, F6, 8D, C8, F0, 71, 94, 0A, 28, 1A, 7D, F9, 3F, C1, D8, C9, 75, 90, 79, D2, B2, 79, 8C, B5, D0, D5, 6A, 21, EB, 57, E3, DA, 8A, CE, EE, D2, 74, CA, 20, BF, BE, 33, 21, B8, AD, 53, 6B, BF, 93, 3A, E2, 2E, 10, 8E, 82, AF, 01, 9F, 71, C4, CE, AE, 45, 41, C0, 22, FA, 4C, 57, 54, BD, 22, 83, F1, 6F, 38, 23, 45, 99, 5B, A0, F3, AD, CA, 16, EC, 34, E3, 50, 7D, FA, 3D, 2B, E7, 7A, 0B, E1, E6, 53, CB, 66, AA, 6B, 6C, B5, A8, 74, 02, B8, E5, 3B, 77, 9B, C1, 8E, 08, 97, D9, 1E, FF] ERR: NoSwBytes No matter what I do, I get only 252 bytes in response, there are no SW bytes at the end. I am using pcsc-rust 2.7.0 library and code is: fn transmit(&self, data: &[u8]) -> Result<Vec<u8>, CardError> { log::trace!("[{}] -> {data:02X?}", data.len()); let mut rapdu_buf = [0; MAX_BUFFER_SIZE + 2]; let transmit_result = self.transmit(data, &mut rapdu_buf)?; log::trace!("[{}] <- {transmit_result:02X?}", transmit_result.len()); Ok(transmit_result.to_vec()) } transmit() funcition is the ffi SCardTransmit system.log System log is attached. Also, windows and linux, the same code, works fine. Is there any solution for that problem?
Posted
by makavity.
Last updated
.
Post not yet marked as solved
0 Replies
657 Views
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 On Mac Keychains DevForums post Smart cards and other secure tokens: DevForums tag: CryptoTokenKit CryptoTokenKit framework documentation Mac-specific frameworks: DevForums tags: Security Foundation, Security Interface Security Foundation framework documentation Security Interface framework documentation 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"
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
3 Replies
718 Views
Good afternoon, I have developed a persistent token extension with xcode. I have loaded the certificates with the application inside the token. The system recognizes my token and the smart card is activated, but at no time when I try to authenticate on a website, does it enter any function of the persistent token app (tokensession, signdata, etc..). I need to do the signature in an external HSM, I understood that it would fall within these functions when something needed to be done with a certificate that is inside the smartcard. Thanks greetings.
Posted
by Aekold.
Last updated
.
Post not yet marked as solved
8 Replies
1.2k Views
Hi. Working on macOS Monterey. I have created CTK extension that is used without any issues for all needed use cases (pairing the card with user, logging in to macOS, authenticating to web portal etc.) except one. When SmartCard is paired with a user, user is asked for a PIN when trying to run sudo command from a terminal. If the right PIN is entered, the command is executed normally. Now the issue is if user enters the wrong PIN and when asked for PIN again enters the correct PIN, then sudo command is executed but with segmentation fault. No traces of memory issues in console output of CTK extension itself. Anyone had similar issues, or at least the idea what could be the issue in this case? In addition, is it possible to show left number of attempts for PIN entry to the user when calling sudo command? I've done it for other use cases with filling error string of finnishWithError function and sending TKErrorCodeAuthenticationFailed error code. Then, on wrong PIN entry, macOS writes the error string in PIN entry window. But when running sudo command nothing is shown in the terminal on wrong PIN entry, just asked for PIN again. Thanks in advance.
Posted Last updated
.
Post not yet marked as solved
1 Replies
604 Views
I am trying to get password entered by user from TKTokenPasswordAuthOperation. When system call beginAuthFor i am returning TKTokenPasswordAuthOperation. now i need password that user has entered. when i try to access password property in TKTokenPasswordAuthOperation class it is nil. How i can get that password.
Posted
by mjza.
Last updated
.
Post marked as solved
1 Replies
447 Views
I am working on Token extension on iOS. Apple documentation say if We throw error with error code "TKError.Code.authenticationNeeded.rawValue" will trigger user authentication. In my TKTokenSessionDelegate class in sign dataToSign function i am throwing this error but my extension is not showing authentication screen. Any Idea what i am missing.
Posted
by mjza.
Last updated
.
Post not yet marked as solved
0 Replies
485 Views
Hello, I recently implemented the Cryptotokenkit for IOS in order to sign mails (via Apple Mail app). This part went relatively smooth. I found in the Mail settings the parameter under S/MIME that enable Signing mails. Now that this step is complete I also wanted to implement mail deciphering. I tried to run some tests but I met the following message when opening encrypted mail: This message is encrypted. Install a profile containing your encryption identity to decrypt this message I'm sure I've encrypted the mail for me. and I'm also sure the identity is saved and usable inside the Cryptotokenkit I implemented. My questions are: is it possible to use the Cryptotokenkit for mail deciphering? (I assume that since I can sign mail via Cryptotokenkit I can also do mail deciphering, right ?). If the first question's answer is yes. then how do you enable the Cryptotokenkit to do mail deciphering? (I thought the option was close to the one for enabling signing mails but I only found mail encryption)
Posted
by leocity.
Last updated
.
Post not yet marked as solved
2 Replies
765 Views
Hi there TL;DR : I have a Data object which contains data that is already hashed. I need a Digest object, how should I proceed ? I am developing an OSX Smart Card Token Extension to handle certificates linked to private keys in the Secure Enclave (using CryptoKit). So far my first tests are pretty successful as my extension already answered to various signature requests successfully... until now. So far I was receiving signature requests for ecdsaSignatureMessageX962SHA256 algorithm. All I had to do with was something like this: func tokenSession(_ session: TKTokenSession, sign dataToSign: Data, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) throws -> Data { if let privateKey = try? SecureEnclave.P256.Signing.PrivateKey.init(dataRepresentation: keyObjectID as! Data) {       let rawsignature = try? privateKey.signature(for: dataToSign)       return rawsignature!.derRepresentation     } } Now I receive requests for ecdsaSignatureDigestX962SHA256 signatures. I noticed that there is a public func signature<D>(for digest: D) throws -> P256.Signing.ECDSASignature where D : Digest function that can be called but in the tokenSession i am only given Data... Looking at SHA256Digest documentation I can't find anything to create the digest from bytes. It seems that it can only be the result of a SHA256.hash operation. I thought of using older API like SecKeyCreateSignature but I don't think I can retrieve a SecKey from a private key generated with CryptoKit SecureEnclave.P256.Signing.PrivateKey.init I feel like I may be missing something really simple...
Posted
by aruffin.
Last updated
.
Post not yet marked as solved
3 Replies
812 Views
I tried to run the following command: sudo -u _securityagent pluginkit -a /Applications/SmartCardApp.app/Contents/PlugIns/CssToken.appex But I am getting connection interrupted error. Do you know what that error means and how I can run that command successfully?
Posted
by jluna.
Last updated
.