NCEntoToEndInterface.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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, salt: "$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$")) 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. var salt: NSString?
  152. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.activeUserID, directoryUser: self.appDelegate.directoryUser, passphrase: e2ePassphrase, privateKey: &privateKey, salt: &salt) else {
  153. self.appDelegate.messageNotification("E2E privateKey", description: "Serious internal error to create PrivateKey chiper", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  154. return
  155. }
  156. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: self.appDelegate.activeAccount)
  157. metadataNet.action = actionStoreEndToEndPrivateKeyCipher
  158. metadataNet.key = privateKey! as String
  159. metadataNet.keyCipher = privateKeyChiper
  160. metadataNet.password = e2ePassphrase
  161. self.appDelegate.addNetworkingOperationQueue(self.appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  162. }
  163. alertController.addAction(OKAction)
  164. appDelegate.activeMain.present(alertController, animated: true)
  165. case 409:
  166. 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)
  167. default:
  168. appDelegate.messageNotification("E2E get privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  169. }
  170. }
  171. func storeEnd(toEndPrivateKeyCipherSuccess metadataNet: CCMetadataNet!) {
  172. CCUtility.setEndToEndPrivateKey(appDelegate.activeAccount, privateKey: metadataNet.key)
  173. CCUtility.setEndToEndPassphrase(appDelegate.activeAccount, passphrase:metadataNet.password)
  174. // request publicKey Server()
  175. self.getPublicKeyServer()
  176. }
  177. func storeEnd(toEndPrivateKeyCipherFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  178. switch errorCode {
  179. case 400:
  180. appDelegate.messageNotification("E2E store privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  181. case 409:
  182. 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)
  183. default:
  184. appDelegate.messageNotification("E2E store privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  185. }
  186. }
  187. func deleteEnd(toEndPrivateKeySuccess metadataNet: CCMetadataNet!) {
  188. appDelegate.messageNotification("E2E delete privateKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  189. }
  190. func deleteEnd(toEndPrivateKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  191. appDelegate.messageNotification("E2E delete privateKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  192. }
  193. // --------------------------------------------------------------------------------------------
  194. // MARK: Manage Server PublicKey
  195. // --------------------------------------------------------------------------------------------
  196. func getEndToEndServerPublicKeySuccess(_ metadataNet: CCMetadataNet!) {
  197. CCUtility.setEndToEndPublicKeyServer(appDelegate.activeAccount, publicKey: metadataNet.key)
  198. // Clear Table
  199. NCManageDatabase.sharedInstance.clearTable(tableDirectory.self, account: appDelegate.activeAccount)
  200. NCManageDatabase.sharedInstance.clearTable(tableE2eEncryption.self, account: appDelegate.activeAccount)
  201. // Reload All Datasource
  202. NotificationCenter.default.post(name: Notification.Name("clearDateReadDataSource"), object: nil)
  203. // All OK Activated flsg on Manage EndToEnd Encryption
  204. NotificationCenter.default.post(name: Notification.Name("reloadManageEndToEndEncryption"), object: nil)
  205. }
  206. func getEndToEndServerPublicKeyFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  207. switch (errorCode) {
  208. case 400:
  209. appDelegate.messageNotification("E2E Server publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  210. case 404:
  211. appDelegate.messageNotification("E2E Server publicKey", description: "Server publickey doesn't exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  212. case 409:
  213. 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)
  214. default:
  215. appDelegate.messageNotification("E2E Server publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  216. }
  217. }
  218. // --------------------------------------------------------------------------------------------
  219. // MARK: Manage Mark/Delete Encrypted Folder
  220. // --------------------------------------------------------------------------------------------
  221. @objc func markEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  222. var token: NSString?
  223. // Remove all records e2eMetadata
  224. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl))
  225. 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? {
  226. 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)
  227. return false
  228. }
  229. return true
  230. }
  231. @objc func deletemarkEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  232. var token: NSString?
  233. // Remove all records e2eMetadata
  234. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl))
  235. 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? {
  236. 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)
  237. return false
  238. }
  239. return true
  240. }
  241. // --------------------------------------------------------------------------------------------
  242. // MARK: Manage Metadata
  243. // --------------------------------------------------------------------------------------------
  244. func getEndToEndMetadataSuccess(_ metadataNet: CCMetadataNet!) {
  245. guard let privateKey = CCUtility.getEndToEndPrivateKey(appDelegate.activeAccount) else {
  246. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: PrivareKey not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  247. return
  248. }
  249. guard let main = appDelegate.listMainVC[metadataNet.serverUrl] as? CCMain else {
  250. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: Main not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  251. return
  252. }
  253. // Decode metadata JSON
  254. if NCEndToEndMetadata.sharedInstance.decoderMetadata(metadataNet.encryptedMetadata, privateKey: privateKey, serverUrl: metadataNet.serverUrl, account: appDelegate.activeAccount, url: appDelegate.activeUrl) == false {
  255. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  256. return
  257. }
  258. // Reload data source
  259. main.reloadDatasource(metadataNet.serverUrl)
  260. }
  261. func getEndToEndMetadataFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  262. // Unauthorized
  263. if (errorCode == kOCErrorServerUnauthorized) {
  264. appDelegate.openLoginView(appDelegate.activeMain, loginType: loginModifyPasswordUser)
  265. } else if (errorCode == 404) {
  266. print("No metadata found: "+metadataNet.serverUrl+"/"+metadataNet.fileName)
  267. } else if (errorCode != 404) {
  268. appDelegate.messageNotification("E2E Get metadata", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  269. }
  270. }
  271. @objc func getEndToEndMetadata(_ fileName: String, fileID: String, serverUrl: String) {
  272. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  273. metadataNet.action = actionGetEndToEndMetadata
  274. metadataNet.fileID = fileID
  275. metadataNet.fileName = fileName
  276. metadataNet.serverUrl = serverUrl
  277. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  278. }
  279. }