Security

RSS for tag

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

Posts under Security tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SecCodeCopyPath and /System/Volumes/Preboot/Cryptexes/App/System
Looking at the path name for reasons, and ran into a thing: one of my coworkers was not getting /Applications/Safari.app as expected, but instead got /System/Volumes/Preboot/Cryptexes/App/System/Applications/Safari.app. Which is annoying because I'm actually using spotlight to find the paths for applications, and that one doesn't show up. Has anyone run into this? And know why? (I figure I'll simply remove the prefix if it's there, and that should be fine, but I'm curious why it only seems to happen sometimes.)
4
0
1.2k
Feb ’24
Key Storage Provider (KSP) macOS equivalent
Hi, I successfully developed a key storage provider (KSP) under Windows that allows me to digitally sign from 3rd party application (typically Acrobat Reader but not only). Now I'm trying to port the key storage provider to macOS, but I cannot find an equivalent technology under this OS. I've tried different solutions: API hooking/method swizzling/dll interposing: It doesn't look officially supported plus easily blockable (with hardened runtime); Endpoint security framework: It looks basically for watch-only purposes plus minimal blocking capabilities; Is there any supported way to implement a KSP macOS equivalent? Any suggestion? Something else to explore? Thanks a lot, max
1
0
420
Feb ’24
Utilizing Keychain Services with Swift 5.9
Hello, I'm near-brand new to writing in Swift and am attempting to write a simple VPN configuration to start an existing VPN in-app for a mobile app I'm developing for the company I work for. We're writing this in Swift in hopes of converting them to C# eventually for the mobile app's end product. So I'm attempting to set VPN configurations using a NEVPNProtocolIKEv2() type, and when it comes to setting the server address, remote identifier, and username, it seems pretty straightforward. However, when I try to set a password reference, I'm failing to figure out how to do so in a straight forward way. I've tried several methods from the docs and continuously yield no results, so I wanted to ask if I was doing something wrong in the following code (most of which is commented out, but indicated by single line comments where the attempts were). /** @class VPN contains all of the configuration and handling for enacting a VPN connection */ class VPN { // Initialize `manager` variable with `NEVPNManager` object using @method `shared()` let manager = NEVPNManager.shared() /** @variable vpnLoadHandler handles loading the VPN and error catching? */ private var vpnLoadHandler: (Error?) -> Void { return { (error:Error?) in if ((error) != nil) { print("Load VPN Configurations failed...") return; } // Initialize and assign `p` as `NEVPNProtocolIKEv2()` interface let p = NEVPNProtocolIKEv2() // Assign property values for the IKEv2 VPN p.serverAddress = "0.0.0.0" p.remoteIdentifier = "abc" p.username = "iosUser" // Assign string `pass` with string value of intended password let pass = "password" // Assign string `key` with string value of intended key let key = "pwd" // Create an add query to encode password as `Data` instance var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrGeneric as String: key, kSecValueData as String: pass] // Add the item to `passKeyValue` using `SecAddItem` let passKeyValue = SecItemAdd(query as CFDictionary, nil) // ALTERNATIVE VALUE ASSIGNMENT // let passKeyValue = SecItemCopyMatching(query as CFDictionary, nil) // Initiate search to access password from query // ATTEMPT 1 /* var item: CFTypeRef? guard let existingItem = item as? [String: Any], let passwordData = existingItem[kSecValueData as String] as? Data, let password = passwordData else { print("Keychain failed...") } */ // ATTEMPT 2 /* var error: Unmanaged<CFError>? guard let data = SecKeyCopyExternalRepresentation(passKeyValue, &error) as Data else { throw error!.takeRetainedValue() as Error } */ // ATTEMPT 3 /* var error: Unmanaged<CFError>? guard let pkData = SecKeyCreateWithData(data as CFData, query as CFDictionary, &error) else { throw error!.takeRetainedValue() as Error } */ } } } I'm just a little lost because as of a year ago, other similar code that I've referenced uses conventions of: let kcs = KeychainService(); kcs.save(key: "SHARED", value: "MY_SHARED_KEY") kcs.save(key: "VPN_PASSWORD", value: "MY_PASSWORD" Why has it changed? How would I go about achieving the same thing?
1
0
297
Jan ’24
SmartCard logon
Hello, I am developing a smartcard CTK extension for macOS. I have trouble to smartcard logon the first time after a reboot or a logout (e.g. when there is the text "Your password is required to enable touch id"). Trouble = I'm not asked for the PIN. But time to time after a logout (from whatever account), I can login with the smartcard. After a lockscreen I can always login with the smartcard. Is there an easy way to debug the logon process ? Regards, ++dom
6
0
673
Jun ’24
Is the code in 'Building a custom peer-to-peer protocol' insecure?
I'm new to Networking, so forgive me if this is a silly question: In the sample code, Building a custom peer-to-peer protocol, TLS is configured as follows: // Create TLS options using a passcode to derive a pre-shared key. private static func tlsOptions(passcode: String) -> NWProtocolTLS.Options { let tlsOptions = NWProtocolTLS.Options() let authenticationKey = SymmetricKey(data: passcode.data(using: .utf8)!) var authenticationCode = HMAC<SHA256>.authenticationCode(for: "TicTacToe".data(using: .utf8)!, using: authenticationKey) let authenticationDispatchData = withUnsafeBytes(of: &authenticationCode) { (ptr: UnsafeRawBufferPointer) in DispatchData(bytes: ptr) } sec_protocol_options_add_pre_shared_key(tlsOptions.securityProtocolOptions, authenticationDispatchData as __DispatchData, stringToDispatchData("TicTacToe")! as __DispatchData) sec_protocol_options_append_tls_ciphersuite(tlsOptions.securityProtocolOptions, tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!) return tlsOptions } The sample code touts the connection as secure ("...uses Bonjour and TLS to establish secure connections between nearby devices"), but to my untrained eye it doesn't seem so. My reasoning is as follows: If I adapt this code as-is, so connections between two instances of my app use SymmetricKeys derived from the four-digit passcode, then wouldn't my encryption be easy to break by an adversary who sends 0000...9999 and records corresponding changes in the encryption, exposing my app to all sorts of attacks? The sample uses the passcode to validate the connection (host user shows client user the passcode, which is manually entered), which is a feature I would like to keep in some form or another, which is why this is causing so many headaches. Generally speaking, is there a way to secure a local peer-to-peer connection over Network.framework that doesn't involve certificates? If certificates are the only way, are there good resources you can recommend?
6
0
745
May ’24
Type mismatch in SessionGetInfo() swift
The Apple documentation for SessionGetInfo for swift mentions that this API takes third argument of type UnsafeMutablePointer&lt;SessionAttributeBits&gt;? but I m getting the below error when I pass an argument of this type. Cannot convert value of type 'UnsafeMutablePointer&lt;SessionAttributeBits&gt;' to expected argument type 'UnsafeMutablePointer&lt;UInt32&gt;' Why is it expecting a different type. The documentation states otherwise. How to resolve this? Is this a Bug? public static func GetSessionInfo () -&gt; Void { var sessionID = SecuritySessionId() var sessionAttrs = SessionAttributeBits() let status = SessionGetInfo(callerSecuritySession, &amp;sessionID, &amp;sessionAttrs) //error:Cannot convert value of type 'UnsafeMutablePointer&lt;SessionAttributeBits&gt;' to expected argument type 'UnsafeMutablePointer&lt;UInt32&gt;' if status != errSessionSuccess { print("Could not get session info. Error \(status)") } }
6
0
598
Feb ’24
Secure enclave protected private key in CryptoKit vs Security framework
My goal is: Generate a public and private key pair Add the private key to the keychain and protect it with the secure enclave Create a self-signed certificate with the public key and send it to a server Add the certificate to the keychain When I communicate with the server I want to create a SecIdentity during the client challenge which is basically a SecCertificate + SecKey combo. For the certificate generation I would like to use the swift-certificates library to not have to compose manually the certificate fields and signature. My problem is that the swift-certificates during the Certificate initialisation needs a SecureEnclave.P256.Signing.PrivateKey private key and to add a key to the keychain we need a SecKey object. And unfortunately there is no clean way to create from one of them the other one. I read several threads here about this, but I haven't found a clean solution for it. I tried to approach the problem from two directions: First: Create the key with the SecKeyCreateRandomKey, mark in the attributes that I want to protect the key with secure enclave and also mark that I want the private key to be kSecAttrIsPermanent so it is automatically saved in the keychain The SecKeyCreateRandomKey returns a SecKey which is a reference to the private key from the keychain (!) Unfortunately I haven't found a clean way to convert a SecKey to a -&gt; SecureEnclave.P256.Signing.PrivateKey There is a workaround to SecKeyCopyAttributes of the private key and to extract the bytes from the attributes["toid"], but I guess it's not safe to use an undocumented key ("toid") if there is no constant defined to it (the name could be changed in future releases) Second approach: Create a SecureEnclave.P256.Signing.PrivateKey Create the Certificate using the swift-certificates The created private key is protected by the secure enclave but it's not added automatically to the keychain so we should add it to can query after that the SecIdentity (!) Unfortunately I haven't found a way to convert the SecureEnclave.P256.Signing.PrivateKey to -&gt; SecKey. There are threads which say that the SecKeyCreateWithData(...) helps us, but unfortunately if we set the kSecAttrTokenIDSecureEnclave in the attribute dictionary, the method creates a brand new key for us, regardless the passed data. So the initial key will never be the same as the newly created SecKey. This we can see in the method's implementation. So I got stuck with both approaches because seemingly there is no clean way to switch between SecureEnclave.P256.Signing.PrivateKey and SecKey. One solution would be to compose manually the certificate, without swift-certificates because like that we would not need a SecureEnclave.P256.Signing.PrivateKey object. But I would like to avoid the manual composition and signature calculation... Anybody has any idea?
2
1
932
Jan ’24
Private key is not accessible when device is locked
We have implemented a Notification Service Extension in our app to handle remote notification and access keychain to get certificate and identity to refresh network relay configuration. Using SecItemCopyMatching to get SecIdentityRef works when device is unlocked. Whenever push notification arrives and device is locked, our notification service extension failed to access keychain to get identity reference with error code -25308 errSecInteractionNotAllowed. It looks like keychain is locked when device is locked. Is there a way to make keychain unlocked?
1
0
475
Jan ’24
Screensaver is not coming when system.login.screensaver is updated to use authenticate-session-owner-or-admin
On recent macOS versions(Sonoma or previous), if system.login.screensaver is updated to use “authenticate-session-owner-or-admin” then fancy screensaver is not coming up, instead we are seeing only black screensaver ( black screen). Note: Observed we are getting fancy screensavers with this setting on macOS BigSur. Can you please let us know if this is an intentional change from macOS or we have any settings to enable to get fancy screensavers with recent macOS versions? Thanks &amp; Regards, Tata Chaitanya
2
0
463
Jan ’24
APNS Key Vs Certificate Security
I've learned that providing an APNS “Key (Cannot expire)” instead of an APNS “Certificate (Can expire)” will provide the app "access to all topics" for all apps within the organization ‘team’ that the key is forged from. 1.) Can someone elaborate on the specifics for what that means from a security prospective? For instance, if my organization 'team' manages many applications under the same umbrella account and provides the same (or different) APNS key to each app, but one of the apps accidentally (or intentionally) wants to utilize the APNS key to affect the other apps, what are the potential consequences? And, is it possible to create a new APNS key for each app to close any security concerns for multiple apps managed under the same account, or are we stuck with every key having access to all topics?
1
1
1.1k
Jan ’24
Unable to create 'Shared Web Credentials' on fresh TestFlight Install
Hey Apple team (and eskimo 🙏), Our FinTech app uses iCloud Keychain shared web credentials to store a secure encryption password in iCloud Keychain. Some of our new users seem to run into an issue where the app fails to successfully create a shared web credential. All users are required to have the following two settings enabled: Settings --&gt; Passwords --&gt; Password Options --&gt; Autofill from iCloud Passwords &amp; Keychain Settings --&gt; Apple D - -&gt; iCloud - -&gt; Passwords and Keychain --&gt; 'Sync this iPhone' The issue appears to resolve itself when the user restarts their iPhone. We've had this bug 3 times now and would like to understand the root cause. We have a couple hypotheses: iOS is failing to verify that the domain for the shared web credential is valid via &lt;domain&gt;/.well-known/apple-app-site-association (and then restarting triggers reverification) Users were on a version of iOS where it was bugged (and then restarting finally completed an update to a new version). We've verified that the bug happened on 17.0.2 with one user (until they updated and it fixed itself)
1
0
491
Jan ’24
Keychain change notifications?
Is there a way to find out when the set of keychains changes? ie, when a keychain is added or removed? I searched here and grepped through the headers in Security.framework but nothing leaped out at me -- which could just mean I missed something, as happens frequently. (This is on macOS.)
4
0
454
Jan ’24
Firebase’s Remote Config in context of an Authorization Plugin
I am trying to use Firebase’s Remote Config in the context of an Authorization Plugin. I’m doing this in order to implement feature flag support in our Auth Plugin. When I try to fetch remote Firebase settings, I get a -34018 indicating that there is an error with access to the keychain on the Mac. Based on https://forums.developer.apple.com/forums/thread/114456, I have an entitlement problem. It’s my impression that it is not possible to grant entitlements to an Authorization Plugin, so I’m wondering if this kind of keychain access that Firebase requires is simply not possible. Or, if perhaps there is something I can do with entitlements to get this to work? Working with macOS 13.6.2, XCode 15.1
3
0
476
Jan ’24
Find Internet password from keychain?
I have a internet password stored in my keychain with below details: Internet Password Item: Account: user Server: some Ip address(Let's say w.x.y.z) Protocol: htpx But when I use the below code, I receive item not found. But when I remove kSecAttrProtocol attribute from my dictionary, it works. The document says kSecProtocolTypeHTTPProxy corresponds to htpx. Not sure what I am doing wrong, Please guide. I have a dependency on SecProtocolType in my code to look for an internet password in keychain. https://developer.apple.com/documentation/security/secprotocoltype/ksecprotocoltypehttpproxy/ NSString *account = @"user"; NSString *server = @"w.x.y.z"; SecProtocolType protocol = kSecProtocolTypeHTTPProxy; NSDictionary *query = @{ (__bridge id)kSecClass: (__bridge id)kSecClassInternetPassword, (__bridge id)kSecAttrAccount: account, (__bridge id)kSecAttrServer: server, (__bridge id)kSecAttrProtocol:@(protocol), (__bridge id)kSecReturnAttributes: (__bridge id)kCFBooleanTrue, (__bridge id)kSecReturnData: (__bridge id)kCFBooleanFalse, (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne }; CFDictionaryRef result = NULL; OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&amp;result); if (status == errSecSuccess) { NSDictionary *passwordItem = CFBridgingRelease(result); NSLog(@"Internet Password Item Found:"); } else if (status == errSecItemNotFound) { NSLog(@"Internet Password Item Not Found"); } else { NSLog(@"Error retrieving Internet password: %d (%@)", (int)status, CFBridgingRelease(SecCopyErrorMessageString(status, NULL))); }
3
0
464
Jan ’24
Custom SFAuthorizationPluginView for Lock Screen
Hi, I have a bundle with my custom lock screen which is a subclass of SFAuthorizationPluginView. I have implemented : override func view(for viewType: SFViewType) -> NSView? and override func buttonPressed(_ inButtonType: SFButtonType), as required in apple's documentation. I have replaced the default UI in the system.login.screensaver.plist with my mchanism. (the custom plist is in the end of this post) When I lock the screen, I get a black screen with the mouse hovering over. I can see in my logs that my view is loaded and the overriden function view(for viewType: SFViewType) is called. When I change the authenticate.plist to display my custom UI, it is displayed properly. Why do I get a black screen when activating the lock screen, but do get my UI when authentication is needed? What I am missing with the lock screen? Here is the system.login.screensaver.plist: ################################################################## <key>class</key> <string>evaluate-mechanisms</string> <key>comment</key> <string>The owner or any administrator can unlock the screensaver, set rule to &quot;authenticate-session-owner-or-admin&quot; to enable SecurityAgent.</string> <key>created</key> <real>711292439.260325</real> <key>mechanisms</key> <array> <string>MyBnndle:LockScreen</string> </array> <key>modified</key> <real>717407094.6108691</real> <key>shared</key> <true/> <key>tries</key> <integer>10000</integer> <key>version</key> <integer>1</integer> cheers, sivan
1
0
375
Jan ’24
Stealth Mode broken in Sleep
Hello here, There is a macOS feature called Stealth Mode under Firewall in System Settings. It's supposedly blocks ICMP request messages (aka Ping). It seems to work fine, only until the device is put to sleep. This can be done either manually from Apple Menu -> Sleep, or by simply closing the MacBook lid. The device suddenly starts replying to pings roughly 10 seconds after entering sleep mode. Exactly the same seems to happen even if I enable pf with a rule: block all Does anyone know what's happening? Seems like packet filtering or firewall is not applied anymore after the OS is put to sleep. Are the ICMP packets handled by the Kernel or WNIC firmware after sleep? I reported this through Apple Feedback Assistant but they were very dismissive and simply said they were not able to reproduce this.
0
0
282
Jan ’24
Unable to consistently detect lock/unlock events with Swift
I need to detect lock & unlock events in my swift iOS application. I have tried using AppDelegate functions like UIApplicationProtectedDataWillBecomeUnavailable & UIApplicationProtectedDataDidBecomeAvailable to record the lock and unlock events respectively, but have found this to be inconsistent. UIApplicationProtectedDataWillBecomeUnavailable is not called immediately after the lock event, and sometimes misses the event altogether. Is there a different approach to this problem that guarantees detecting lock & unlock correctly every time?
2
0
517
Jan ’24