Prioritize user privacy and data security in your app. Discuss best practices for data handling, user consent, and security measures to protect user information.

All subtopics
Posts under Privacy & Security topic

Post

Replies

Boosts

Views

Activity

Detecting masked Face ID enrolment via evaluatedPolicyDomainState
Hi, iOS 15.4 is bringing a new exciting security feature which allows users to enroll "masked face" so they can unlock their devices while wearing a mask. Some apps might leverage evaluatedPolicyDomainState (https://developer.apple.com/documentation/localauthentication/lacontext/1514150-evaluatedpolicydomainstate) to detect if the biometric state has changed, and if so, logging out/locking the user to protect their data. Looks like the masked-face enrolment changes the policy domain state as such it might lead to many unexpected logouts. Is there any way to detect if the change to the state was introduced by the masked face enrollment as such we can somehow retain the user's login session? Many thanks!
1
0
2.1k
May ’22
Password input view is not showing
I am working on Token extension on iOS. Apple documentation say if We throw error with error code "TKError.Code.authenticationNeeded.rawValue" will trigger user authentication. In my TKTokenSessionDelegate class in sign dataToSign function i am throwing this error but my extension is not showing authentication screen. Any Idea what i am missing.
3
0
2.1k
Feb ’23
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.8k
Apr ’22
How to trust self signed certificate programmatically ?
My app is using a self signed certificate and we are planning to use the same in production. To avoid asking user to install the certificate manually, can I add the certificate to the list of trusted anchors using SecTrustSetAnchorCertificates(_: _:). Is this a correct approach ? Please find the code below:   func addAnchorToTrust(trust: SecTrust, certificate: SecCertificate) -> SecTrust {         let array: NSMutableArray = NSMutableArray()         array.add(certificate)         SecTrustSetAnchorCertificates(trust, array)         return trust     }     func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {         guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let filePath = Bundle.main.path(forResource: "httpsPublicCertificate", ofType: "cer")         guard let file = filePath, let savedCertificateData = NSData(contentsOfFile: file), let rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, savedCertificateData) else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let sslInput = addAnchorToTrust(trust: serverTrust, certificate: rootCert)         var result: SecTrustResultType = SecTrustResultType.unspecified         let error: OSStatus = SecTrustEvaluate(sslInput, &result)         if (error != 0){             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         guard self.validate(trust: serverTrust, with: SecPolicyCreateBasicX509()), let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)         else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let serverCertificateData = SecCertificateCopyData(serverCertificate)         let serverCertificateDataPtr = CFDataGetBytePtr(serverCertificateData);         let serverCertificateDataSize = CFDataGetLength(serverCertificateData);         let serverCertificateNSData = NSData(bytes: serverCertificateDataPtr, length: serverCertificateDataSize)         if serverCertificateNSData.isEqual(to: savedCertificateData as Data) {             completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))             return         }     }     private func validate(trust: SecTrust, with policy: SecPolicy) -> Bool {         let status = SecTrustSetPolicies(trust, policy)         guard status == errSecSuccess else { return false }         return SecTrustEvaluateWithError(trust, nil)     }
2
0
3.2k
Mar ’22
keychain question
The project uses keychain to store data. When kSecAttrAccessible is set to kSecAttrAccessibleAfterFirstUnlock or this property is not set, Apple backs up the system and restores it to the new machine. Will the data stored in the keychain be transferred to the new machine? Will the data in UserDefault be additionally transferred to the new machine?
0
0
480
Mar ’22
SecItem created with kSecAttrAccessControl is not visible in the keychain
I'm trying to save a password to the keychain using the kSecAttrAccessControl attribute to control access. This is the code I'm running: let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, .userPresence, nil) let attributes = [kSecClass: kSecClassGenericPassword, kSecAttrService: forPath,   kSecAttrLabel: "My Password",   kSecAttrAccessControl: access as Any,   kSecValueData: password.data(using: .utf8) as Any] as CFDictionary SecItemAdd(attributes, nil) The item is being created and I can find it using SecItemCopyMatching but it is not visible in the Keychain Access app. If I remove kSecAttrAccessControl from the list of attribtues, then the created item is visible in Keychain Access.
5
0
950
Mar ’22
SHA1 fingerprint calculation(iOS)
i would like to know how to calculate SHA1 fingerprint in ios swift, i am trying to calculate it on runtime to have some potential checking of integrity of my application. I know macos has some direct APIs to get it but i dont know how can we achieve this in iOS as well. P.S. I am new to iOS development , so please bear with me if i ask some naive questions in this thread.
2
0
1.3k
Apr ’22
TLS For Accessory Developers
I often get questions about disabling the HTTPS default server trust evaluation done by NSURLSession. My general advice is “Don’t do that!” However, there is one case where you have to do that, namely when dealing with a hardware accessory on the local network. This post contains my advice on how to deal with that situation. IMPORTANT If you found your way here and you’re not developing a network-based accessory, I have two suggestions for you: If you’re trying to override HTTPS server trust evaluation for testing purposes, see QA1948 HTTPS and Test Servers. If not, post a question here on DevForums and we’ll try to get you heading in the right direction. Tag it with Security, and either CFNetwork or Network depending on which API you’re using. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" TLS For Accessory Developers Communicating securely with a network-based accessory is tricky because the standard network security protocol, TLS, was designed for the wider Internet, where servers have a stable DNS name. A devices on your local network doesn’t have a stable DNS name. The DNS name my-waffle-maker.local. might resolve to your waffle maker today, but tomorrow it might resolve to a different waffle maker or, worse yet, a malicious waffle varnisher. I guarantee that you won’t like them waffles! Note If you’re unfamiliar with TLS in general, I encourage you to read TLS for App Developers first. TLS puts the S into HTTPS. This post focuses on URLSession and HTTPS, because that’s where this most commonly crops up, but similar logic applies to other networking APIs. Doing the Minimum: The SSH Approach Many accessory firmware developers support TLS by generating a self-signed digital identity on the accessory and using that for their HTTPS server. IMO they should do better — the subject of later sections in this post — but sometimes you have to work with what you’ve got. If you’re working with an accessory like this, and you can’t convince the firmware developer to do better, I recommend that you adopt the SSH approach. In this approach you accept the certificate offered by the accessory the first time and then, when you connect again in the future, check the accessory still has the same certificate. Note I call this the SSH approach because that’s how many folks use SSH. To implement the SSH approach, first disable App Transport Security for local networking by setting the NSAllowsLocalNetworking property. On modern systems this isn’t strictly necessary but, as it says in the docs, this is a good “declaration of intent”. Next, override HTTPS server trust evaluation as shown below: var expectedCertificate: SecCertificate? = nil func shouldAllowHTTPSConnection(trust: SecTrust) async -> Bool { guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let actual = chain.first else { return false } guard let expected = self.expectedCertificate else { // A. First connection self.expectedCertificate = actual return true } // B. Subsequent connections return CFEqual(expected, actual) } func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodServerTrust: let trust = challenge.protectionSpace.serverTrust! guard await self.shouldAllowHTTPSConnection(trust: trust) else { return (.cancelAuthenticationChallenge, nil) } let credential = URLCredential(trust: trust) return (.useCredential, credential) default: return (.performDefaultHandling, nil) } } There are a few things to note here: The snippet uses the new Swift async/await syntax. That simplifies the code and it also avoids a gotcha with the old completion-handler approach, where it was easy to forget to call the completion handler. Having said that, you can achieve the same result without using Swift async/await, or indeed, in Objective-C. The authentication challenge handler only deals with HTTPS server trust challenges (NSURLAuthenticationMethodServerTrust). Critically, if it finds a challenge it doesn’t recognise, it resolves that in the default way (.performDefaultHandling). The shouldAllowHTTPSConnection(trust:) method checks to see if it’s connected to the server before. If not, it defaults to allowing the connection (case A). If so, it checks that the certificate hasn’t changed (case B). In a real app you would persist expectedCertificate so that this logic continues to apply the next time your app is launched. When you do that, store the certificate using a key that uniquely identifies the accessory. Do not use the DNS name or IP address because that can change. The first time you connect (case A) you might take other steps to confirm the identity of the accessory. This is something I’ll cover below. The thing to note here is that this function is async, so you can take your time doing that confirmation. For example, you could bounce over to the main actor and display a UI. Doing Better: Add a Side Channel The above represents the absolute minimum you should do; anything less is doing the user a disservice. Aim to do better! Doing better requires some sort of side channel so that the user can confirm the identity of the accessory. For example: If the accessory has a display, you might present a UI asking the user to confirm that the code in your UI matches the one on the accessory’s display. If the accessory has a LED, it might blink that during this initial setup process. If the accessory has a serial number, you might ask the user to confirm that. Or scan that via a barcode. Note For an example of the barcode approach, see Matt’s Configuring a Wi-Fi Accessory to Join the User’s Network sample. This sample uses a different technique for TLS, namely TLS-PSK. This has some advantages — most notably, it avoids messing around with certificates — but I’m not discussing it here because it’s not supported by URLSession. If you adopt this approach make sure that you present a UI that the user can understand. If your UI contains raw certificate details, most users will just say “Sure, whatever.” and click OK, at which point you might as well have saved everyone’s time by accepting the connection on their behalf. Take care not to blindly trust any information you get from the accessory. After all, the goal here is to check the identity of the accessory, and so you mustn’t trust it before completing that check. Sometimes this can be quite subtle. Consider the accessory-with-a-display example above. In that case the accessory’s self-signed certificate might contain a common name of Acme Waffle Maker CCC, where CCC is the code showing on its display. Don’t display the entire string to the user. The presence of Acme Waffle Maker might lead the user to believe that the accessory is valid, even when it isn’t. After all, a malicious waffle varnisher can just as easily create a self-signed certificate with that common name. Rather, extract the code (CCC) and display just that. That way the user will focus on what’s important. Doing Even Better: Proper Security If the accessory’s firmware and hardware developers are on board, there are steps you can take to properly secure your communication with the accessory: Create a custom certificate authority (CA) for your accessories. At the factory, have that CA issue a certificate to each accessory as its produced, embedding identifying details, like the serial number, in that certificate. Then install that certificate and its associated private key (thus forming a digital identity) on the accessory as it comes off the line. Embed the CA’s certificate in your app. When you connect the accessory, verify that its certificate was issued by your CA. If it was, you can trust the identifying information, like the serial number, embedded in that certificate. With this setup your app will never connect to a malicious accessory. The worst that can happen is that you accidentally connect to the wrong instance of your accessory. IMPORTANT This is just an outline of one approach that I believe offers specific advantages. If you plan to deploy this in practice, hire a security profession to design your process. They can advise you on the details of creating a system that’s secure in practice. For example, they can help you: Create a mechanism that prevents your factory from leaking valid digital identities. Design your hardware to prevent an attacker from extracting an accessory’s digital identity from the accessory itself. To implement the URLSession side of this, change the shouldAllowHTTPSConnection(trust:) method like so: let waffleVarnisherCA: SecCertificate = { let u = Bundle.main.url(forResource: "WaffleVarnisherCA", withExtension: "cer")! let d = try! Data(contentsOf: u) let c = SecCertificateCreateWithData(nil, d as NSData)! return c }() func shouldAllowHTTPSConnection(trust: SecTrust) async -> Bool { var err = SecTrustSetPolicies(trust, SecPolicyCreateBasicX509()) guard err == errSecSuccess else { return false } err = SecTrustSetAnchorCertificates(trust, [self.waffleVarnisherCA] as NSArray) guard err == errSecSuccess else { return false } err = SecTrustSetAnchorCertificatesOnly(trust, true) guard err == errSecSuccess else { return false } let wasIssuedByOurCA = SecTrustEvaluateWithError(trust, nil) guard wasIssuedByOurCA else { return false } guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let trustedLeaf = chain.first else { return false } // C. Check the now-trusted leaf certificate return true } There are a few things to note about this code: It changes the trust policy (SecTrustSetPolicies) to the basic X.509 policy (SecPolicyCreateBasicX509) because the standard policy for TLS connections checks the DNS name, and that’s not appropriate for an accessory on the local network. It applies a custom anchor (SecTrustSetAnchorCertificates) and then disables all the other anchors (SecTrustSetAnchorCertificatesOnly) [1]. That prevents someone from impersonating your accessory by getting some other CA to issue a certificate that looks like the accessory’s certificate. It evaluates trust to confirm that the certificate was issued by the accessory’s CA. At point C you can trust the details in the accessory’s certificate (trustedLeaf). Here you might add code to confirm the identity of the accessory, to prevent you from accidentally connecting to the wrong accessory. [1] This is not strictly necessary because calling SecTrustSetAnchorCertificates disables other anchors. However, I’m applying both belt and braces [2] here. [2] I’m using the British idiom because belt and suspenders is so wrong (-:
0
0
3.0k
Mar ’22
How do I find the security session id for a pid?
I am building a somewhat-VPN-like system. I have a daemon that handles the networking and a couple of agents that interact with the logged-in user. The daemon and agent communicate via XPC. I am trying to get this to work "smoothly" with fast-user-switching. Empirically, I find that the daemon can correlate XPC connection from different agents in the different login sessions via xpc_connection_get_asid(), which appears to be equivalent to the security session id, though it's not clear this this equivalence is always they case, nor will always be the case in the future. If I had a way to get the security session id for a pid, I would use xpc_connection_get_pid() When the daemon gets a network connection I want to find the pid the connection is coming from (it can only be from the local machine) and figure out which security session that pid belongs to so that I can direct any necessary user interaction and permission checking to the agent in the security session from which the network request is coming. Finding the pid from the TCP port is arduous and inefficient, but doable. However, once I've found the pid, I don't know how to determine the security session id (or audit session id) that that pid is part of. GetSessionInfo appears to permit me to get information about my own session id including my session id, or additional info about another session, if I already have that session id. For my purposes, a viable alternative to being able to get the security session for a pid might be to be able to ask the question "Is this pid part of this security session?" since I expect to have agents in a small number of security sessions. Getting the username of the pid is obviously doable, however this would mean that I would be unable to determine where a sudo'ed process was coming from (at least not without walking up the parent heirarchy). This feels dicey. Am I missing something?
2
0
1.5k
Apr ’22
Erasing all browser data removes credential manager data - WebAuthN iOS 14+
Greetings, I've working lately with webauthn navigator feature in order to make users registrations and logins with Touch ID or any other sign option that the device might offer. To give a quick context: in my webapp I register users using username + webauthn and store their credentials.id from navigator.credentials.create() and generate a pubKey that it's being store at local storage and in our DB, which is the same for the credential.id. Despite the fact that I can use my device to use my webapp after the creation of this account and using navigator.credentials.get() I'm able to log with my account with no problem but, if I go to settings > safari > clear all browser data & history I can end up destroying my access to my webapp, even though that I have the credentials on my server. Is this an expected behaviour? If I do the same on different devices, this does not happen, in fact accounts are able to log even if the browser does not have data anymore, since it only removes the browser data and not the Credential Manager data. Also, for Mac devices these keys are only accessible per browser, which mean that I have to link those different browsers as secondary devices so the user can login at any browser that they have on their device. Is this expected?
1
0
1.5k
Apr ’22
SMJobBless privileged helpers and granting permission
I have a signed, notarized app that makes use of a privileged helper. In macOS 11 and 12, as noted in several places in the documentation, there was/is an increasing requirement for the user to grant permission for things over prior macOS releases. This is great, I'm on board. I've found that the privileged helper now needs the broad "Full Disk Access". How do I get the Finder to ask the user permission for this? My helper has the special text sections called "__info_plist" and "__launchd_plist" and I tried putting what I think should go into them in those but I didn't have any luck. Is there another section I need to know about or did I just mess something else up? I'm not using Xcode or Swift or ObjectiveC, everything is C++/C and the command line tools. My helper and Application use XPC to communicate with each other. Thanks! (after my helper fails it does show up in the Full Disk Access list, if you check that pref and try again it all works, I don't want my users to ever have to do that)
5
0
1.7k
Apr ’22
Write Permissions Error (-61) returned by SecItemAdd() Objective-C API
The Keychain API SecItemAdd() returns -61 status code. Programming Language: objective-c OS: Mac BigSur 11.6.3 Default keychain: /Users/user_name/Library/Keychains/login.keychain-db Ownership: UID and GID of logged in user match those of the keychain Status of keychain as reported by SecKeychainGetStatus(): 7 (unlocked + read-permission + write-permission) Test runs fine in local environment but fails in CI environment
1
0
1.5k
Apr ’22
How to read
{"message":{"Count":8,"bundleID":"org.whispersystems.signal","position":"background","sum_of_duration":91},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"} {"message":{"Count":6,"bundleID":"org.whispersystems.signal","position":"foreground","sum_of_duration":410},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"l"} {"message":{"Count":2,"bundleID":"org.whispersystems.signal.SignalNSE","position":"background","sum_of_duration":20},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":""} {"message":{"Count":3,"bundleID":"org.whispersystems.signal.shareextension","position":"background","sum_of_duration":3},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"} {"message":{"Count":3,"bundleID":"org.whispersystems.signal.shareextension","position":"foreground","sum_of_duration":26},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":2"} {"message":{"Count":3685,"sum_of_initParameterCurve":null,"sum_of_initParameterCurve_SPI":null,"sum_of_initPatternPlayer":1,"sum_of_initPatternPlayer_SPI":550,"sum_of_startHapticEngine":3,"sum_of_startHapticEngine_SPI":1200},"name":"CH_Metrics_ProductUsage","sampling":10,"uuid":""}
0
0
1.1k
Apr ’22
Detecting masked Face ID enrolment via evaluatedPolicyDomainState
Hi, iOS 15.4 is bringing a new exciting security feature which allows users to enroll "masked face" so they can unlock their devices while wearing a mask. Some apps might leverage evaluatedPolicyDomainState (https://developer.apple.com/documentation/localauthentication/lacontext/1514150-evaluatedpolicydomainstate) to detect if the biometric state has changed, and if so, logging out/locking the user to protect their data. Looks like the masked-face enrolment changes the policy domain state as such it might lead to many unexpected logouts. Is there any way to detect if the change to the state was introduced by the masked face enrollment as such we can somehow retain the user's login session? Many thanks!
Replies
1
Boosts
0
Views
2.1k
Activity
May ’22
Password input view is not showing
I am working on Token extension on iOS. Apple documentation say if We throw error with error code "TKError.Code.authenticationNeeded.rawValue" will trigger user authentication. In my TKTokenSessionDelegate class in sign dataToSign function i am throwing this error but my extension is not showing authentication screen. Any Idea what i am missing.
Replies
3
Boosts
0
Views
2.1k
Activity
Feb ’23
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.8k
Activity
Apr ’22
How to trust self signed certificate programmatically ?
My app is using a self signed certificate and we are planning to use the same in production. To avoid asking user to install the certificate manually, can I add the certificate to the list of trusted anchors using SecTrustSetAnchorCertificates(_: _:). Is this a correct approach ? Please find the code below:   func addAnchorToTrust(trust: SecTrust, certificate: SecCertificate) -> SecTrust {         let array: NSMutableArray = NSMutableArray()         array.add(certificate)         SecTrustSetAnchorCertificates(trust, array)         return trust     }     func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {         guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let filePath = Bundle.main.path(forResource: "httpsPublicCertificate", ofType: "cer")         guard let file = filePath, let savedCertificateData = NSData(contentsOfFile: file), let rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, savedCertificateData) else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let sslInput = addAnchorToTrust(trust: serverTrust, certificate: rootCert)         var result: SecTrustResultType = SecTrustResultType.unspecified         let error: OSStatus = SecTrustEvaluate(sslInput, &result)         if (error != 0){             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         guard self.validate(trust: serverTrust, with: SecPolicyCreateBasicX509()), let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)         else {             completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)             return         }         let serverCertificateData = SecCertificateCopyData(serverCertificate)         let serverCertificateDataPtr = CFDataGetBytePtr(serverCertificateData);         let serverCertificateDataSize = CFDataGetLength(serverCertificateData);         let serverCertificateNSData = NSData(bytes: serverCertificateDataPtr, length: serverCertificateDataSize)         if serverCertificateNSData.isEqual(to: savedCertificateData as Data) {             completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))             return         }     }     private func validate(trust: SecTrust, with policy: SecPolicy) -> Bool {         let status = SecTrustSetPolicies(trust, policy)         guard status == errSecSuccess else { return false }         return SecTrustEvaluateWithError(trust, nil)     }
Replies
2
Boosts
0
Views
3.2k
Activity
Mar ’22
keychain question
The project uses keychain to store data. When kSecAttrAccessible is set to kSecAttrAccessibleAfterFirstUnlock or this property is not set, Apple backs up the system and restores it to the new machine. Will the data stored in the keychain be transferred to the new machine? Will the data in UserDefault be additionally transferred to the new machine?
Replies
0
Boosts
0
Views
480
Activity
Mar ’22
SecItem created with kSecAttrAccessControl is not visible in the keychain
I'm trying to save a password to the keychain using the kSecAttrAccessControl attribute to control access. This is the code I'm running: let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, .userPresence, nil) let attributes = [kSecClass: kSecClassGenericPassword, kSecAttrService: forPath,   kSecAttrLabel: "My Password",   kSecAttrAccessControl: access as Any,   kSecValueData: password.data(using: .utf8) as Any] as CFDictionary SecItemAdd(attributes, nil) The item is being created and I can find it using SecItemCopyMatching but it is not visible in the Keychain Access app. If I remove kSecAttrAccessControl from the list of attribtues, then the created item is visible in Keychain Access.
Replies
5
Boosts
0
Views
950
Activity
Mar ’22
Thread Error - NSHealthUpdateUsageDescription set in Info.plist
I'm trying to request access to read/write from HealthKit but am un able to figure out how to solve this error. When I attempt to put in "NSHealthUpdateUsageDescription" to my Info.plist file I get the Privacy - "Update Usage Description" equivalent, but still get this error. I'm working with some code based on WWDC20 10664.
Replies
0
Boosts
0
Views
598
Activity
Mar ’22
SHA1 fingerprint calculation(iOS)
i would like to know how to calculate SHA1 fingerprint in ios swift, i am trying to calculate it on runtime to have some potential checking of integrity of my application. I know macos has some direct APIs to get it but i dont know how can we achieve this in iOS as well. P.S. I am new to iOS development , so please bear with me if i ask some naive questions in this thread.
Replies
2
Boosts
0
Views
1.3k
Activity
Apr ’22
TLS For Accessory Developers
I often get questions about disabling the HTTPS default server trust evaluation done by NSURLSession. My general advice is “Don’t do that!” However, there is one case where you have to do that, namely when dealing with a hardware accessory on the local network. This post contains my advice on how to deal with that situation. IMPORTANT If you found your way here and you’re not developing a network-based accessory, I have two suggestions for you: If you’re trying to override HTTPS server trust evaluation for testing purposes, see QA1948 HTTPS and Test Servers. If not, post a question here on DevForums and we’ll try to get you heading in the right direction. Tag it with Security, and either CFNetwork or Network depending on which API you’re using. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" TLS For Accessory Developers Communicating securely with a network-based accessory is tricky because the standard network security protocol, TLS, was designed for the wider Internet, where servers have a stable DNS name. A devices on your local network doesn’t have a stable DNS name. The DNS name my-waffle-maker.local. might resolve to your waffle maker today, but tomorrow it might resolve to a different waffle maker or, worse yet, a malicious waffle varnisher. I guarantee that you won’t like them waffles! Note If you’re unfamiliar with TLS in general, I encourage you to read TLS for App Developers first. TLS puts the S into HTTPS. This post focuses on URLSession and HTTPS, because that’s where this most commonly crops up, but similar logic applies to other networking APIs. Doing the Minimum: The SSH Approach Many accessory firmware developers support TLS by generating a self-signed digital identity on the accessory and using that for their HTTPS server. IMO they should do better — the subject of later sections in this post — but sometimes you have to work with what you’ve got. If you’re working with an accessory like this, and you can’t convince the firmware developer to do better, I recommend that you adopt the SSH approach. In this approach you accept the certificate offered by the accessory the first time and then, when you connect again in the future, check the accessory still has the same certificate. Note I call this the SSH approach because that’s how many folks use SSH. To implement the SSH approach, first disable App Transport Security for local networking by setting the NSAllowsLocalNetworking property. On modern systems this isn’t strictly necessary but, as it says in the docs, this is a good “declaration of intent”. Next, override HTTPS server trust evaluation as shown below: var expectedCertificate: SecCertificate? = nil func shouldAllowHTTPSConnection(trust: SecTrust) async -> Bool { guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let actual = chain.first else { return false } guard let expected = self.expectedCertificate else { // A. First connection self.expectedCertificate = actual return true } // B. Subsequent connections return CFEqual(expected, actual) } func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodServerTrust: let trust = challenge.protectionSpace.serverTrust! guard await self.shouldAllowHTTPSConnection(trust: trust) else { return (.cancelAuthenticationChallenge, nil) } let credential = URLCredential(trust: trust) return (.useCredential, credential) default: return (.performDefaultHandling, nil) } } There are a few things to note here: The snippet uses the new Swift async/await syntax. That simplifies the code and it also avoids a gotcha with the old completion-handler approach, where it was easy to forget to call the completion handler. Having said that, you can achieve the same result without using Swift async/await, or indeed, in Objective-C. The authentication challenge handler only deals with HTTPS server trust challenges (NSURLAuthenticationMethodServerTrust). Critically, if it finds a challenge it doesn’t recognise, it resolves that in the default way (.performDefaultHandling). The shouldAllowHTTPSConnection(trust:) method checks to see if it’s connected to the server before. If not, it defaults to allowing the connection (case A). If so, it checks that the certificate hasn’t changed (case B). In a real app you would persist expectedCertificate so that this logic continues to apply the next time your app is launched. When you do that, store the certificate using a key that uniquely identifies the accessory. Do not use the DNS name or IP address because that can change. The first time you connect (case A) you might take other steps to confirm the identity of the accessory. This is something I’ll cover below. The thing to note here is that this function is async, so you can take your time doing that confirmation. For example, you could bounce over to the main actor and display a UI. Doing Better: Add a Side Channel The above represents the absolute minimum you should do; anything less is doing the user a disservice. Aim to do better! Doing better requires some sort of side channel so that the user can confirm the identity of the accessory. For example: If the accessory has a display, you might present a UI asking the user to confirm that the code in your UI matches the one on the accessory’s display. If the accessory has a LED, it might blink that during this initial setup process. If the accessory has a serial number, you might ask the user to confirm that. Or scan that via a barcode. Note For an example of the barcode approach, see Matt’s Configuring a Wi-Fi Accessory to Join the User’s Network sample. This sample uses a different technique for TLS, namely TLS-PSK. This has some advantages — most notably, it avoids messing around with certificates — but I’m not discussing it here because it’s not supported by URLSession. If you adopt this approach make sure that you present a UI that the user can understand. If your UI contains raw certificate details, most users will just say “Sure, whatever.” and click OK, at which point you might as well have saved everyone’s time by accepting the connection on their behalf. Take care not to blindly trust any information you get from the accessory. After all, the goal here is to check the identity of the accessory, and so you mustn’t trust it before completing that check. Sometimes this can be quite subtle. Consider the accessory-with-a-display example above. In that case the accessory’s self-signed certificate might contain a common name of Acme Waffle Maker CCC, where CCC is the code showing on its display. Don’t display the entire string to the user. The presence of Acme Waffle Maker might lead the user to believe that the accessory is valid, even when it isn’t. After all, a malicious waffle varnisher can just as easily create a self-signed certificate with that common name. Rather, extract the code (CCC) and display just that. That way the user will focus on what’s important. Doing Even Better: Proper Security If the accessory’s firmware and hardware developers are on board, there are steps you can take to properly secure your communication with the accessory: Create a custom certificate authority (CA) for your accessories. At the factory, have that CA issue a certificate to each accessory as its produced, embedding identifying details, like the serial number, in that certificate. Then install that certificate and its associated private key (thus forming a digital identity) on the accessory as it comes off the line. Embed the CA’s certificate in your app. When you connect the accessory, verify that its certificate was issued by your CA. If it was, you can trust the identifying information, like the serial number, embedded in that certificate. With this setup your app will never connect to a malicious accessory. The worst that can happen is that you accidentally connect to the wrong instance of your accessory. IMPORTANT This is just an outline of one approach that I believe offers specific advantages. If you plan to deploy this in practice, hire a security profession to design your process. They can advise you on the details of creating a system that’s secure in practice. For example, they can help you: Create a mechanism that prevents your factory from leaking valid digital identities. Design your hardware to prevent an attacker from extracting an accessory’s digital identity from the accessory itself. To implement the URLSession side of this, change the shouldAllowHTTPSConnection(trust:) method like so: let waffleVarnisherCA: SecCertificate = { let u = Bundle.main.url(forResource: "WaffleVarnisherCA", withExtension: "cer")! let d = try! Data(contentsOf: u) let c = SecCertificateCreateWithData(nil, d as NSData)! return c }() func shouldAllowHTTPSConnection(trust: SecTrust) async -> Bool { var err = SecTrustSetPolicies(trust, SecPolicyCreateBasicX509()) guard err == errSecSuccess else { return false } err = SecTrustSetAnchorCertificates(trust, [self.waffleVarnisherCA] as NSArray) guard err == errSecSuccess else { return false } err = SecTrustSetAnchorCertificatesOnly(trust, true) guard err == errSecSuccess else { return false } let wasIssuedByOurCA = SecTrustEvaluateWithError(trust, nil) guard wasIssuedByOurCA else { return false } guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let trustedLeaf = chain.first else { return false } // C. Check the now-trusted leaf certificate return true } There are a few things to note about this code: It changes the trust policy (SecTrustSetPolicies) to the basic X.509 policy (SecPolicyCreateBasicX509) because the standard policy for TLS connections checks the DNS name, and that’s not appropriate for an accessory on the local network. It applies a custom anchor (SecTrustSetAnchorCertificates) and then disables all the other anchors (SecTrustSetAnchorCertificatesOnly) [1]. That prevents someone from impersonating your accessory by getting some other CA to issue a certificate that looks like the accessory’s certificate. It evaluates trust to confirm that the certificate was issued by the accessory’s CA. At point C you can trust the details in the accessory’s certificate (trustedLeaf). Here you might add code to confirm the identity of the accessory, to prevent you from accidentally connecting to the wrong accessory. [1] This is not strictly necessary because calling SecTrustSetAnchorCertificates disables other anchors. However, I’m applying both belt and braces [2] here. [2] I’m using the British idiom because belt and suspenders is so wrong (-:
Replies
0
Boosts
0
Views
3.0k
Activity
Mar ’22
How do I find the security session id for a pid?
I am building a somewhat-VPN-like system. I have a daemon that handles the networking and a couple of agents that interact with the logged-in user. The daemon and agent communicate via XPC. I am trying to get this to work "smoothly" with fast-user-switching. Empirically, I find that the daemon can correlate XPC connection from different agents in the different login sessions via xpc_connection_get_asid(), which appears to be equivalent to the security session id, though it's not clear this this equivalence is always they case, nor will always be the case in the future. If I had a way to get the security session id for a pid, I would use xpc_connection_get_pid() When the daemon gets a network connection I want to find the pid the connection is coming from (it can only be from the local machine) and figure out which security session that pid belongs to so that I can direct any necessary user interaction and permission checking to the agent in the security session from which the network request is coming. Finding the pid from the TCP port is arduous and inefficient, but doable. However, once I've found the pid, I don't know how to determine the security session id (or audit session id) that that pid is part of. GetSessionInfo appears to permit me to get information about my own session id including my session id, or additional info about another session, if I already have that session id. For my purposes, a viable alternative to being able to get the security session for a pid might be to be able to ask the question "Is this pid part of this security session?" since I expect to have agents in a small number of security sessions. Getting the username of the pid is obviously doable, however this would mean that I would be unable to determine where a sudo'ed process was coming from (at least not without walking up the parent heirarchy). This feels dicey. Am I missing something?
Replies
2
Boosts
0
Views
1.5k
Activity
Apr ’22
Erasing all browser data removes credential manager data - WebAuthN iOS 14+
Greetings, I've working lately with webauthn navigator feature in order to make users registrations and logins with Touch ID or any other sign option that the device might offer. To give a quick context: in my webapp I register users using username + webauthn and store their credentials.id from navigator.credentials.create() and generate a pubKey that it's being store at local storage and in our DB, which is the same for the credential.id. Despite the fact that I can use my device to use my webapp after the creation of this account and using navigator.credentials.get() I'm able to log with my account with no problem but, if I go to settings > safari > clear all browser data & history I can end up destroying my access to my webapp, even though that I have the credentials on my server. Is this an expected behaviour? If I do the same on different devices, this does not happen, in fact accounts are able to log even if the browser does not have data anymore, since it only removes the browser data and not the Credential Manager data. Also, for Mac devices these keys are only accessible per browser, which mean that I have to link those different browsers as secondary devices so the user can login at any browser that they have on their device. Is this expected?
Replies
1
Boosts
0
Views
1.5k
Activity
Apr ’22
SMJobBless privileged helpers and granting permission
I have a signed, notarized app that makes use of a privileged helper. In macOS 11 and 12, as noted in several places in the documentation, there was/is an increasing requirement for the user to grant permission for things over prior macOS releases. This is great, I'm on board. I've found that the privileged helper now needs the broad "Full Disk Access". How do I get the Finder to ask the user permission for this? My helper has the special text sections called "__info_plist" and "__launchd_plist" and I tried putting what I think should go into them in those but I didn't have any luck. Is there another section I need to know about or did I just mess something else up? I'm not using Xcode or Swift or ObjectiveC, everything is C++/C and the command line tools. My helper and Application use XPC to communicate with each other. Thanks! (after my helper fails it does show up in the Full Disk Access list, if you check that pref and try again it all works, I don't want my users to ever have to do that)
Replies
5
Boosts
0
Views
1.7k
Activity
Apr ’22
Write Permissions Error (-61) returned by SecItemAdd() Objective-C API
The Keychain API SecItemAdd() returns -61 status code. Programming Language: objective-c OS: Mac BigSur 11.6.3 Default keychain: /Users/user_name/Library/Keychains/login.keychain-db Ownership: UID and GID of logged in user match those of the keychain Status of keychain as reported by SecKeychainGetStatus(): 7 (unlocked + read-permission + write-permission) Test runs fine in local environment but fails in CI environment
Replies
1
Boosts
0
Views
1.5k
Activity
Apr ’22
How to read
{"message":{"Count":8,"bundleID":"org.whispersystems.signal","position":"background","sum_of_duration":91},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"} {"message":{"Count":6,"bundleID":"org.whispersystems.signal","position":"foreground","sum_of_duration":410},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"l"} {"message":{"Count":2,"bundleID":"org.whispersystems.signal.SignalNSE","position":"background","sum_of_duration":20},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":""} {"message":{"Count":3,"bundleID":"org.whispersystems.signal.shareextension","position":"background","sum_of_duration":3},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":"} {"message":{"Count":3,"bundleID":"org.whispersystems.signal.shareextension","position":"foreground","sum_of_duration":26},"name":"embeddedOSAppUsageSessions","sampling":10,"uuid":2"} {"message":{"Count":3685,"sum_of_initParameterCurve":null,"sum_of_initParameterCurve_SPI":null,"sum_of_initPatternPlayer":1,"sum_of_initPatternPlayer_SPI":550,"sum_of_startHapticEngine":3,"sum_of_startHapticEngine_SPI":1200},"name":"CH_Metrics_ProductUsage","sampling":10,"uuid":""}
Replies
0
Boosts
0
Views
1.1k
Activity
Apr ’22