NCEntoToEndInterface.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. struct e2eMetadataElement: Codable {
  26. let initializationVector: String
  27. let authenticationTag: String
  28. let metadataKey: Int
  29. let encrypted: String
  30. }
  31. struct e2eMetadata: Codable {
  32. let files: [String:e2eMetadataElement]
  33. }
  34. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  35. override init() {
  36. }
  37. // --------------------------------------------------------------------------------------------
  38. // MARK: Initialize
  39. // --------------------------------------------------------------------------------------------
  40. @objc func initEndToEndEncryption() {
  41. // Clear all keys
  42. CCUtility.clearAllKeysEnd(toEnd: appDelegate.activeAccount)
  43. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  44. metadataNet.action = actionGetEndToEndPublicKeys
  45. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  46. }
  47. func getPrivateKeyCipher() {
  48. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  49. metadataNet.action = actionGetEndToEndPrivateKeyCipher
  50. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  51. }
  52. func getPublicKeyServer() {
  53. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  54. metadataNet.action = actionGetEndToEndServerPublicKey
  55. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  56. }
  57. // --------------------------------------------------------------------------------------------
  58. // MARK: Manage PublicKey
  59. // --------------------------------------------------------------------------------------------
  60. func getEndToEndPublicKeysSuccess(_ metadataNet: CCMetadataNet!) {
  61. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  62. // Request PrivateKey chiper to Server
  63. getPrivateKeyCipher()
  64. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPublicKeys, note: "E2E PublicKey present on Server and stored to keychain", type: k_activityTypeSuccess, verbose: false, activeUrl: "")
  65. }
  66. func getEndToEndPublicKeysFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  67. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPublicKeys, note: message as String!, type: k_activityTypeFailure, verbose: false, activeUrl: "")
  68. switch errorCode {
  69. case 400:
  70. appDelegate.messageNotification("E2E publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  71. case 404:
  72. guard let csr = NCEndToEndEncryption.sharedManager().createCSR(appDelegate.activeUserID, directoryUser: appDelegate.directoryUser) else {
  73. appDelegate.messageNotification("E2E Csr", description: "Error to create Csr", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  74. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPublicKeys, note: "E2E Error to create Csr", type: k_activityTypeFailure, verbose: false, activeUrl: "")
  75. return
  76. }
  77. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  78. metadataNet.action = actionSignEndToEndPublicKey;
  79. metadataNet.key = csr;
  80. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  81. case 409:
  82. appDelegate.messageNotification("E2E publicKey", description: "forbidden: the user can't access the public keys", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  83. default:
  84. appDelegate.messageNotification("E2E publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  85. }
  86. }
  87. func signEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  88. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  89. // Request PrivateKey chiper to Server
  90. getPrivateKeyCipher()
  91. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionSignEndToEndPublicKey, note: "E2E Csr - publicKey sign on Server and stored publicKey locally", type: k_activityTypeFailure, verbose: false, activeUrl: "")
  92. }
  93. func signEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  94. appDelegate.messageNotification("E2E sign Csr - publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  95. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionSignEndToEndPublicKey, note: message, type: k_activityTypeFailure, verbose: false, activeUrl: "")
  96. }
  97. func deleteEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  98. appDelegate.messageNotification("E2E delete publicKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  99. }
  100. func deleteEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  101. appDelegate.messageNotification("E2E delete publicKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  102. }
  103. // --------------------------------------------------------------------------------------------
  104. // MARK: Manage PrivateKey
  105. // --------------------------------------------------------------------------------------------
  106. func getEndToEndPrivateKeyCipherSuccess(_ metadataNet: CCMetadataNet!) {
  107. // request Passphrase
  108. var passphraseTextField: UITextField?
  109. let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
  110. //TEST
  111. /*
  112. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  113. let fileURL = dir.appendingPathComponent("privatekey.txt")
  114. //writing
  115. do {
  116. try metadataNet.key.write(to: fileURL, atomically: false, encoding: .utf8)
  117. }
  118. catch {/* error handling here */}
  119. }
  120. */
  121. //
  122. let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
  123. let passphrase = passphraseTextField?.text
  124. let publicKey = CCUtility.getEndToEndPublicKey(self.appDelegate.activeAccount)
  125. guard let privateKey = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(metadataNet.key, passphrase: passphrase, publicKey: publicKey)) else {
  126. self.appDelegate.messageNotification("E2E decrypt privateKey", description: "Error to decrypt Private Key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  127. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPrivateKeyCipher, note: "E2E Error to decrypt PrivateKey", type: k_activityTypeFailure, verbose: false, activeUrl: "")
  128. return
  129. }
  130. // privateKey
  131. print(privateKey)
  132. // Save to keychain
  133. CCUtility.setEndToEndPrivateKey(self.appDelegate.activeAccount, privateKey: privateKey)
  134. CCUtility.setEndToEndPassphrase(self.appDelegate.activeAccount, passphrase:passphrase)
  135. // request publicKey Server()
  136. self.getPublicKeyServer()
  137. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPrivateKeyCipher, note: "E2E PrivateKey present on Server and stored to keychain", type: k_activityTypeSuccess, verbose: false, activeUrl: "")
  138. })
  139. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
  140. }
  141. alertController.addAction(ok)
  142. alertController.addAction(cancel)
  143. alertController.addTextField { (textField) -> Void in
  144. passphraseTextField = textField
  145. passphraseTextField?.placeholder = "Enter passphrase (12 words)"
  146. }
  147. appDelegate.activeMain.present(alertController, animated: true)
  148. }
  149. func getEndToEndPrivateKeyCipherFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  150. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPrivateKeyCipher, note: message as String!, type: k_activityTypeFailure, verbose: false, activeUrl: "")
  151. switch errorCode {
  152. case 400:
  153. appDelegate.messageNotification("E2E privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  154. case 404:
  155. // message
  156. let e2ePassphrase = NYMnemonic.generateString(128, language: "english")
  157. let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase!
  158. let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
  159. let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  160. var privateKey : NSString?
  161. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.activeUserID, directoryUser: self.appDelegate.directoryUser, passphrase: e2ePassphrase, privateKey: &privateKey) else {
  162. self.appDelegate.messageNotification("E2E privateKey", description: "Error to create PrivateKey chiper", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  163. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndPrivateKeyCipher, note: "E2E Error to create PrivateKey chiper", type: k_activityTypeFailure, verbose: false, activeUrl: "")
  164. return
  165. }
  166. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: self.appDelegate.activeAccount)
  167. metadataNet.action = actionStoreEndToEndPrivateKeyCipher
  168. metadataNet.key = privateKey! as String
  169. metadataNet.keyCipher = privateKeyChiper
  170. metadataNet.password = e2ePassphrase
  171. self.appDelegate.addNetworkingOperationQueue(self.appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  172. }
  173. alertController.addAction(OKAction)
  174. appDelegate.activeMain.present(alertController, animated: true)
  175. case 409:
  176. appDelegate.messageNotification("E2E privateKey", description: "forbidden: the user can't access the private key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  177. default:
  178. appDelegate.messageNotification("E2E privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  179. }
  180. }
  181. func storeEnd(toEndPrivateKeyCipherSuccess metadataNet: CCMetadataNet!) {
  182. CCUtility.setEndToEndPrivateKey(appDelegate.activeAccount, privateKey: metadataNet.key)
  183. CCUtility.setEndToEndPassphrase(appDelegate.activeAccount, passphrase:metadataNet.password)
  184. // request publicKey Server()
  185. self.getPublicKeyServer()
  186. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionStoreEndToEndPrivateKeyCipher, note: "E2E PrivateKey stored on Server and stored locally", type: k_activityTypeSuccess, verbose: false, activeUrl: "")
  187. }
  188. func storeEnd(toEndPrivateKeyCipherFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  189. appDelegate.messageNotification("E2E sign privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  190. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionStoreEndToEndPrivateKeyCipher, note: message, type: k_activityTypeFailure, verbose: false, activeUrl: "")
  191. }
  192. func deleteEnd(toEndPrivateKeySuccess metadataNet: CCMetadataNet!) {
  193. appDelegate.messageNotification("E2E delete privateKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  194. }
  195. func deleteEnd(toEndPrivateKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  196. appDelegate.messageNotification("E2E delete privateKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  197. }
  198. // --------------------------------------------------------------------------------------------
  199. // MARK: Manage Server PublicKey
  200. // --------------------------------------------------------------------------------------------
  201. func getEndToEndServerPublicKeySuccess(_ metadataNet: CCMetadataNet!) {
  202. CCUtility.setEndToEndPublicKeyServer(appDelegate.activeAccount, publicKey: metadataNet.key)
  203. // All OK Activated flsg on Manage EndToEnd Encryption
  204. NotificationCenter.default.post(name: Notification.Name("reloadManageEndToEndEncryption"), object: nil)
  205. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndServerPublicKey, note: "E2E Server PublicKey present on Server and stored to keychain", type: k_activityTypeSuccess, verbose: false, activeUrl: "")
  206. }
  207. func getEndToEndServerPublicKeyFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  208. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndServerPublicKey, note: message as String!, type: k_activityTypeFailure, verbose: false, activeUrl: "")
  209. switch (errorCode) {
  210. case 400:
  211. appDelegate.messageNotification("E2E Server publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  212. case 404:
  213. appDelegate.messageNotification("E2E Server publicKey", description: "Server publickey doesn't exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  214. case 409:
  215. 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)
  216. default:
  217. appDelegate.messageNotification("E2E Server publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  218. }
  219. }
  220. // --------------------------------------------------------------------------------------------
  221. // MARK: Mark/Delete Encrypted Folder
  222. // --------------------------------------------------------------------------------------------
  223. @objc func markEndToEndFolderEncrypted(_ url: String, fileID: String, token: String?) {
  224. var token : NSString? = token as NSString?
  225. if let error = NCNetworkingSync.sharedManager().lockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url , fileID: fileID, token: &token) as NSError? {
  226. appDelegate.messageNotification("_error_", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  227. return
  228. }
  229. if let error = NCNetworkingSync.sharedManager().markEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID) as NSError? {
  230. appDelegate.messageNotification("_error_", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  231. return
  232. }
  233. if let error = NCNetworkingSync.sharedManager().unlockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID, token: token! as String) as NSError? {
  234. appDelegate.messageNotification("_error_", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  235. return
  236. }
  237. }
  238. @objc func deletemarkEndToEndFolderEncrypted(_ metadata: tableMetadata) {
  239. }
  240. // --------------------------------------------------------------------------------------------
  241. // MARK: Manage Metadata
  242. // --------------------------------------------------------------------------------------------
  243. func getEndToEndMetadataSuccess(_ metadataNet: CCMetadataNet!) {
  244. let decoder = JSONDecoder.init()
  245. let data = metadataNet.encryptedMetadata.data(using: .utf8)
  246. do {
  247. let response = try decoder.decode(e2eMetadata.self, from: data!)
  248. let files = response.files
  249. for metadata in files {
  250. let fileNameID = metadata.key
  251. let element = metadata.value as e2eMetadataElement
  252. let iv = element.initializationVector
  253. let tag = element.authenticationTag
  254. let encrypted = element.encrypted
  255. let privateKey = CCUtility.getEndToEndPrivateKey(appDelegate.activeAccount)
  256. let x = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(encrypted.data(using: .utf8), privateKey: privateKey)
  257. //let x = NCEndToEndEncryption.sharedManager().decryptMetadata(encrypted, key: privateKey, iv: iv, tag: tag)
  258. print(metadata)
  259. }
  260. print(response)
  261. } catch let error {
  262. appDelegate.messageNotification("_error_", description: "Error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  263. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionEndToEndEncryption, selector: actionGetEndToEndServerPublicKey, note: error.localizedDescription, type: k_activityTypeSuccess, verbose: false, activeUrl: "")
  264. }
  265. }
  266. func getEndToEndMetadataFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  267. // Unauthorized
  268. if (errorCode == kOCErrorServerUnauthorized) {
  269. appDelegate.openLoginView(appDelegate.activeMain, loginType: loginModifyPasswordUser)
  270. }
  271. if (errorCode != kOCErrorServerUnauthorized) {
  272. appDelegate.messageNotification("_error_", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  273. }
  274. }
  275. @objc func getEndToEndMetadata(_ metadata: tableMetadata) {
  276. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  277. metadataNet.action = actionGetEndToEndMetadata;
  278. metadataNet.fileID = metadata.fileID;
  279. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  280. }
  281. }