NCEntoToEndInterface.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // NCEntoToEndInterface.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/04/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. class NCEntoToEndInterface : NSObject, OCNetworkingDelegate {
  25. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  26. override init() {
  27. }
  28. // --------------------------------------------------------------------------------------------
  29. // MARK: Initialize
  30. // --------------------------------------------------------------------------------------------
  31. @objc func initEndToEndEncryption() {
  32. // Clear all keys
  33. CCUtility.clearAllKeysEnd(toEnd: appDelegate.activeAccount)
  34. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  35. metadataNet.action = actionGetEndToEndPublicKeys
  36. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  37. }
  38. func getPrivateKeyCipher() {
  39. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  40. metadataNet.action = actionGetEndToEndPrivateKeyCipher
  41. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  42. }
  43. func getPublicKeyServer() {
  44. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  45. metadataNet.action = actionGetEndToEndServerPublicKey
  46. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  47. }
  48. // --------------------------------------------------------------------------------------------
  49. // MARK: Manage PublicKey
  50. // --------------------------------------------------------------------------------------------
  51. func getEndToEndPublicKeysSuccess(_ metadataNet: CCMetadataNet!) {
  52. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  53. // Request PrivateKey chiper to Server
  54. getPrivateKeyCipher()
  55. }
  56. func getEndToEndPublicKeysFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  57. switch errorCode {
  58. case 400:
  59. appDelegate.messageNotification("E2E get publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  60. case 404:
  61. guard let csr = NCEndToEndEncryption.sharedManager().createCSR(appDelegate.activeUserID, directoryUser: appDelegate.directoryUser) else {
  62. appDelegate.messageNotification("E2E Csr", description: "Error to create Csr", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  63. return
  64. }
  65. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  66. metadataNet.action = actionSignEndToEndPublicKey;
  67. metadataNet.key = csr;
  68. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  69. case 409:
  70. appDelegate.messageNotification("E2E get publicKey", description: "forbidden: the user can't access the public keys", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  71. default:
  72. appDelegate.messageNotification("E2E get publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  73. }
  74. }
  75. func signEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  76. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  77. // Request PrivateKey chiper to Server
  78. getPrivateKeyCipher()
  79. }
  80. func signEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  81. switch errorCode {
  82. case 400:
  83. appDelegate.messageNotification("E2E sign publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  84. case 409:
  85. appDelegate.messageNotification("E2E sign publicKey", description: "conflict: a public key for the user already exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  86. default:
  87. appDelegate.messageNotification("E2E sign publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  88. }
  89. }
  90. func deleteEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  91. appDelegate.messageNotification("E2E delete publicKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  92. }
  93. func deleteEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  94. appDelegate.messageNotification("E2E delete publicKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  95. }
  96. // --------------------------------------------------------------------------------------------
  97. // MARK: Manage PrivateKey
  98. // --------------------------------------------------------------------------------------------
  99. func getEndToEndPrivateKeyCipherSuccess(_ metadataNet: CCMetadataNet!) {
  100. // request Passphrase
  101. var passphraseTextField: UITextField?
  102. let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
  103. //TEST
  104. /*
  105. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  106. let fileURL = dir.appendingPathComponent("privatekey.txt")
  107. //writing
  108. do {
  109. try metadataNet.key.write(to: fileURL, atomically: false, encoding: .utf8)
  110. }
  111. catch {/* error handling here */}
  112. }
  113. */
  114. //
  115. let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
  116. let passphrase = passphraseTextField?.text
  117. let publicKey = CCUtility.getEndToEndPublicKey(self.appDelegate.activeAccount)
  118. guard let privateKey = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(metadataNet.key, passphrase: passphrase, publicKey: publicKey)) else {
  119. self.appDelegate.messageNotification("E2E decrypt privateKey", description: "Serious internal error to decrypt Private Key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  120. return
  121. }
  122. // privateKey
  123. print(privateKey)
  124. // Save to keychain
  125. CCUtility.setEndToEndPrivateKey(self.appDelegate.activeAccount, privateKey: privateKey)
  126. CCUtility.setEndToEndPassphrase(self.appDelegate.activeAccount, passphrase:passphrase)
  127. // request publicKey Server()
  128. self.getPublicKeyServer()
  129. })
  130. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
  131. }
  132. alertController.addAction(ok)
  133. alertController.addAction(cancel)
  134. alertController.addTextField { (textField) -> Void in
  135. passphraseTextField = textField
  136. passphraseTextField?.placeholder = "Enter passphrase (12 words)"
  137. }
  138. appDelegate.activeMain.present(alertController, animated: true)
  139. }
  140. func getEndToEndPrivateKeyCipherFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  141. switch errorCode {
  142. case 400:
  143. appDelegate.messageNotification("E2E get privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  144. case 404:
  145. // message
  146. let e2ePassphrase = NYMnemonic.generateString(128, language: "english")
  147. let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase!
  148. let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
  149. let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  150. var privateKey: NSString?
  151. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.activeUserID, directoryUser: self.appDelegate.directoryUser, passphrase: e2ePassphrase, privateKey: &privateKey) else {
  152. self.appDelegate.messageNotification("E2E privateKey", description: "Serious internal error to create PrivateKey chiper", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  153. return
  154. }
  155. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: self.appDelegate.activeAccount)
  156. metadataNet.action = actionStoreEndToEndPrivateKeyCipher
  157. metadataNet.key = privateKey! as String
  158. metadataNet.keyCipher = privateKeyChiper
  159. metadataNet.password = e2ePassphrase
  160. self.appDelegate.addNetworkingOperationQueue(self.appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  161. }
  162. alertController.addAction(OKAction)
  163. appDelegate.activeMain.present(alertController, animated: true)
  164. case 409:
  165. appDelegate.messageNotification("E2E get privateKey", description: "forbidden: the user can't access the private key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  166. default:
  167. appDelegate.messageNotification("E2E get privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  168. }
  169. }
  170. func storeEnd(toEndPrivateKeyCipherSuccess metadataNet: CCMetadataNet!) {
  171. CCUtility.setEndToEndPrivateKey(appDelegate.activeAccount, privateKey: metadataNet.key)
  172. CCUtility.setEndToEndPassphrase(appDelegate.activeAccount, passphrase:metadataNet.password)
  173. // request publicKey Server()
  174. self.getPublicKeyServer()
  175. }
  176. func storeEnd(toEndPrivateKeyCipherFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  177. switch errorCode {
  178. case 400:
  179. appDelegate.messageNotification("E2E store privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  180. case 409:
  181. appDelegate.messageNotification("E2E store privateKey", description: "conflict: a private key for the user already exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  182. default:
  183. appDelegate.messageNotification("E2E store privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  184. }
  185. }
  186. func deleteEnd(toEndPrivateKeySuccess metadataNet: CCMetadataNet!) {
  187. appDelegate.messageNotification("E2E delete privateKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  188. }
  189. func deleteEnd(toEndPrivateKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  190. appDelegate.messageNotification("E2E delete privateKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  191. }
  192. // --------------------------------------------------------------------------------------------
  193. // MARK: Manage Server PublicKey
  194. // --------------------------------------------------------------------------------------------
  195. func getEndToEndServerPublicKeySuccess(_ metadataNet: CCMetadataNet!) {
  196. CCUtility.setEndToEndPublicKeyServer(appDelegate.activeAccount, publicKey: metadataNet.key)
  197. // Clear Table
  198. NCManageDatabase.sharedInstance.clearTable(tableDirectory.self, account: appDelegate.activeAccount)
  199. NCManageDatabase.sharedInstance.clearTable(tableE2eEncryption.self, account: appDelegate.activeAccount)
  200. // Reload All Datasource
  201. NotificationCenter.default.post(name: Notification.Name("clearDateReadDataSource"), object: nil)
  202. // All OK Activated flsg on Manage EndToEnd Encryption
  203. NotificationCenter.default.post(name: Notification.Name("reloadManageEndToEndEncryption"), object: nil)
  204. }
  205. func getEndToEndServerPublicKeyFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  206. switch (errorCode) {
  207. case 400:
  208. appDelegate.messageNotification("E2E Server publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  209. case 404:
  210. appDelegate.messageNotification("E2E Server publicKey", description: "Server publickey doesn't exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  211. case 409:
  212. appDelegate.messageNotification("E2E Server publicKey", description: "forbidden: the user can't access the Server publickey", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  213. default:
  214. appDelegate.messageNotification("E2E Server publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  215. }
  216. }
  217. // --------------------------------------------------------------------------------------------
  218. // MARK: Manage Mark/Delete Encrypted Folder
  219. // --------------------------------------------------------------------------------------------
  220. @objc func markEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  221. var token: NSString?
  222. // Remove all records e2eMetadata
  223. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl))
  224. if let error = NCNetworkingSync.sharedManager().markEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID, serverUrl: serverUrl,token: &token) as NSError? {
  225. appDelegate.messageNotification("E2E Mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  226. return false
  227. }
  228. return true
  229. }
  230. @objc func deletemarkEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  231. var token: NSString?
  232. // Remove all records e2eMetadata
  233. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl))
  234. if let error = NCNetworkingSync.sharedManager().deletemarkEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID, serverUrl: serverUrl, token: &token) as NSError? {
  235. appDelegate.messageNotification("E2E Remove mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  236. return false
  237. }
  238. return true
  239. }
  240. // --------------------------------------------------------------------------------------------
  241. // MARK: Manage Metadata
  242. // --------------------------------------------------------------------------------------------
  243. func getEndToEndMetadataSuccess(_ metadataNet: CCMetadataNet!) {
  244. guard let privateKey = CCUtility.getEndToEndPrivateKey(appDelegate.activeAccount) else {
  245. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: PrivareKey not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  246. return
  247. }
  248. guard let main = appDelegate.listMainVC[metadataNet.serverUrl] as? CCMain else {
  249. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: Main not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  250. return
  251. }
  252. // Decode metadata JSON
  253. if NCEndToEndMetadata.sharedInstance.decoderMetadata(metadataNet.encryptedMetadata, privateKey: privateKey, serverUrl: metadataNet.serverUrl, account: appDelegate.activeAccount, url: appDelegate.activeUrl) == false {
  254. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  255. return
  256. }
  257. // Reload data source
  258. main.reloadDatasource(metadataNet.serverUrl)
  259. }
  260. func getEndToEndMetadataFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  261. // Unauthorized
  262. if (errorCode == kOCErrorServerUnauthorized) {
  263. appDelegate.openLoginView(appDelegate.activeMain, loginType: loginModifyPasswordUser)
  264. } else if (errorCode == 404) {
  265. print("No metadata found: "+metadataNet.serverUrl+"/"+metadataNet.fileName)
  266. } else if (errorCode != 404) {
  267. appDelegate.messageNotification("E2E Get metadata", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  268. }
  269. }
  270. @objc func getEndToEndMetadata(_ fileName: String, fileID: String, serverUrl: String) {
  271. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  272. metadataNet.action = actionGetEndToEndMetadata
  273. metadataNet.fileID = fileID
  274. metadataNet.fileName = fileName
  275. metadataNet.serverUrl = serverUrl
  276. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  277. }
  278. }