Эх сурвалжийг харах

Improvements

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>
marinofaggiana 3 жил өмнө
parent
commit
b296c7ed56

+ 38 - 53
iOSClient/AppDelegate.swift

@@ -273,8 +273,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             scheduleBackgroundProcessing()
             scheduleBackgroundProcessing()
         }
         }
         
         
-        //TODO: INSERT BACKGROUD PRIVACY
-
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
     }
     }
     
     
@@ -292,10 +290,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         if account == "" { return }
         if account == "" { return }
 
 
         NCCommunicationCommon.shared.writeLog("initialize Main")
         NCCommunicationCommon.shared.writeLog("initialize Main")
-        
-        // Clear error certificate
-        NCNetworking.shared.certificatesError = nil
-        
+                
         // Registeration push notification
         // Registeration push notification
         NCPushNotification.shared().pushNotification()
         NCPushNotification.shared().pushNotification()
         
         
@@ -535,62 +530,53 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         }
         }
     }
     }
     
     
-    func viewCertificateDetailsDismiss() {
-        self.startTimerErrorNetworking()
-    }
-    
     @objc func startTimerErrorNetworking() {
     @objc func startTimerErrorNetworking() {
         timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
         timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
     }
     }
     
     
     @objc private func checkErrorNetworking() {
     @objc private func checkErrorNetworking() {
-                
-        if account == "" { return }
-        guard let currentHost = URL(string: self.urlBase)?.host else { return }
-                
+        
         // check unauthorized server (401/403)
         // check unauthorized server (401/403)
-        if CCUtility.getPassword(account)!.count == 0 {
+        if account != "" && CCUtility.getPassword(account)!.count == 0 {
             openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
             openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
         }
         }
+    }
+    
+    func trustCertificateError(host: String) {
         
         
-        // check certificate untrusted (-1202)        
-        if NCNetworking.shared.certificatesError == currentHost {
-            
-            let certificateHostSavedPath = CCUtility.getDirectoryCerificates()! + "/" + currentHost + ".der"
-            var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
-            
-            if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
-                title = NSLocalizedString("_connect_server_anyway_", comment: "")
-            }
-            
-            let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
-                
-                NCNetworking.shared.writeCertificate(host: currentHost)
-                NCNetworking.shared.certificatesError = nil
-                self.startTimerErrorNetworking()
-            }))
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
-                
-                NCNetworking.shared.certificatesError = nil
-                self.startTimerErrorNetworking()
-            }))
-            
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
-                if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
-                    let viewController = navigationController.topViewController as! NCViewCertificateDetails
-                    viewController.delegate = self
-                    viewController.host = currentHost
-                    self.window?.rootViewController?.present(navigationController, animated: true)
-                }
-            }))
-            
-            window?.rootViewController?.present(alertController, animated: true, completion: {
-                self.timerErrorNetworking?.invalidate()
-            })
+        guard let currentHost = URL(string: self.urlBase)?.host else { return }
+        guard let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host else { return }
+        if host == pushNotificationServerProxyHost || host != currentHost { return }
+        
+        let certificateHostSavedPath = CCUtility.getDirectoryCerificates()! + "/" + host + ".der"
+        var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
+        
+        if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
+            title = NSLocalizedString("_connect_server_anyway_", comment: "")
         }
         }
+        
+        let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
+        
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
+            NCNetworking.shared.writeCertificate(host: host)
+        }))
+        
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in }))
+        
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
+            if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
+                let viewController = navigationController.topViewController as! NCViewCertificateDetails
+                viewController.delegate = self
+                viewController.host = host
+                self.window?.rootViewController?.present(navigationController, animated: true)
+            }
+        }))
+        
+        window?.rootViewController?.present(alertController, animated: true)
+    }
+    
+    func viewCertificateDetailsDismiss(host: String) {
+        trustCertificateError(host: host)
     }
     }
     
     
     // MARK: - Account
     // MARK: - Account
@@ -625,7 +611,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
         }
         }
         NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
         NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
         
         
-        NCNetworking.shared.certificatesError = nil
         CCUtility.clearAllKeysEnd(toEnd: account)
         CCUtility.clearAllKeysEnd(toEnd: account)
         CCUtility.clearAllKeysPushNotification(account)
         CCUtility.clearAllKeysPushNotification(account)
         CCUtility.setPassword(account, password: nil)
         CCUtility.setPassword(account, password: nil)

+ 1 - 4
iOSClient/Login/NCLogin.swift

@@ -344,10 +344,7 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
             if NCManageDatabase.shared.getAccounts() == nil {
             if NCManageDatabase.shared.getAccounts() == nil {
                 NCUtility.shared.removeAllSettings()
                 NCUtility.shared.removeAllSettings()
             }
             }
-               
-            // Clear certificate error
-            NCNetworking.shared.certificatesError = nil
-            
+                           
             NCManageDatabase.shared.deleteAccount(account)
             NCManageDatabase.shared.deleteAccount(account)
             NCManageDatabase.shared.addAccount(account, urlBase: url, user: user, password: password)
             NCManageDatabase.shared.addAccount(account, urlBase: url, user: user, password: password)
             
             

+ 0 - 3
iOSClient/Login/NCLoginWeb.swift

@@ -270,9 +270,6 @@ extension NCLoginWeb: WKNavigationDelegate {
             NCUtility.shared.removeAllSettings()
             NCUtility.shared.removeAllSettings()
         }
         }
         
         
-        // Clear certificate error
-        NCNetworking.shared.certificatesError = nil
-
         // Add new account
         // Add new account
         NCManageDatabase.shared.deleteAccount(account)
         NCManageDatabase.shared.deleteAccount(account)
         NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: username, password: password)
         NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: username, password: password)

+ 32 - 30
iOSClient/Networking/NCNetworking.swift

