According to https://developer.apple.com/documentation/security/app_sandbox/discovering_and_diagnosing_app_sandbox_violations it is possible to view detailed violation reports for non-system services. Is it possible to do something similar for system services?
I have encountered an issue where several (all?) of my Macbooks get into a sandbox violation situation (I assume). Below is in excerpt from logs focusing just on the sandbox violation. The errors are surrounded by XPC failures and errors.
error 23:23:21.382263+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
error 23:23:24.385962+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
error 23:23:27.389910+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
error 23:23:36.408940+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
error 23:23:45.419593+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
error 23:23:54.432109+0100 kernel Sandbox: Family(1316) deny(1) mach-lookup com.apple.contactsd.persistence
The above is just an except, and it seems that Family, imagent and searchpartyuseragent are trying to access com.apple.contactsd.persistance once per second or so and failing (there are also some attempts to reach com.apple.timed.xpc, but an insignificant amount in comparison to com.apple.contactsd.persistance). This in turn causes Diagnostics Reporter to start, and then end hastily almost every ten seconds.
fault 23:23:05.903908+0100 Diagnostics Reporter Invalid launch.
fault 23:23:16.038017+0100 Diagnostics Reporter Invalid launch.
fault 23:23:26.136348+0100 Diagnostics Reporter Invalid launch.
fault 23:23:36.274543+0100 Diagnostics Reporter Invalid launch.
fault 23:23:46.414546+0100 Diagnostics Reporter Invalid launch.
I have no idea how I did this, but I seemed to have messed up sandbox access rights to contacts for some system services?
Prioritize user privacy and data security in your app. Discuss best practices for data handling, user consent, and security measures to protect user information.
Post
Replies
Boosts
Views
Activity
I am working on improving Keychain item storage secured with Face ID using SecAccessControlCreateWithFlags. The implementation uses the .biometryAny flag as shown below:
SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
.biometryAny,
&error
)
While this approach generally works as expected, I encountered a specific edge case during testing. On iOS 18.3.1 with Xcode 15.4, the following sequence causes the Keychain item to become inaccessible:
Navigate to Settings > Face ID & Passcode and select Reset Face ID.
Before setting up a new Face ID, tap the Back button to exit the setup process.
Reopen the Face ID setup and complete the enrollment.
Return to the app—previously stored Keychain items protected by .biometryAny are no longer available.
This behavior appears to be a change introduced in recent iOS versions. In versions prior to iOS 15, resetting or deleting Face ID entries did not invalidate existing Keychain items protected by .biometryAny.
This difference in behavior between iOS versions raises questions about the changes to biometric protection handling.
Any suggestions are welcomed that might shine a light on what the best practice to use keychain access control and prevent the data to become unavailable.
We recently transferred two applications to a different account, both of which utilize Keychain and shared app containers. Before transferring the first application, we anticipated losing access to the Keychain and took proactive measures by backing up data to the app’s private container in the final release prior to the transfer.
During the app transfer process, we removed the shared container group ID from the old account and recreated it under the new account. In our testing, Keychain restoration from the local backup was successful, and users experienced no disruptions. However, after releasing the application, we observed that approximately 25% of our users not only lost their Keychain data as expected but also their shared app container data.
As we have been unable to reproduce this issue internally, we are seeking your guidance on how to prevent a similar situation when transferring our second application. At this stage, we have not yet released any updates from the new account, and the Keychain data remains backed up in the app’s private container.
We would appreciate any insights or recommendations you can provide to ensure a smooth transition for our users and make sure we can keep the data in shared container.
Hello, I have created an app for both iOs and Android where upon speaking two trigger words, the listening app sends a text and then calls to an inputted designated phone contact. The Android version works perfectly. The iOs version also works perfectly but the iOs app emiits a PopUp for each, the text and then the call asking "Do you really want to send the text -or- make the call". Basically, I input the contact info and I spoke the trigger words. So, yes I want to send the text and make the call. So, I have to click the two PopUps then the device sends and calls.
Is there a way to suppress the PopUps in any way? The app is designed for emergencies. So, a dely to anser a popup is not at all good.
Maybe by telling the device to allow auto calls and texts from my app?
Any and all help on this issue will be very welcomed...
Thanks :)
Hello --
I am developing an Authentication Plug-in for the purpose of invoking login with no user interaction (headless).
There seems to be sufficient documentation and sample code on how to implement a plug-in and mechanism, and debug the same, which is great. What I am trying to understand is exactly how to modify the login right (system.login.console) in order to accomplish my goal.
Question 1:
I had the idea of installing my mechanism as the first mechanism of the login right, and when invoked to set the username and password into the engine’s context, in the belief that this would negate the system from needing to display the login screen. I didn’t modify or remove any other mechanisms. This did not work, in the sense that the login screen was still shown. Should this work in theory?
Question 2:
I then tried modifying the login right to remove anything that interacted with the user, leaving only the following:
<array>
<string>builtin:prelogin</string>
<string>builtin:login-begin</string>
<string>builtin:forward-login,privileged</string>
<string>builtin:auto-login,privileged</string> <string>MyAuthPlugin:customauth,privileged</string>
<string>PKINITMechanism:auth,privileged</string>
<string>builtin:login-success</string>
<string>HomeDirMechanism:login,privileged</string>
<string>HomeDirMechanism:status</string>
<string>MCXMechanism:login</string>
<string>CryptoTokenKit:login</string>
</array>
The mechanisms I removed were:
<string>builtin:policy-banner</string>
<string>loginwindow:login</string>
<string>builtin:reset-password,privileged</string>
<string>loginwindow:FDESupport,privileged</string>
<string>builtin:authenticate,privileged</string>
<string>loginwindow:success</string>
<string>loginwindow:done</string>
In place of builtin:authenticate I supplied my own mechanism to verify the user’s password using OD and then set the username and password in the context. This attempt appears to have failed quite badly, as authd reported an error almost immediately (I believe it was related to the AuthEngine failing to init).
There’s very little information to go on as to what each of these mechanisms do, and which are required, etc.
Am I on the wrong track in attempting this? What would be the correct approach?
I'm looking for confirmation on the security aspects of fdesetup authrestart when used on a FileVault-enabled Mac.
As I understand it, this command temporarily stores the decryption key in memory to allow the system to restart without requiring manual entry of the FileVault password. However, I have a few security-related concerns:
Storage of the Decryption Key: Where exactly is the key stored during an authenticated restart? Is it protected within the Secure Enclave (for Apple Silicon Macs) or the T2 Security Chip on Intel Macs?
Key Lifetime & Wiping: At what point is the decryption key erased from memory? Does it persist in any form after the system has fully rebooted?
Protection Against Physical Attacks: If an attacker gains physical access to the machine before the restart completes, is there any possibility that they could extract the decryption key from memory?
Cold Boot Attack Resistance: Is there any risk that advanced forensic techniques (such as freezing RAM to retain data) could be used to recover the decryption key after issuing an authenticated restart?
Malware Resistance: Could a compromised system (e.g., root access by an attacker) intercept or misuse the decryption key before the restart?
I understand that on Apple Silicon and T2-equipped Macs, FileVault keys are tied to hardware-based encryption, making unauthorized access difficult.
However, I'd like to confirm whether Authenticated Restart introduces any new risks compared to a standard FileVault-enabled boot process.
Hello. I want to do the following and need your help.
I want to import a certificate (pkcs#12) into my macOS keychain with a setting that prohibits exporting the certificate.
I want to import the certificate (pkcs#12) into my login keychain or system keychain.
I was able to achieve [1] with the help of the following threads, but have the following problems.
https://developer.apple.com/forums/thread/677314?answerId=824644022#824644022
how to import into login keychain or system keychain
How to achieve this without using the deprecated API
To import into the login keychain, I could use the “SecKeychainCopyDefault” function instead of the “SecKeychainCopySearchList” function,
However, both of these functions were deprecated APIs.
https://developer.apple.com/documentation/security/seckeychaincopysearchlist(_:)
https://developer.apple.com/documentation/security/seckeychaincopydefault(_:)
I checked the following URL and it seems that using the SecItem API is correct, but I could not figure out how to use it.
https://developer.apple.com/documentation/technotes/tn3137-on-mac-keychains
Is there any way to import them into the login keychain or system keychain without using these deprecated APIs?
Hi,
We are using the following API from sys/random.h to generate entropy in our module.
int getentropy(void* buffer, size_t size);
Could you confirm if this API internally uses a non-physical entropy source and adhere to SP800-90B as the following document says:
https://csrc.nist.gov/CSRC/media/projects/cryptographic-module-validation-program/documents/entropy/E181_PublicUse.pdf
I am working on adding RFC4217 Secure FTP with TLS by extending Mike Gleason's classic libncftp client library. I refactored the code to include an FTP channel abstraction with FTP channel abstraction types for TCP, TLS, and TCP with Opportunistic TLS types. The first implementation of those included BSD sockets that libncftp has always supported with the clear TCP channel type.
I first embarked on extending the sockets implementation by adding TCP, TLS, and TCP with Opportunistic TLS channel abstraction types against the new, modern Network.framework C-based APIs, including using the “tricky” framer technique to employ a TCP with Opportunistic TLS FTP channel abstraction type to support explicit FTPS as specified by RFC4217 where you have to connect first in the clear with TCP, request AUTH TLS, and then start TLS after receiving positive confirmation. That all worked great.
Unfortunately, at the end of that effort, I discovered that many modern FTPS server implementations (vsftpd, pure-ftpd, proftpd) mandate TLS session reuse / resumption across the control and data channels, specifying the identical session ID and cipher suites across the control and data channels. Since Network.framework lacked a necessary and equivalent to the Secure Transport SSLSetPeerID, I retrenched and rewrote the necessary TLS and TCP with Opportunistic TLS FTP channel abstraction types using the now-deprecated Secure Transport APIs atop the Network.framework-based TCP clear FTP channel type abstraction I had just written.
Using the canonical test server I had been using throughout development, test.rebex.net, this Secure Transport solution seemed to work perfectly, working in clear, secure-control-only, and secure-control+data explicit FTPS operation.
I then proceeded to expand testing to include a broad set of Microsoft FTP Service, pure-ftpd, vsftpd, proftpd, and other FTP servers identified on the Internet (a subset from this list: https://gist.github.com/mnjstwins/85ac8348d6faeb32b25908d447943300).
In doing that testing, beyond test.rebex.net, I was unable to identify a single (among hundreds), that successfully work with secure-control+data explicit FTPS operation even though nearly all of them work with secure-control-only explicit FTPS operation.
So, I started regressing my libncftp + Network.framework + Secure Transport implementation against curl 8.7.1 on macOS 14.7.2 “Sonoma":
% which curl; `which curl` --version
/usr/bin/curl
curl 8.7.1 (x86_64-apple-darwin23.0) libcurl/8.7.1 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.61.0
Release-Date: 2024-03-27
Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS GSS-API HSTS HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM SPNEGO SSL threadsafe UnixSockets
I find that curl (also apparently written against Secure Transport) works in almost all of the cases my libncftp does not. This is a representative example:
% ./samples/misc/ncftpgetbytes -d stderr --secure --explicit --secure-both ftps://ftp.sjtu.edu.cn:21/pub/README.NetInstall
which fails in the secure-control+data case with errSSLClosedAbort on the data channel TLS handshake, just after ClientHello, attempts whereas:
% curl -4 --verbose --ftp-pasv --ftp-ssl-reqd ftp://ftp.sjtu.edu.cn:21/pub/README.NetInstall
succeeds.
I took an in-depth look at the implementation of github.com/apple-oss-distributions/curl/ and git/github.com/apple-oss-distributions/Security/ to identify areas where my implementation was, perhaps, deficient relative to curl and its curl/lib/vtls/sectransp.c Secure Transport implementation. As far as I can tell, I am doing everything consistently with what the Apple OSS implementation of curl is doing. The analysis included:
SSLSetALPNProtocols
Not applicable for FTP; only used for HTTP/2 and HTTP/3.
SSLSetCertificate
Should only be relevant when a custom, non-Keychain-based certificate is used.
SSLSetEnabledCiphers
This could be an issue; however, the cipher suite used for the data channel should be the same as that used for the control channel. curl talks about disabling "weak" cipher suites that are known-insecure even though the default suites macOS enables are unlikely to enable them.
SSLSetProtocolVersionEnabled
We do not appear to be getting a protocol version negotiation error, so this seems unlikely, but possible.
SSLSetProtocolVersionMax
We do not appear to be getting a protocol version negotiation error, so this seems unlikely, but possible.
SSLSetProtocolVersionMin
We do not appear to be getting a protocol version negotiation error, so this seems unlikely, but possible.
SSLSetSessionOption( , kSSLSessionOptionFalseStart)
curl does seem to enable this for certain versions of macOS and disables it for others. Possible.
Running curl with the --false-start option does not seem to make a difference.
SSLSetSessionOption( , kSSLSessionOptionSendOneByteRecord)
Corresponds to "*****" which seems defaulted and is related to an SSL security flaw when using CBC-based block encryption ciphers, which is not applicable here.
Based on that, further experiments I attempted included:
Disable use of kSSLSessionOptionBreakOnServerAuth: No impact
Assert use of kSSLSessionOptionFalseStart: No impact
Assert use of kSSLSessionOptionSendOneByteRecord: No impact
Use SSLSetProtocolVersionMin and SSLSetProtocolVersionMax in various combinations: No impact
Use SSLSetProtocolVersionEnabled in various combinations: No impact
Forcibly set a single cipher suite (TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, known to work with a given server): No impact
Employ a SetDefaultCipherSuites function similar to what curl does (filtering out “weak” cipher suites): No impact
Notably, I can never coax a similar set of cipher suites that macOS curl does with that technique. In fact, it publishes ciphers that aren’t even in <Security/CipherSuite.h> nor referenced by github.com/apple-oss-distributions/curl/curl/lib/vtls/sectransp.c.
Assert use of kSSLSessionOptionAllowRenegotiation: No impact
Assert use of kSSLSessionOptionEnableSessionTickets: No impact
Looking at Wireshark, my ClientHello includes status_request, signed_certificate_timestamp, and extended_master_secret extensions whereas macOS curl's never do--same Secure Transport APIs. None of the above API experiments seem to influence the inclusion / exclusion of those three ClientHello additions.
Any suggestions are welcomed that might shine a light on what native curl has access to that allows it to work with ST for these FTP secure-control+data use cases.
I am currently working on Fraud System Detection that will be used by one of the financial institutions. Those tools are related to ensuring user security.
Our goal is to identify features that can trigger an early warning system for attempted fraud. We have identified three uncertain variables:
Whether the user is having a conversation while using our app,
Whether the user has specific screen sharing apps on their phone,
Whether the user has enabled VPN connection.
Here my doubts appear:
Can we check the presence of a telephone conversation if we are not a VOIP application?
Can we check the presence of installed programs using Universal Link and canOpenUrl(_:) method?
Can we read "SCOPED" key from CFNetworkCopySystemProxySettings() dictionary?
I will be glad for any advice and help.
I have these two pods:
Frameworks/GTMSessionFetcher.framework/GTMSessionFetcher
Frameworks/GoogleToolboxForMac.framework/GoogleToolboxForMac
they are showing this error:
ITMS-91061: Missing privacy manifest
I've tried manually making privacy files, I've tried updating the SDK's too. I cant update them because firebase depends on GTM Session at a lower version and if I update, MLKit depends on toolbox (even though its deprecating) If I upgrade then the whole project explodes. What do I do. I need help.
this is all I get and it doesn't help:
https://developer.apple.com/support/third-party-SDK-requirements
Hey everyone,
I'm working on a password manager app for iOS and I'm trying to implement the new iOS 18 feature that lets users enable autofill directly from within the app. I know this exists because I've seen it in action in another app. They've clearly figured it out, but I'm struggling to find any documentation or info about the specific API.
Has anyone else had any luck finding this? Any help would be greatly appreciated!
Thanks in advance!
Hello everyone,
In my application, i have implemented authentication using ASWebauthenticationSession. However, when redirecting the user to a WKWebView, no cookies are shared, causing the session to be lost and requiring the user to log in again.
Is there a way to share cookies between the two? If not, what would be the best approach to set up authentication that ensures SSO when switching to a WebView ?
Thank you very much for your help !
My app has been rejected by App Store review because the sign in with Apple functionality is not working properly. I'm able to reproduce the issue on my end but I don't understand why it's happening.
I have two other apps that implement the same OAuth flow in an identical manner, and those apps have no issues signing in with Apple.
I've copied my OAuth flow to a fresh project to see if that would make a difference, and it gives me the exact same error. In the simulator I get "invalid_request, invalid web redirect URL", and on-device the FaceID authentication fails with a very non-specific "Sign Up Not Completed" error.
I'm completely out of ideas here, so any guidance would be appreciated. Thanks!
This post is an extension to Importing Cryptographic Keys that covers one specific common case: importing a PEM-based RSA private key and its certificate to form a digital identity.
If you have questions or comments, start a new thread in Privacy & Security > General. Tag your thread with Security so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Importing a PEM-based RSA Private Key and its Certificate
I regularly see folks struggle to import an RSA private key and its corresponding certificate. Importing Cryptographic Keys outlines various options for importing keys, but in this post I want to cover one specific case, namely, a PEM-based RSA private key and its corresponding certificate. Together these form a digital identity, represented as a SecIdentity object.
IMPORTANT If you can repackage your digital identity as a PKCS#12, please do. It’s easy to import that using SecPKCS12Import. If you can switch to an elliptic curve (EC) private key, please do. It’s generally better and Apple CryptoKit has direct support for importing an EC PEM.
Assuming that’s not the case, let’s explore how to import a PEM-base RSA private key and its corresponding certificate to form a digital identity.
Note The code below was built with Xcode 16.2 and tested on the iOS 18.2 simulator. It uses the helper routines from Calling Security Framework from Swift.
This code assumes the data protection keychain. If you’re targeting macOS, add kSecUseDataProtectionKeychain to all the keychain calls. See TN3137 On Mac keychain APIs and implementations for more background to that.
Unwrap the PEM
To start, you need to get the data out of the PEM:
/// Extracts the data from a PEM.
///
/// As PEM files can contain a large range of data types, you must supply the
/// expected prefix and suffix strings. For example, for a certificate these
/// are `"-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----`.
///
/// - important: This assumes the simplest possible PEM format. It does not
/// handle metadata at the top of the PEM or PEMs with multiple items in them.
func dataFromPEM(_ pem: String, _ expectedPrefix: String, _ expectedSuffix: String) -> Data? {
let lines = pem.split(separator: "\n")
guard
let first = lines.first,
first == expectedPrefix,
let last = lines.last,
last == expectedSuffix
else { return nil }
let base64 = lines.dropFirst().dropLast().joined()
guard let data = Data(base64Encoded: base64) else { return nil }
return data
}
IMPORTANT Read the doc comment to learn about some important limitations with this code.
Import a Certificate
When adding a digital identity to the keychain, it’s best to import the certificate and the key separately and then add them to the keychain. That makes it easier to track down problems you encounter.
To import a PEM-based certificate, extract the data from the PEM and call SecCertificateCreateWithData:
/// Import a certificate in PEM format.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
func importCertificatePEM(_ pem: String) throws -> SecCertificate {
guard
let data = dataFromPEM(pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"),
let cert = SecCertificateCreateWithData(nil, data as NSData)
else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) }
return cert
}
Here’s an example that shows this in action:
let benjyCertificatePEM = """
-----BEGIN CERTIFICATE-----
MIIC4TCCAcmgAwIBAgIBCzANBgkqhkiG9w0BAQsFADAfMRAwDgYDVQQDDAdNb3Vz
ZUNBMQswCQYDVQQGEwJHQjAeFw0xOTA5MzAxNDI0NDFaFw0yOTA5MjcxNDI0NDFa
MB0xDjAMBgNVBAMMBUJlbmp5MQswCQYDVQQGEwJHQjCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAOQe5ai68FQhTVIgpsDK+UOPIrgKzqJcW+wwLnJRp6GV
V9EmifJq7wjrXeqmP1XgcNtu7cVhDx+/ONKl/8hscak54HTQrgwE6mK628RThld9
BmZoOjaWWCkoU5bH7ZIYgrKF1tAO5uTAmVJB9v7DQQvKERwjQ10ZbFOW6v8j2gDL
esZQbFIC7f/viDXLsPq8dUZuyyb9BXrpEJpXpFDi/wzCV3C1wmtOUrU27xz4gBzi
3o9O6U4QmaF91xxaTk0Ot+/RLI70mR7TYa+u6q7UW/KK9q1+8LeTVs1x24VA5csx
HCAQf+xvMoKlocmUxCDBYkTFkmtyhmGRN52XucHgu0kCAwEAAaMqMCgwDgYDVR0P
AQH/BAQDAgWgMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUA
A4IBAQAyrArH7+IyHTyEOrv/kZr3s3h4HWczSVeiO9qWD03/fVew84J524DiSBK4
mtAy3V/hqXrzrQEbsfyT7ZhQ6EqB/W0flpVYbku10cSVgoeSfjgBJLqgJRZKFonv
OQPjTf9HEDo5A1bQdnUF1y6SwdFaY16lH9mZ5B8AI57mduSg90c6Ao1GvtbAciNk
W8y4OTQp4drh18hpHegrgTIbuoWwgy8V4MX6W39XhkCUNhrQUUJk3mEfbC/yqfIG
YNds0NRI3QCTJCUbuXvDrLEn4iqRfbzq5cbulQBxBCUtLZFFjKE4M42fJh6D6oRR
yZSx4Ac3c+xYqTCjf0UdcUGxaxF/
-----END CERTIFICATE-----
"""
print(try? importCertificatePEM(benjyCertificatePEM))
If you run this it prints:
Optional(<cert(0x11e304c10) s: Benjy i: MouseCA>)
Import a Private Key
To import a PEM-base RSA private key, extract the data from the PEM and call SecKeyCreateWithData:
/// Import an 2048-bit RSA private key in PEM format.
///
/// Don’t use this code if:
///
/// * If you can switch to an EC key. EC keys are generally better and, for
/// this specific case, there’s support for importing them in Apple CryptoKit.
///
/// * You can switch to using a PKCS#12. In that case, use the system’s
/// `SecPKCS12Import` routine instead.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
func importRSA2048PrivateKeyPEM(_ pem: String) throws -> SecKey {
// Most private key PEMs are in PKCS#8 format. There’s no way to import
// that directly. Instead you need to strip the header to get to the
// `RSAPrivateKey` data structure encapsulated within the PKCS#8. Doing that
// in the general case is hard. In the specific case of an 2048-bit RSA
// key, the following hack works.
let rsaPrefix: [UInt8] = [
0x30, 0x82, 0x04, 0xBE, 0x02, 0x01, 0x00, 0x30,
0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
0x04, 0xA8,
]
guard
let pkcs8 = dataFromPEM(pem, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"),
pkcs8.starts(with: rsaPrefix)
else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) }
let rsaPrivateKey = pkcs8.dropFirst(rsaPrefix.count)
return try secCall { SecKeyCreateWithData(rsaPrivateKey as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, $0) }
}
IMPORTANT This code only works with 2048-bit RSA private keys. The comments explain more about that limitation.
Here’s an example that shows this in action:
let benjyPrivateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkHuWouvBUIU1S
IKbAyvlDjyK4Cs6iXFvsMC5yUaehlVfRJonyau8I613qpj9V4HDbbu3FYQ8fvzjS
pf/IbHGpOeB00K4MBOpiutvEU4ZXfQZmaDo2llgpKFOWx+2SGIKyhdbQDubkwJlS
Qfb+w0ELyhEcI0NdGWxTlur/I9oAy3rGUGxSAu3/74g1y7D6vHVGbssm/QV66RCa
V6RQ4v8MwldwtcJrTlK1Nu8c+IAc4t6PTulOEJmhfdccWk5NDrfv0SyO9Jke02Gv
ruqu1FvyivatfvC3k1bNcduFQOXLMRwgEH/sbzKCpaHJlMQgwWJExZJrcoZhkTed
l7nB4LtJAgMBAAECggEBAKOPF6ED776SZgrliEog/dmXrhABB6jXybytyw+CRkuP
dXhrRmr+isZ9Y0gTzMN4+dILVgW4EozzoP0/sgZ04oWwDqQS30eU2qzRRzMbo+3k
oYsZXeu3nhxcYppwXIDsfAEd/ygMFzaadRPKYhrFykR2rA/dpLYCvW2tfm5SuULp
RxnKykFlVi8yVT64AovVm0XGOy/QTO5BBbUdftvZY9QCjGn/IEL8QFEz0rxZsb2L
s0HgVMUcB1My38RksZQRKLMWCtqLqWnez3oCnPka+dxFQj5RU//vNtRoVh1ExbmW
txHz48v00AKQvaudC4ujIspZlY8+UPdYQT0TNjhsfoUCgYEA+7yEvyCgRtYwUNm6
jHTg67LoSldHwENOry63qGZp3rCkWBkPXle7ulgRtuw+e11g4MoMMAgkIGyIGB/Z
6YvnQGmJCTMw+HHIyw3k/OvL1iz4DM+QlxDuD79Zu2j2UIL4maDG0ZDskiJujVAf
sFOy4r36TvYedmd7qgh9pgpsFl8CgYEA5/v8PZDs2I1wSDGllGfTr6aeQcxvw98I
p8l/8EV/lYpdKQMFndeFZI+dnJCcTeBbeXMmPNTAdL5gOTwDReXamIAdr93k7/x6
iKMHzBrpQZUMEhepSd8zdR1+vLvyszvUU6lvNXcfjwbu7gJQkwbA6kSoXRN+C1Cv
i5/w66t0f1cCgYBt02FWwTUrsmaB33uzq4o1SmhthoaXKsY5R3h4z7WAojAQ/13l
GwGb2rBfzdG0oJiTeZK3odWhD7iQTdUUPyU0xNY0XVEQExQ3AmjUr0rOte/CJww9
2/UAicrsKG7N0VYEMFCNPVz4pGz22e35T4rLwXZi3J2NqrgZBntK5WEioQKBgEyx
L4ii+sn0qGQVlankUUVGjhcuoNxeRZxCrzsdnrovTfEbAKZX88908yQpYqMUQul5
ufBuXVm6/lCtmF9pR8UWxbm4X9E+5Lt7Oj6tvuNhhOYOUHcNhRN4tsdqUygR5XXr
E8rXIOXF4wNoXH7ewrQwEoECyq6u8/ny3FDtE8xtAoGBALNFxRGikbQMXhUXj7FA
lLwWlNydCxCc7/YwlHfmekDaJRv59+z7SWAR15azhbjqS9oXWJUQ9uvpKF75opE7
MT0GzblkKAYu/3uhTENCjQg+9RFfu5w37E5RTWHD2hANV0YqXUlmH3d+f5uO0xN7
7bpqwYuYzSv1hBfU/yprDco6
-----END PRIVATE KEY-----
"""
print(try? importRSA2048PrivateKeyPEM(benjyPrivateKeyPEM))
If you run this it prints:
Optional(<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000c5ce50>)
Form a Digital Identity
There are two common ways to form a digital identity:
SecPKCSImport
SecItemCopyMatching
SecPKCSImport is the most flexible because it gives you an in-memory digital identity. You can then choose to add it to the keychain or not. However, it requires a PKCS#12 as input. If you’re starting out with separate private key and certificate PEMs, you have to use SecItemCopyMatching.
Note macOS also has SecIdentityCreateWithCertificate, but it has some seriously limitations. First, it’s only available on macOS. Second, it requires the key to be in the keychain. If you’re going to add the key to the keychain anyway, you might as well use SecItemCopyMatching.
To form a digital identity from a separate private key and certificate:
Add the certificate to the keychain.
Add the private key to the keychain.
Call SecItemCopyMatching to get back a digital identity.
Here’s an example of that in action:
/// Imports a digital identity composed of separate certificate and private key PEMs.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
/// See ``importRSA2048PrivateKeyPEM(_:)`` for alternative strategies that are
/// much easier to deploy.
func addRSA2048DigitalIdentityPEMToKeychain(certificate: String, privateKey: String) throws -> SecIdentity {
// First import the certificate and private key. This has the advantage in
// that it triggers an early failure if the data is in the wrong format.
let certificate = try importCertificatePEM(certificate)
let privateKey = try importRSA2048PrivateKeyPEM(privateKey)
// Check that the private key matches the public key in the certificate. If
// not, someone has given you bogus credentials.
let certificatePublicKey = try secCall { SecCertificateCopyKey(certificate) }
let publicKey = try secCall { SecKeyCopyPublicKey(privateKey) }
guard CFEqual(certificatePublicKey, publicKey) else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecPublicKeyInconsistent))
}
// Add the certificate first. If that fails — and the most likely error is
// `errSecDuplicateItem` — we want to stop immediately.
try secCall { SecItemAdd([
kSecValueRef: certificate,
] as NSDictionary, nil) }
// The add the private key.
do {
try secCall { SecItemAdd([
kSecValueRef: privateKey,
] as NSDictionary, nil) }
} catch let error as NSError {
// We ignore a `errSecDuplicateItem` error when adding the key. It’s
// possible to have multiple digital identities that share the same key,
// so if you try to add the key and it’s already in the keychain then
// that’s fine.
guard error.domain == NSOSStatusErrorDomain, error.code == errSecDuplicateItem else {
throw error
}
}
// Finally, search for the resulting identity.
//
// I originally tried querying for the identity based on the certificate’s
// attributes — the ones that contribute to uniqueness, namely
// `kSecAttrCertificateType`, `kSecAttrIssuer`, and `kSecAttrSerialNumber` —
// but that failed for reasons I don't fully understand (r. 144152660). So
// now I get all digital identities and find the one with our certificate.
let identities = try secCall { SecItemCopyMatching([
kSecClass: kSecClassIdentity,
kSecMatchLimit: kSecMatchLimitAll,
kSecReturnRef: true,
] as NSDictionary, $0) } as! [SecIdentity]
let identityQ = try identities.first { i in
try secCall { SecIdentityCopyCertificate(i, $0) } == certificate
}
return try secCall(Int(errSecItemNotFound)) { identityQ }
}
IMPORTANT This code is quite subtle. Read the comments for an explanation as to why it works the way it does.
Further reading
For more information about the APIs and techniques used above, see:
Importing Cryptographic Keys
On Cryptographic Keys Formats
SecItem: Fundamentals
SecItem: Pitfalls and Best Practices
Calling Security Framework from Swift
TN3137 On Mac keychain APIs and implementations
Finally, for links to documentation and other resources, see Security Resources.
Revision History
2025-02-13 Added code to check for mismatched private key and certificate.
2025-02-04 First posted.
I am writing a MacOS app that uses the Apple crypto libraries to create, save, and use an RSA key pair. I am not using a Secure Enclave so that the private key can later the retrieved through the keychain. The problem I am running into is that on my and multiple other systems the creation and retrieval works fine. On a different system -- running MacOS 15.3 just like the working systems -- the SecKeyCreateRandomKey function appears to work fine and I get a key reference back, but on subsequent runs SecItemCopyMatching results in errSecItemNotFound. Why would it appear to save properly on some systems and not others?
var error: Unmanaged<CFError>?
let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
.biometryAny,
&error)!
let tag = TAG.data(using: .utf8)! // com.example.myapp.rsakey
let attributes: [String: Any] = [
kSecAttrKeyType as String: KEY_TYPE, // set to kSecAttrKeyTypeRSA
kSecAttrKeySizeInBits as String: 3072,
kSecPrivateKeyAttrs as String: [
kSecAttrIsPermanent as String: true,
kSecAttrApplicationTag as String: tag,
kSecAttrAccessControl as String: access,
],
]
guard let newKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
return newKey
This runs fine on both systems, getting a valid key reference that I can use. But then if I immediately try to pull the key, it works on my system but not the other.
let query = [ kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: tag,
kSecReturnRef as String: true, ]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
let msg = SecCopyErrorMessageString(status, nil)
if status == errSecItemNotFound {
print("key not found")
}
guard status == errSecSuccess else { print("other retrieval error") }
return item as! SecKey
I've also tried a separate query using the secCall function from here (https://developer.apple.com/forums/thread/710961) that gets ALL kSecClassKey items before and after the "create the key" function and it'll report the same amount of keys before and after on the bugged system. On the other machines where it works, it'll show one more key as expected.
In the Signing & Capabilities section of the project config, I have Keychain Sharing set up with a group like com.example.myapp where my key uses a tag like com.example.myapp.rsakey. The entitlements file has an associated entry for Keychain Access Groups with value $(AppIdentifierPrefix)com.example.myapp.
I am using Auth0 as a login manager for our app. The way Auth0 handles login is that their SDK will create a web view where the login is actually handled. Once the login is finished the session will end and the app will gain control. We are not set up for passkeys in their system and can't set up quickly to do that. Unfortunately with the new iOS "passkey is the primary login" way iOS is set up now, users are asked to use passkey when it's not supported on the backend. I don't have direct control of the login screens. Is there any way, at the app level, to tell the app to not use passkeys so that it quits showing up as an option for the users? I can't find any documentation on doing this. How can I stop passkey in my app entirely?
I am currently unable to enable passkey in my app so I am having to tell my users to skip the prompts for using passkey. We have noticed that after a few times of this the OS will stop asking the user to register their passkey. The question is, how long does this last before the OS asks you to use passkey again? Is it permanent until you re-install the app? Just looking for a time frame if anyone knows.
Hi,
I am working on Authorisation Plugin for Mac OS X and able to get going for most of the parts and taking inspiration from Jamf Authorisation Plugin repo https://github.com/jamf/NoMADLogin-AD.
I have seen in project they are implementing logic for following.
Connecting to Wifi
Power management (Sleep, Restart, Power Off)
Question: I was wondering these things need to be implemented or is there a way some components from Mac OS X could be integrated calling some API and I don't have to implement them and I see say a top bar where these items are viable as we see in default login screen.
I have developed my own login screen and I do see it is all blank everything I have to implement from scratch.
Trying luck here if any API is out there to reduce work, else no option but to implement all logic.
I'll really appreciate if someone just could help me know such API's are present or not. In case there are will save lot of effort.
Thanks,
Hello,
I have an application which uses a helper[1] to download[2] files. When files download is a DMG and user mounts the image to run the application from this DMG it doesn't pass Gatekeeper. It presents the "Application XYZ.app can't be opened.".
Same file downloaded via Safari shows a different dialog, the "XYZ.app is an app downloaded from the internet. Are you sure you want to open it?"
In the system log I see this line:
exec of /Volumes/SampleApp/SampleApp.app/Contents/MacOS/SampleApp denied since it was quarantined by Download\x20Helper and created without user consent, qtn-flags was 0x00000187
The application is running sandboxed and hardened, the main application has com.apple.security.files.downloads.read-write entitlement. Everything is signed by DeveloperID and passes all checks[3].
I tried to check the responsible process[4] of the helper. Then trivial stuff like download folder access in System Settings/Privacy & Security/Files & Folders. Everything seems to be fine.
For what it worths the value of quarantine attribute is following:
com.apple.quarantine: 0087;6723b80e;My App;
The Safari downloaded one posses:
com.apple.quarantine: 0083;6723b9fa;Safari;02162070-2561-42BE-B30B-19A0E94FE7CA
Also tried a few more ways and got to 0081 with Edge and 0082 with a sample app with similar setup. Not sure if that has any meaning.
What could I be doing wrong that Gatekeeper right away refuses to run the application from DMG instead of showing the dialog like in other cases?
[1] The executable is in application bundle located in Contents/Helpers/DownloadHelper.app in the main application bundle.
[2] Nothing fancy, curl + regular POSIX file operations
[3] codesign, syspolicy_check, spctl
[4] launchctl procinfo pid