Security

RSS for tag

Secure the data your app manages and control access to your app using the Security framework.

Posts under Security tag

202 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Security Implications of fdesetup authrestart on FileVault-Enabled Macs
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.
1
1
461
Feb ’25
MacOS sometimes not asking for password after sleep when close lid
Sometimes, when I close the lid using the MacOs version Sequoia 15.2, with the configuration to require a password for 5 seconds, the system does not ask for the password as expected. This happens sometimes even though nothing preventing the system from sleeping when you close and open the lid, but it still seems like a security concern. Is there some known issue related to this problem or a way to avoid it? Result of command pmset -g: Configuration:
1
0
334
Feb ’25
Import PKCS#12 into macOS login keychain or system keychain
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?
4
0
411
Feb ’25
Fails to capture IOUSBHostInterface with macOS 15.3 despite root privileges in app
I have an app that captures USB storage device and sends some commands to it. The app has a privilege helper tool which captures the USB device. Everything was working fine upto macOS 15.2 but it 15.3 update broke the functionality. When the helper tool tries to capture the USB device, it is able to capture IOUSBHostDevice but fails to capture IOUSBHostInterface. The error is Code: 3758097097; Domain: IOUSBHostErrorDomain; Description: Failed to create IOUSBHostInterface.; Reason: Failed [super init] I have verified the UID, EUID, GID, EGID = 0 for the helper process. So by IOUSBHost documentation it should have worked. The code that cause the error inside the helper tool is func captureUSBInterface(interface: io_service_t) -> IOUSBHostInterface? { let queue = DispatchQueue(label: "com.example.usbdevice.queue2") var capturedInterface: IOUSBHostInterface? do { capturedInterface = try IOUSBHostInterface(__ioService: interface, options: .deviceCapture, queue: queue, interestHandler: nil) } catch { NSLog("Failed to capture USB interface: \(error)") return nil } return capturedInterface } The app has sandbox=False and is distributed outside of the App Store. Please advise (long-term, short-term solutions) on how to make this work.
2
0
366
Feb ’25
full disk access granted, but app fails to load file from user folder
i recently upgraded to sequoia, and now, more often than not, when running in the debugger, opening my database causes a hang: When i run outside the debugger, it opens just fine. I suspect it has to do with "full disk access"? but i've given my app full disk access. i've also set Qt and Xcode to have "Allow apps to use developer tools" permissions. as a test i also added my app into that permission group, all to no avail. the path to the DB being opened is in my user's Music folder, and having full disk access gives permission for everything, including things in that folder. confused!
1
0
319
Feb ’25
iOS Biometric Authentication Implementation when biometric is added
Current Setup: Using Secure Enclave with userPresence access control Foreground keychain accessibility: whenPasscodeSetThisDeviceOnly Security Requirement: Our security group wants us to invalidate biometrics and require a username/password if a biometric item is added (potentially by a hostile 3rd party) Need to upgrade from userPresence to biometricCurrentSet to ensure re-authentication when biometric credentials change. Issue: After implementing biometricCurrentSet, authentication cancels after two failed biometric attempts instead of falling back to passcode. Current Detection Method: User completes initial biometric authentication Biometric changes occur (undetectable by app) App attempts Secure Enclave access Access denial triggers re-authentication requirement Cannot revoke refresh token after access is denied Security Concern: Current implementation allows new biometric enrollments to access existing authenticated sessions without re-verification. Question: What's the recommended approach to: Implement biometricCurrentSet while maintaining passcode fallback Properly handle refresh token invalidation when biometric credentials change Looking for guidance on best practices for implementing these security requirements while maintaining good UX.
0
0
359
Feb ’25
Reduced certificate lifespan: CA root
I have some concerns related to shortening the lifetime of certificates, as per https://support.apple.com/en-gb/102028 Does this apply to Private CA root certificates? And if yes: does it apply if I use ATS and higher level API like URLSession does it apply it I carry my root CA cert in my app payload and use low level libraries without ATS support?
5
0
412
Feb ’25
Importing a PEM-based RSA Private Key and its Certificate
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.
0
0
384
Feb ’25
iOS 18 - Intermittent keychain issue
Hi, We're encountering an intermittent issue where certain users are unexpectedly logged out of our app and unable to log in again. We believe we've narrrowed down the issue to the Keychain due to the following reasons: We use a keychain item to determine if the member is logged in or not. Failure to retrieve the value leads the app to believe the member is logged out. API error logs on the server show 3 missing values in fields that are each populated from items stored in the keychain. Additional Notes: The issue is hard to reproduce and seems to affect only a subset of users. In some cases, uninstalling and reinstalling the app temporarily resolves the problem, but the issue recurs after a period of time. The behavior appears to have coincided with the release of iOS 18. We’re using the “kSecAttrAccessibleWhenUnlocked” accessibility attribute. Given that our app doesn’t perform background operations, we wouldn’t expect this to be an issue. We’re also considering changing this to "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly" to see if this might resolve the issue. We're the keychain-swift library to interact with the keychain. We are currently adding extensive logging around our keychain implementation to confirm our findings but are looking for any additional input. Questions: Has anyone encountered similar keychain behavior on iOS 18? Are there known changes or stability issues with the keychain in iOS 18 that might lead to such intermittent “item not found” errors? Any recommended workarounds or troubleshooting steps that could help isolate the problem further? Thanks for any help you can provide.
1
0
484
Feb ’25
Launch constraints using LightweightCodeRequirements framework
MacOS Version: 14.7.2 macOS SDKs: macOS 14.5 -sdk macosx14.5 I am working on a sample program for validation Against: Team Identifier Developer ID I started with validating Team Identifier, but my validation is not working and it is allowing to launch programs which are not matching the team identifier in the signature. Below is my code: func verifyExecutableWithLCR(executablePath: String, arguments: [String]) -&gt; Bool { let task = Process() task.launchPath = executablePath task.arguments = arguments if #available(macOS 14.4, *) { print("launchRequirementData is available on this system.") do { let req = try OnDiskCodeRequirement.allOf { TeamIdentifier("ABCDEFGHI") //SigningIdentifier("com.***.client.***-Client.****") } let encoder = PropertyListEncoder() encoder.outputFormat = .xml let requirementData = try encoder.encode(req) task.launchRequirementData = requirementData print("launchRequirementData is set.") try task.run() print("[SUCCESS] Executable passed the code signature verification.") return true } catch { print("[ERROR] Code signature verification failed: \(error.localizedDescription)") return false } } else { print("[WARNING] launchRequirement is not available on this macOS version.") return false } } Could you please help me in identifying whay am I doing wrong here?
7
0
472
Feb ’25
Screen recording detect in MACOs Apps
Hi, My MACOS app has sensitive content and dont want user to take screenshot or to record the screen. I tries window.sharingType=none. With this user can still record the screen. I know that user can record with external device. But we dont want him to record using screen capture. Can you please tell me how to detect when screen recording is active in MACOs apps? or how to prevent screen recording in MACOs apps. Thanks
0
1
324
Feb ’25
What is the alternative to Environment and Library Constraints before macOS 14.0?
In the macOS 14.0 SDK, environment and library constraints were introduced, which made defense against common attack vectors relatively simple (especially with the LightWeightCodeRequirements framework added in 14.4). Now, the application I'm working on must support macOS 13.0 too, so I was looking into alternatives that do work for those operating systems as well. What I found myself is that the SecCode/SecStaticCode APIs in the Security Framework do offer very similar fashion checks as the LightWeightCodeRequirements framework does: SecCodeCopySigningInformation can return values like signing identifier, team identifier, code requirement string and so on. SecStaticCodeCreateWithPath can return a SecStaticCode object to an executable/app bundle on the file system. Let's say, I would want to protect myself against launchd executable swap. From macOS 14.0 onward, I would use a Spawn Constraint for this, directly in the launchd.plist file. Before macOS 14.0, I would create a SecStaticCode object for the executable path found in the launchd.plist, and then examine its SecCodeCopySigningInformation dictionary. If the expectations are met, only then would I execute the launchd.plist-defined executable or connect to it via XPC. Are these two equivalent? If not, what are the differences?
3
0
670
Jan ’25
How to perform actions as root from GUI apps on macOS?
I'm building a tool for admins in the enterprise context. The app needs to do some things as root, such as executing a script. I was hoping to implement a workflow where the user clicks a button, then will be shown the authentication prompt, enter the credentials and then execute the desired action. However, I couldn't find a way to implement this. AuthorizationExecuteWithPrivileges looked promising, but that's deprecated since 10.7. I've now tried to use a launch daemon that's contained in the app bundle with XPC, but that seems overly complicated and has several downsides (daemon with global machservice and the approval of a launch daemon suggests to the user that something's always running in the background). Also I'd like to stream the output of the executed scripts in real time back to the UI which seems very complicated to implement in this fashion. Is there a better way to enable an app to perform authorized privilege escalation for certain actions? What about privileged helper tools? I couldn't find any documentation about them. I know privilege escalation is not allowed in the App Store, but that's not relevant for us.
4
0
443
Jan ’25
Create an SecIdentityRef from a certificate and private key
Hi, I am working on a react native module used for tis connection and I am trying to implement the possibility to use a custom certificate/Private key. I have already implemented on android but on iOS I am getting hard times, we cannot find lots of resources, api is different on macOS and iOS with subtle differences so after having tested SO, chatgpt, ... I am trying here: I even tried to use an internal api since it seems ffmpeg uses it but with no success. I have attached my current code because it does not fit here. to sump up after having inserted cert and private key I try to get a SecIdentityRef but it fails. I assume that it's not enough to simply add certain and private key... // Query for the identity with correct attributes NSDictionary *identityQuery = @{ (__bridge id)kSecClass: (__bridge id)kSecClassIdentity, (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne, (__bridge id)kSecReturnRef: @YES, (__bridge id)kSecReturnData: @YES, (__bridge id)kSecAttrLabel: @"My Certificate", //(__bridge id)kSecUseDataProtectionKeychain: @YES }; SecIdentityRef identity = NULL; status = SecItemCopyMatching((__bridge CFDictionaryRef)identityQuery, (CFTypeRef *)&identity); TcpSocketClient.txt SecItemCopyMatching with kSecClassIdentity fails, SecIdentityCreate return NULL... So please help and indicates what I am doing wrong and how I am supposed getting a SecIdentityRef. Thanks
22
0
723
Mar ’25
Does SecKeyCreateDecryptedData Ignore LATouchIDAuthenticationMaximumAllowableReuseDuration?
Hi everyone, I’m working on an iOS app that uses biometric authentication to access secure keychain items and private keys stored in the Secure Enclave with some data encryption/decryption with those keys. My goal is to minimize the number of biometric prompts by reusing the authentication result within a short time window. I have the following setup: When writing the biometry-restricted keychain items and Secure Enclave keys, I use LAContext with the property LATouchIDAuthenticationMaximumAllowableReuseDuration = 1 minute, and I pass this context as the kSecUseAuthenticationContext field in the query. When retrieving these items later (in a synchronous sequence upon app launch), I pass the same instance of LAContext as the kSecUseAuthenticationContext field. The issue: If I unlock my device and the biometric reuse time has not expired (i.e., less than 1 minute), the first two actions (keychain item retrieval and Secure Enclave key retrieval) do not prompt for Face ID. However, when I attempt to decrypt data with the private key using SecKeyCreateDecryptedData, I’m prompted for Face ID even if the biometric reuse time is still valid. If the biometric reuse time has expired (more than 1 minute since last authentication), I get prompted for Face ID on the first action (keychain retrieval), and subsequent actions (including data decryption) reuse that biometric result. Question: Does this behavior mean that SecKeyCreateDecryptedData ignore the LATouchIDAuthenticationMaximumAllowableReuseDuration property of LAContext, causing an additional biometric prompt during decryption with the private key? Or is there another reason for this behavior? Is there a way to make the biometric result reusable across all these actions, including decryption? Thank you!
1
0
478
Jan ’25
Understanding Keychain Errors in Mobile Banking App
Hi, We use the iOS Keychain in our mobile app to securely store and retrieve data, which is tightly coupled with the initialization of some app features within the application. This issue is encountered during app launch We retrieve during Splash Screen UI controller at viewDidApper() The logic we use to access the Keychain is as follows: NSDate *NSDate_CD; NSString *account = [NSString stringWithUTF8String:@"SOME_KEY_ACCOUNT"]; NSString *attrgen = [NSString stringWithUTF8String:@"SOME_KEY"]; NSMutableDictionary *query = [[NSMutableDictionary alloc] init]; [query setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id&lt;NSCopying&gt;)(kSecClass)]; [query setObject:attrgen forKey:(__bridge id&lt;NSCopying&gt;)(kSecAttrGeneric)]; [query setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) forKey:(__bridge id&lt;NSCopying&gt;)(kSecAttrAccessible)]; [query setObject: [NSBundle mainBundle].bundleIdentifier forKey:(__bridge id&lt;NSCopying&gt;)(kSecAttrService)]; [query setObject:account forKey:(__bridge id&lt;NSCopying&gt;)(kSecAttrAccount)]; [query setObject:@YES forKey:(__bridge id&lt;NSCopying&gt;)(kSecReturnAttributes)]; [query setObject:@YES forKey:(__bridge id&lt;NSCopying&gt;)(kSecReturnData)]; CFDictionaryRef valueAttributes = NULL; OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&amp;valueAttributes); NSDictionary *attributes = (__bridge_transfer NSDictionary *)valueAttributes; if(status==errSecSuccess) { NSDate_CD = [attributes objectForKey:(__bridge id)kSecAttrCreationDate]; } else { NSLog(@"Key chain query failed"); } However, some users have reported intermittent failures during app launch. Upon investigation, we discovered that these failures are caused by exceptions thrown by the iOS Keychain, which the app is currently not handling. Unfortunately, we do not log the exception or the Keychain error code in the app logs at the moment, but we plan to implement this logging feature in the near future. For now, we are trying to better understand the nature of these errors. Could you help clarify the following Keychain errors, which might be encountered from the code above? errSecServiceNotAvailable (-25307) errSecAllocate (-108) errSecNotAvailable (-25291) If these errors are encountered, are they typically persistent or are they temporary states that could resolve on their own? Your insights would be greatly appreciated. Thank you.
1
0
403
Jan ’25