Swift and SecTrust

I'm having trouble trying to convert the code I found in the Apple documentation into quick code. To be precise, this is information about TSL and certificates ...

https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html

This is the source code in Objective-C.

SecTrustResultType secresult = kSecTrustResultInvalid; if (SecTrustEvaluate(trust, &secresult) != errSecSuccess) return; } 

And this is my attempt ...

 var secresult:SecTrustResultType = kSecTrustResultInvalid // ERROR 1 if (SecTrustEvaluate(trust, &secresult) != errSecSuccess) { // ERROR 2 return; } 

ERROR 1:

 'Int' is not convertible to 'SecTrustResultType' 

ERROR 2:

  Could not find an overload for '!=' that accepts the supplied arguments 

Now I see that SecTrustResultType is UInt32 and kSecTrustResultInvalid is Int ... but this header is defined by Apple, so I suppose it should be correct: P

 typealias SecTrustResultType = UInt32 var kSecTrustResultInvalid: Int { get } 

About the second error, I really do not know how to manage it, because the SecTrustEvaluate function returns OSStatus (this is an alias for UInt32 ), and errSecSuccess is OSStatus .

I'm really confused. Do you have any suggestions for creating this material ??

+6
source share
4 answers

You can run SecTrustResultType with this line in Swift 5

 var secResult = SecTrustResultType.invalid 

Unlike other answers, I preferred one result descriptor (SecTrustResultType) when checking the server certificate chain. Please see below:

 func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let trust: SecTrust = challenge.protectionSpace.serverTrust else { return } var secResult = SecTrustResultType.invalid SecTrustEvaluate(trust, &secResult) switch secResult { case .proceed: // ✅ case .recoverableTrustFailure: // ❌ check Root CA and Int CA trusted on IOS device default: // ❌ default error } completionHandler(.performDefaultHandling, nil) } 
+1
source

I ran into this problem myself, and the header documents are a bit confused because the constants are defined as Int , and SecTrustResultType is defined as UInt32 .

But the good news is, the solution is pretty simple, just init SecTrustResultType with kSecTrustResultInvalid :

 var secresult = SecTrustResultType(kSecTrustResultInvalid) if (SecTrustEvaluate(serverTrust, &secresult) != errSecSuccess){ return; } 
+5
source

Swift 2.3

 var secresult = SecTrustResultType.Invalid if (SecTrustEvaluate(serverTrust, &secresult) != errSecSuccess){ return; } 
+2
source

Still stays in Swift 3.0:

 var secresult = SecTrustResultType.Invalid if (SecTrustEvaluate(serverTrust, &secresult) != errSecSuccess){ return; } 
0
source

Source: https://habr.com/ru/post/986214/


All Articles