Search code examples
iosswiftmacosnsurlsessionurlsession

Swift: SSL Error when the function didReceive challenge function is not called


Hi I am working on the test project for fixing SSL error. When I try to get data from https://1tamilmv.eu I am getting error

NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://www.1tamilmv.eu/, NSUnderlyingError=0x600003f6c090 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816, _NSURLErrorNWPathKey=satisfied (Path is satisfied), viable, interface: en1, ipv4, ipv6, dns}}, _kCFStreamErrorCodeKey=-9816}

I've tested cURL using the command curl https://www.1tamilmv.eu in terminal. cURL also gives error

curl: (35) LibreSSL SSL_connect: Connection reset by peer in connection to www.1tamilmv.eu:443

But the same URL works displays website without any issues in chrome, firefox web browser. But not in the safari browser I've noticied didReceive challenge function is not called almost all times. But If it's called then the site is loading succesfully. It was loaded 1 time just moment now. I'm getting same errors in random sites on web scraping tasks.

I've tried info.plist also

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>1tamilmv.eu</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Code:

import Foundation

class HTTP: NSObject, URLSessionDelegate, URLSessionTaskDelegate {
    
    private(set) var session: URLSession!
 
    override init() {
        
        let config = URLSessionConfiguration.default
        //config.tlsMaximumSupportedProtocolVersion = .TLSv13
        config.timeoutIntervalForRequest = 30
        config.timeoutIntervalForResource = 30
        config.httpAdditionalHeaders = [
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15",
            "Accept-Encoding": "gzip, deflate, br",
            "Connection": "Keep-Alive"
        ]
     
        super.init()
       
        self.session = .init(configuration: config, delegate: self, delegateQueue: .main)
    }
    
    func load() {
        
        Task.detached(priority: .userInitiated) {
          
            var request = URLRequest(url: URL(string: "https://www.1tamilmv.eu/")!)
            request.httpMethod = "GET"
            
            do {
                
                let (data, response) = try await self.session.data(for: request)
                
                if let response = response as? HTTPURLResponse {
                    
                    print("-----------")
                    print("Status: \(response.statusCode)")
                    print("Data: \(data.count)")
                    print("-----------")

                } else {
                    
                    print("Unable to load")
                }
                
            } catch {
                
                print("Error: \(error.localizedDescription)")
            } 
        }
       
    }
  
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {

        print("Challenging....")
        if challenge.protectionSpace.serverTrust == nil {

            return (.useCredential, nil)
        }

        let trust: SecTrust = challenge.protectionSpace.serverTrust!
        let credential = URLCredential(trust: trust)
        return (.useCredential, credential)
    }
}

The data is not downloaded when I hit HTTP().load() at most of the time. Is there any other solution to fix this issue?


Solution

  • This is server side problem. I've resolved the same by sending additional headers as browsers generally do.

    "Accept-Language": "en-GB,en;q=0.9",
    "Origin": "https://www.1tamilmv.eu",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "cross-site"