@@ -48,8 +48,6 @@ import Queuer
     var uploadRequest: [String: UploadRequest] = [:]
     var uploadRequest: [String: UploadRequest] = [:]
     var uploadMetadataInBackground: [String: tableMetadata] = [:]
     var uploadMetadataInBackground: [String: tableMetadata] = [:]
     
     
-    var certificatesError: String?
-
     @objc public let sessionMaximumConnectionsPerHost = 5
     @objc public let sessionMaximumConnectionsPerHost = 5
     @objc public let sessionIdentifierBackground: String = "com.nextcloud.session.upload.background"
     @objc public let sessionIdentifierBackground: String = "com.nextcloud.session.upload.background"
     @objc public let sessionIdentifierBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
     @objc public let sessionIdentifierBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
@@ -163,45 +161,49 @@ import Queuer
         let protectionSpace: URLProtectionSpace = challenge.protectionSpace
         let protectionSpace: URLProtectionSpace = challenge.protectionSpace
         let directoryCertificate = CCUtility.getDirectoryCerificates()!
         let directoryCertificate = CCUtility.getDirectoryCerificates()!
         let host = challenge.protectionSpace.host
         let host = challenge.protectionSpace.host
-        let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host
-            
+        let certificateSavedPath = directoryCertificate + "/" + host + ".der"
+        var isTrusted: Bool
+
+        defer {
+            #if !EXTENSION
+            DispatchQueue.main.async {
+                if !isTrusted {
+                    (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host)
+                }
+            }
+            #endif
+        }
+        
         print("SSL host: \(host)")
         print("SSL host: \(host)")
         
         
-        if let serverTrust: SecTrust = protectionSpace.serverTrust {
+        if let serverTrust: SecTrust = protectionSpace.serverTrust, let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)  {
             
             
+            // extarct certificate txt
             saveX509Certificate(serverTrust, host: host, directoryCertificate: directoryCertificate)
             saveX509Certificate(serverTrust, host: host, directoryCertificate: directoryCertificate)
-            
+           
             var secresult = SecTrustResultType.invalid
             var secresult = SecTrustResultType.invalid
             let status = SecTrustEvaluate(serverTrust, &secresult)
             let status = SecTrustEvaluate(serverTrust, &secresult)
             let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
             let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
-
-            if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
-                
-                let serverCertificateData = SecCertificateCopyData(serverCertificate)
-                let data = CFDataGetBytePtr(serverCertificateData);
-                let size = CFDataGetLength(serverCertificateData);
-                let certificate = NSData(bytes: data, length: size)
-                
-                // write certificate tmp to disk
-                certificate.write(toFile: directoryCertificate + "/" + host + ".tmp", atomically: true)
+            
+            let serverCertificateData = SecCertificateCopyData(serverCertificate)
+            let data = CFDataGetBytePtr(serverCertificateData);
+            let size = CFDataGetLength(serverCertificateData);
+            let certificate = NSData(bytes: data, length: size)
                 
                 
-                if isServerTrusted {
-                    return true
-                } else if status == errSecSuccess {
-                    // verify
-                    let certificateSavedPath = directoryCertificate + "/" + host + ".der"
-                    if let certificateSaved = NSData(contentsOfFile: certificateSavedPath), certificate.isEqual(to: certificateSaved as Data) {
-                        return true
-                    }
-                }
+            certificate.write(toFile: directoryCertificate + "/" + host + ".tmp", atomically: true)
+            
+            if isServerTrusted {
+                isTrusted = true
+            } else if status == errSecSuccess, let certificateSaved = NSData(contentsOfFile: certificateSavedPath), certificate.isEqual(to: certificateSaved as Data) {
+                isTrusted = true
+            } else {
+                isTrusted = false
             }
             }
+        } else {
+            isTrusted = false
         }
         }
         
         
-        if host != pushNotificationServerProxyHost {
-            NCNetworking.shared.certificatesError = host
-        }
-        
-        return false
+        return isTrusted
     }
     }
     
     
     func writeCertificate(host: String) {
     func writeCertificate(host: String) {

+ 1 - 8
iOSClient/Networking/NCNetworkingE2EE.swift

@@ -324,14 +324,7 @@ import Alamofire
                                 NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
                                 NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
                                 #endif
                                 #endif
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
-                            
-                            } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
-                            
-                                if let host = URL(string: metadata.urlBase)?.host {
-                                    NCNetworking.shared.certificatesError = host
-                                }
-                                NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
-                                                    
+                                
                             } else {
                             } else {
                             
                             
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
                                 NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)

+ 3 - 3
iOSClient/Security/NCViewCertificateDetails.swift

@@ -24,12 +24,12 @@
 import UIKit
 import UIKit
 
 
 public protocol NCViewCertificateDetailsDelegate {
 public protocol NCViewCertificateDetailsDelegate {
-    func viewCertificateDetailsDismiss()
+    func viewCertificateDetailsDismiss(host: String)
 }
 }
 
 
 // optional func
 // optional func
 public extension NCViewCertificateDetailsDelegate {
 public extension NCViewCertificateDetailsDelegate {
-    func viewCertificateDetailsDismiss() {}
+    func viewCertificateDetailsDismiss(host: String) {}
 }
 }
 
 
 class NCViewCertificateDetails: UIViewController  {
 class NCViewCertificateDetails: UIViewController  {
@@ -87,7 +87,7 @@ class NCViewCertificateDetails: UIViewController  {
     override func viewWillDisappear(_ animated: Bool) {
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         super.viewWillDisappear(animated)
         
         
-        self.delegate?.viewCertificateDetailsDismiss()
+        self.delegate?.viewCertificateDetailsDismiss(host: host)
     }
     }
     
     
     // MARK: ACTION
     // MARK: ACTION