CryptoTokenKit

RSS for tag

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

Posts under CryptoTokenKit tag

92 Posts

Post

Replies

Boosts

Views

Activity

PIV token authentication
I'm writing an application which is using a custom right to require that a user authenticate as an admin to access a specific part of my app, and I'm struggling with cases where smart card usage is enforced. The simplest way is to use a custom right, but the dialog presented to the user gives no feedback that smartcard is required should they try to authenticate with password when the token isn't connected (i.e. a yubikey for example isn't plugged in to the USB bus) Instead, in this case, the authentication dialog simply wobbles as though they hadn't entered the correct password. It looks like the same is true of default macOS dialogs too such as unlocking a preference pane. I've looked around the API docks to see if there's any other way I can do this, but I don't seem to find any API methods that explicitly state I want the user to authenticate with a PIV token? Do I need to use CryptoTokenKit to send raw ADPU commands to a connected token to achieve this? I was hoping I could use LAContext from LocalAuthentication to do this as it supports watch/fingerprint auth, but again I couldn't see any obvious sign of support for smartcards.
1
0
1.8k
Feb ’23
TKSmartCard transmit command on iOS fails after 600 ms.
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) } } }
2
3
1.5k
Feb ’23
Open Containing app from Crypto Token Kit (CTK) extension iOS
Hi! I want to open the containing app from ctk extension because i need to ask for parameters related to the signature operation. The beginAuthFor: method is not enough, because i need more input than just the password. I can do this on MacOS with NSWorkspace.shared.open(url), but on iOS UIApplication.shared.open " is unavailable in application extensions for iOS" Any Suggestions?
1
0
1.1k
Jan ’23
CryptoTokenKit persistent token extension + SSH PKCS#11 authentication doesn't work
I am building a CryptoTokenKit based persistent token extension where : the private key is generated in Secure Enclave (the idea is not to store the private key on disk) CSR is sent to a server signed OpenSSH cert is received and is on the disk along with the public key i.e id_foo-cert.pub, id_foo.pub the private key ref is stored in the token driver  // Mac keychain can't store OpenSSH certificate so set as nil   let tokenKey = TKTokenKeychainKey(certificate: certificate, objectID: tag) .... // Add to the keychain for future access by SSH   tokenConfig.keychainItems.append(tokenKey) My extension is loaded : % system_profiler SPSmartCardsDataType                       SmartCards:   Readers:   Reader Drivers:    #01: fr.apdu.ccid.smartcardccid:1.5.0 (/usr/libexec/SmartCardServices/drivers/ifd-ccid.bundle)   SmartCard Drivers:    #01: com.apple.CryptoTokenKit.pivtoken:1.0 (/System/Library/Frameworks/CryptoTokenKit.framework/PlugIns/pivtoken.appex)    #02: com.foo.mac-device-check.SecureEnclaveTokenExtension:1.0 (/Applications/mac_device_check.app/Contents/PlugIns/SecureEnclaveTokenExtension.appex)   Available SmartCards (keychain):     com.apple.setoken:     com.apple.setoken:aks:     com.foo.mac-device-check.SecureEnclaveTokenExtension:700D6B7E8943B529569D9CC81AC6F930:      #01: Kind: private ECDSA 256-bit, Certificate: no, Usage: Sign Derive  Valid from: N/A to: N/A, SSL trust: N/A, X509 trust: N/A   Available SmartCards (token):     com.apple.setoken:     com.apple.setoken:aks:     com.foo.mac-device-check.SecureEnclaveTokenExtension:700D6B7E8943B529569D9CC81AC6F930:      #01: Kind: private ECDSA 256-bit, Certificate: no, Usage: Sign Derive  Valid from: N/A to: N/A, SSL trust: N/A, X509 trust: N/A % security list-smartcard No smartcards found. When I SSH to a remote with this ssh_config below it doesn't load the CTK app extension at all: Host test  HostName abc.foo.com  User foo_user  AddKeysToAgent yes  UseKeychain yes  CertificateFile ~/.ssh_certificates/id_foo-cert.pub  PKCS11Provider /usr/lib/ssh-keychain.dylib Debug logs : debug1: Connecting to abc.foo.com port 22. debug1: Connection established. debug1: provider /usr/lib/ssh-keychain.dylib: manufacturerID <Apple, Inc.> cryptokiVersion 2.20 libraryDescription <Keychain emulation PKCS#11 API> libraryVersion 0.0 debug1: pkcs11_register_provider: provider /usr/lib/ssh-keychain.dylib returned no slots debug1: Next authentication method: publickey debug1: Offering public key: /Users/local/.ssh_certificates/id_foo-cert.pub ECDSA-CERT SHA256:c4uVaMJpVaAWg8gtAxMHtJIpNnZ67P/G9Dw2wx44Kgs explicit debug2: we sent a publickey packet, wait for reply debug1: Server accepts key: /Users/local/.ssh_certificates/id_foo-cert.pub ECDSA-CERT SHA256:c4uVaMJpVaAWg8gtAxMHtJIpNnZ67P/G9Dw2wx44Kgs explicit debug1: sign_and_send_pubkey: no separate private key for certificate "/Users/local/.ssh_certificates/id_foo-cert.pub" debug2: Passphrase not found in the keychain. Load key "/Users/local/.ssh_certificates/id_foo-cert.pub": invalid format Since pkcs11 returned no slots, the private key ref cannot be accessed for signing. I have tested this on Monterey 12.5 and Ventura 13.1 with the same failure. Anyone knows if pkcs11 provider can launch a CTK app extension ? Is there anything wrong in my code/config ? Is there any sample settings/code for persistent token extension handling SSH keys ? Any help is highly appreciated.
3
0
2.1k
Jan ’23
Swift smart contracts
Hello, I came on this forum to ask if there were any other developers or teams currently working on the Swift Based Blockchain protocol for Apple to make "Dapples"? I was hoping that someone would guide me in the right direction as far as exporting my solidity based smart contract application into swift / into Xcode. I cannot find out how to connect solidity and Xcode to make Dapps, and I was wondering if anyone was working on making the official smart contract for Swift IOS? thank you, Dylan Kawalec DYLANKAWALEC@GMAIL.COM 9284990093
1
0
2.4k
Jan ’23
Call to TKSmartCard.endSession() can cause crash
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
1
0
1.1k
Nov ’22
TKSmartCardSlotManager iOS
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?
2
0
2.6k
Nov ’22
How to sign data with SmartCard use CryptoTokenKit?
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!
5
0
2.7k
Sep ’22
CTK Authentication failed repeatedly
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!
3
0
1.5k
Aug ’22
Mixed RSA / EC certificate chain
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
0
0
997
Jun ’22
NSAlert with NSSecureTextField in main thread dont works
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
7
0
1.7k
Jun ’22
PCSC Framework truncates bytes
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?
1
0
1.4k
Jun ’22
CryptoTokenKit
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.
3
0
2.5k
May ’22
Using SmartCard and CryptoTokenKit extension to authenticate for sudo command
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.
8
0
2.2k
May ’22
TKTokenPasswordAuthOperation get password
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.
1
0
1.6k
Apr ’22
Use Cryptotokenkit for mail deciphering
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)
1
1
1.1k
Feb ’22
How to get a Digest object from raw Data
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...
2
0
1.7k
Jan ’22
PIV token authentication
I'm writing an application which is using a custom right to require that a user authenticate as an admin to access a specific part of my app, and I'm struggling with cases where smart card usage is enforced. The simplest way is to use a custom right, but the dialog presented to the user gives no feedback that smartcard is required should they try to authenticate with password when the token isn't connected (i.e. a yubikey for example isn't plugged in to the USB bus) Instead, in this case, the authentication dialog simply wobbles as though they hadn't entered the correct password. It looks like the same is true of default macOS dialogs too such as unlocking a preference pane. I've looked around the API docks to see if there's any other way I can do this, but I don't seem to find any API methods that explicitly state I want the user to authenticate with a PIV token? Do I need to use CryptoTokenKit to send raw ADPU commands to a connected token to achieve this? I was hoping I could use LAContext from LocalAuthentication to do this as it supports watch/fingerprint auth, but again I couldn't see any obvious sign of support for smartcards.
Replies
1
Boosts
0
Views
1.8k
Activity
Feb ’23
TKSmartCard transmit command on iOS fails after 600 ms.
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) } } }
Replies
2
Boosts
3
Views
1.5k
Activity
Feb ’23
Open Containing app from Crypto Token Kit (CTK) extension iOS
Hi! I want to open the containing app from ctk extension because i need to ask for parameters related to the signature operation. The beginAuthFor: method is not enough, because i need more input than just the password. I can do this on MacOS with NSWorkspace.shared.open(url), but on iOS UIApplication.shared.open " is unavailable in application extensions for iOS" Any Suggestions?
Replies
1
Boosts
0
Views
1.1k
Activity
Jan ’23
CryptoTokenKit persistent token extension + SSH PKCS#11 authentication doesn't work
I am building a CryptoTokenKit based persistent token extension where : the private key is generated in Secure Enclave (the idea is not to store the private key on disk) CSR is sent to a server signed OpenSSH cert is received and is on the disk along with the public key i.e id_foo-cert.pub, id_foo.pub the private key ref is stored in the token driver  // Mac keychain can't store OpenSSH certificate so set as nil   let tokenKey = TKTokenKeychainKey(certificate: certificate, objectID: tag) .... // Add to the keychain for future access by SSH   tokenConfig.keychainItems.append(tokenKey) My extension is loaded : % system_profiler SPSmartCardsDataType                       SmartCards:   Readers:   Reader Drivers:    #01: fr.apdu.ccid.smartcardccid:1.5.0 (/usr/libexec/SmartCardServices/drivers/ifd-ccid.bundle)   SmartCard Drivers:    #01: com.apple.CryptoTokenKit.pivtoken:1.0 (/System/Library/Frameworks/CryptoTokenKit.framework/PlugIns/pivtoken.appex)    #02: com.foo.mac-device-check.SecureEnclaveTokenExtension:1.0 (/Applications/mac_device_check.app/Contents/PlugIns/SecureEnclaveTokenExtension.appex)   Available SmartCards (keychain):     com.apple.setoken:     com.apple.setoken:aks:     com.foo.mac-device-check.SecureEnclaveTokenExtension:700D6B7E8943B529569D9CC81AC6F930:      #01: Kind: private ECDSA 256-bit, Certificate: no, Usage: Sign Derive  Valid from: N/A to: N/A, SSL trust: N/A, X509 trust: N/A   Available SmartCards (token):     com.apple.setoken:     com.apple.setoken:aks:     com.foo.mac-device-check.SecureEnclaveTokenExtension:700D6B7E8943B529569D9CC81AC6F930:      #01: Kind: private ECDSA 256-bit, Certificate: no, Usage: Sign Derive  Valid from: N/A to: N/A, SSL trust: N/A, X509 trust: N/A % security list-smartcard No smartcards found. When I SSH to a remote with this ssh_config below it doesn't load the CTK app extension at all: Host test  HostName abc.foo.com  User foo_user  AddKeysToAgent yes  UseKeychain yes  CertificateFile ~/.ssh_certificates/id_foo-cert.pub  PKCS11Provider /usr/lib/ssh-keychain.dylib Debug logs : debug1: Connecting to abc.foo.com port 22. debug1: Connection established. debug1: provider /usr/lib/ssh-keychain.dylib: manufacturerID <Apple, Inc.> cryptokiVersion 2.20 libraryDescription <Keychain emulation PKCS#11 API> libraryVersion 0.0 debug1: pkcs11_register_provider: provider /usr/lib/ssh-keychain.dylib returned no slots debug1: Next authentication method: publickey debug1: Offering public key: /Users/local/.ssh_certificates/id_foo-cert.pub ECDSA-CERT SHA256:c4uVaMJpVaAWg8gtAxMHtJIpNnZ67P/G9Dw2wx44Kgs explicit debug2: we sent a publickey packet, wait for reply debug1: Server accepts key: /Users/local/.ssh_certificates/id_foo-cert.pub ECDSA-CERT SHA256:c4uVaMJpVaAWg8gtAxMHtJIpNnZ67P/G9Dw2wx44Kgs explicit debug1: sign_and_send_pubkey: no separate private key for certificate "/Users/local/.ssh_certificates/id_foo-cert.pub" debug2: Passphrase not found in the keychain. Load key "/Users/local/.ssh_certificates/id_foo-cert.pub": invalid format Since pkcs11 returned no slots, the private key ref cannot be accessed for signing. I have tested this on Monterey 12.5 and Ventura 13.1 with the same failure. Anyone knows if pkcs11 provider can launch a CTK app extension ? Is there anything wrong in my code/config ? Is there any sample settings/code for persistent token extension handling SSH keys ? Any help is highly appreciated.
Replies
3
Boosts
0
Views
2.1k
Activity
Jan ’23
Swift smart contracts
Hello, I came on this forum to ask if there were any other developers or teams currently working on the Swift Based Blockchain protocol for Apple to make "Dapples"? I was hoping that someone would guide me in the right direction as far as exporting my solidity based smart contract application into swift / into Xcode. I cannot find out how to connect solidity and Xcode to make Dapps, and I was wondering if anyone was working on making the official smart contract for Swift IOS? thank you, Dylan Kawalec DYLANKAWALEC@GMAIL.COM 9284990093
Replies
1
Boosts
0
Views
2.4k
Activity
Jan ’23
Call to TKSmartCard.endSession() can cause crash
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
Replies
1
Boosts
0
Views
1.1k
Activity
Nov ’22
TKSmartCardSlotManager iOS
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?
Replies
2
Boosts
0
Views
2.6k
Activity
Nov ’22
iOS USB device access
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?
Replies
9
Boosts
1
Views
8.2k
Activity
Nov ’22
How to sign data with SmartCard use CryptoTokenKit?
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!
Replies
5
Boosts
0
Views
2.7k
Activity
Sep ’22
CTK Authentication failed repeatedly
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!
Replies
3
Boosts
0
Views
1.5k
Activity
Aug ’22
Cypto Token Kit Release not working in release
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
Replies
3
Boosts
0
Views
1.1k
Activity
Aug ’22
Mixed RSA / EC certificate chain
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
Replies
0
Boosts
0
Views
997
Activity
Jun ’22
NSAlert with NSSecureTextField in main thread dont works
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
Replies
7
Boosts
0
Views
1.7k
Activity
Jun ’22
PCSC Framework truncates bytes
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?
Replies
1
Boosts
0
Views
1.4k
Activity
Jun ’22
CryptoTokenKit
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.
Replies
3
Boosts
0
Views
2.5k
Activity
May ’22
Using SmartCard and CryptoTokenKit extension to authenticate for sudo command
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.
Replies
8
Boosts
0
Views
2.2k
Activity
May ’22
TKTokenPasswordAuthOperation get password
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.
Replies
1
Boosts
0
Views
1.6k
Activity
Apr ’22
Use Cryptotokenkit for mail deciphering
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)
Replies
1
Boosts
1
Views
1.1k
Activity
Feb ’22
How to get a Digest object from raw Data
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...
Replies
2
Boosts
0
Views
1.7k
Activity
Jan ’22
Connection Interrupted Error sudo -u _securityagent pluginkit -a /Applications/SmartCardApp.app/Contents/PlugIns/CssToken.appex
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?
Replies
3
Boosts
0
Views
1.5k
Activity
Dec ’21