NCEntoToEndInterface.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 e2eMetadata: Codable {
  26. struct metadataKey: Codable {
  27. let metadataKeys: [String: String]
  28. let version: Int
  29. }
  30. struct sharingKey: Codable {
  31. let recipient: [String: String]
  32. }
  33. struct encrypted: Codable {
  34. let key: String
  35. let filename: String
  36. let mimetype: String
  37. let version: Int
  38. }
  39. struct filesKey: Codable {
  40. let initializationVector: String
  41. let authenticationTag: String
  42. let metadataKey: Int
  43. let encrypted: String
  44. }
  45. let files: [String: filesKey]
  46. let metadata: metadataKey
  47. let sharing: sharingKey?
  48. }
  49. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  50. override init() {
  51. }
  52. // --------------------------------------------------------------------------------------------
  53. // MARK: Initialize
  54. // --------------------------------------------------------------------------------------------
  55. @objc func initEndToEndEncryption() {
  56. // Clear all keys
  57. CCUtility.clearAllKeysEnd(toEnd: appDelegate.activeAccount)
  58. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  59. metadataNet.action = actionGetEndToEndPublicKeys
  60. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  61. }
  62. func getPrivateKeyCipher() {
  63. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  64. metadataNet.action = actionGetEndToEndPrivateKeyCipher
  65. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  66. }
  67. func getPublicKeyServer() {
  68. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  69. metadataNet.action = actionGetEndToEndServerPublicKey
  70. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  71. }
  72. // --------------------------------------------------------------------------------------------
  73. // MARK: Manage PublicKey
  74. // --------------------------------------------------------------------------------------------
  75. func getEndToEndPublicKeysSuccess(_ metadataNet: CCMetadataNet!) {
  76. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  77. // Request PrivateKey chiper to Server
  78. getPrivateKeyCipher()
  79. }
  80. func getEndToEndPublicKeysFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  81. switch errorCode {
  82. case 400:
  83. appDelegate.messageNotification("E2E get publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  84. case 404:
  85. guard let csr = NCEndToEndEncryption.sharedManager().createCSR(appDelegate.activeUserID, directoryUser: appDelegate.directoryUser) else {
  86. appDelegate.messageNotification("E2E Csr", description: "Error to create Csr", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  87. return
  88. }
  89. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  90. metadataNet.action = actionSignEndToEndPublicKey;
  91. metadataNet.key = csr;
  92. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  93. case 409:
  94. 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)
  95. default:
  96. appDelegate.messageNotification("E2E get publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  97. }
  98. }
  99. func signEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  100. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  101. // Request PrivateKey chiper to Server
  102. getPrivateKeyCipher()
  103. }
  104. func signEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  105. switch errorCode {
  106. case 400:
  107. appDelegate.messageNotification("E2E sign publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  108. case 409:
  109. 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)
  110. default:
  111. appDelegate.messageNotification("E2E sign publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  112. }
  113. }
  114. func deleteEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  115. appDelegate.messageNotification("E2E delete publicKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  116. }
  117. func deleteEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  118. appDelegate.messageNotification("E2E delete publicKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  119. }
  120. // --------------------------------------------------------------------------------------------
  121. // MARK: Manage PrivateKey
  122. // --------------------------------------------------------------------------------------------
  123. func getEndToEndPrivateKeyCipherSuccess(_ metadataNet: CCMetadataNet!) {
  124. // request Passphrase
  125. var passphraseTextField: UITextField?
  126. let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
  127. //TEST
  128. /*
  129. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  130. let fileURL = dir.appendingPathComponent("privatekey.txt")
  131. //writing
  132. do {
  133. try metadataNet.key.write(to: fileURL, atomically: false, encoding: .utf8)
  134. }
  135. catch {/* error handling here */}
  136. }
  137. */
  138. //
  139. let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
  140. let passphrase = passphraseTextField?.text
  141. let publicKey = CCUtility.getEndToEndPublicKey(self.appDelegate.activeAccount)
  142. guard let privateKey = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(metadataNet.key, passphrase: passphrase, publicKey: publicKey)) else {
  143. 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)
  144. return
  145. }
  146. // privateKey
  147. print(privateKey)
  148. // Save to keychain
  149. CCUtility.setEndToEndPrivateKey(self.appDelegate.activeAccount, privateKey: privateKey)
  150. CCUtility.setEndToEndPassphrase(self.appDelegate.activeAccount, passphrase:passphrase)
  151. // request publicKey Server()
  152. self.getPublicKeyServer()
  153. })
  154. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
  155. }
  156. alertController.addAction(ok)
  157. alertController.addAction(cancel)
  158. alertController.addTextField { (textField) -> Void in
  159. passphraseTextField = textField
  160. passphraseTextField?.placeholder = "Enter passphrase (12 words)"
  161. }
  162. appDelegate.activeMain.present(alertController, animated: true)
  163. }
  164. func getEndToEndPrivateKeyCipherFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  165. switch errorCode {
  166. case 400:
  167. appDelegate.messageNotification("E2E get privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  168. case 404:
  169. // message
  170. let e2ePassphrase = NYMnemonic.generateString(128, language: "english")
  171. let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase!
  172. let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
  173. let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  174. var privateKey : NSString?
  175. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.activeUserID, directoryUser: self.appDelegate.directoryUser, passphrase: e2ePassphrase, privateKey: &privateKey) else {
  176. self.appDelegate.messageNotification("E2E privateKey", description: "Serious internal error to create PrivateKey chiper", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  177. return
  178. }
  179. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: self.appDelegate.activeAccount)
  180. metadataNet.action = actionStoreEndToEndPrivateKeyCipher
  181. metadataNet.key = privateKey! as String
  182. metadataNet.keyCipher = privateKeyChiper
  183. metadataNet.password = e2ePassphrase
  184. self.appDelegate.addNetworkingOperationQueue(self.appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  185. }
  186. alertController.addAction(OKAction)
  187. appDelegate.activeMain.present(alertController, animated: true)
  188. case 409:
  189. 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)
  190. default:
  191. appDelegate.messageNotification("E2E get privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  192. }
  193. }
  194. func storeEnd(toEndPrivateKeyCipherSuccess metadataNet: CCMetadataNet!) {
  195. CCUtility.setEndToEndPrivateKey(appDelegate.activeAccount, privateKey: metadataNet.key)
  196. CCUtility.setEndToEndPassphrase(appDelegate.activeAccount, passphrase:metadataNet.password)
  197. // request publicKey Server()
  198. self.getPublicKeyServer()
  199. }
  200. func storeEnd(toEndPrivateKeyCipherFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  201. switch errorCode {
  202. case 400:
  203. appDelegate.messageNotification("E2E store privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  204. case 409:
  205. 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)
  206. default:
  207. appDelegate.messageNotification("E2E store privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  208. }
  209. }
  210. func deleteEnd(toEndPrivateKeySuccess metadataNet: CCMetadataNet!) {
  211. appDelegate.messageNotification("E2E delete privateKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  212. }
  213. func deleteEnd(toEndPrivateKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  214. appDelegate.messageNotification("E2E delete privateKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  215. }
  216. // --------------------------------------------------------------------------------------------
  217. // MARK: Manage Server PublicKey
  218. // --------------------------------------------------------------------------------------------
  219. func getEndToEndServerPublicKeySuccess(_ metadataNet: CCMetadataNet!) {
  220. CCUtility.setEndToEndPublicKeyServer(appDelegate.activeAccount, publicKey: metadataNet.key)
  221. // Clear Table
  222. NCManageDatabase.sharedInstance.clearTable(tableDirectory.self, account: appDelegate.activeAccount)
  223. NCManageDatabase.sharedInstance.clearTable(tableE2eEncryption.self, account: appDelegate.activeAccount)
  224. // Reload All Datasource
  225. NotificationCenter.default.post(name: Notification.Name("clearDateReadDataSource"), object: nil)
  226. // All OK Activated flsg on Manage EndToEnd Encryption
  227. NotificationCenter.default.post(name: Notification.Name("reloadManageEndToEndEncryption"), object: nil)
  228. }
  229. func getEndToEndServerPublicKeyFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  230. switch (errorCode) {
  231. case 400:
  232. appDelegate.messageNotification("E2E Server publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  233. case 404:
  234. appDelegate.messageNotification("E2E Server publicKey", description: "Server publickey doesn't exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  235. case 409:
  236. 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)
  237. default:
  238. appDelegate.messageNotification("E2E Server publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  239. }
  240. }
  241. // --------------------------------------------------------------------------------------------
  242. // MARK: Manage Mark/Delete Encrypted Folder
  243. // --------------------------------------------------------------------------------------------
  244. @objc func markEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  245. var token = NCManageDatabase.sharedInstance.getDirectoryTokenLock(serverUrl: serverUrl) as NSString?
  246. if let error = NCNetworkingSync.sharedManager().lockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url , fileID: fileID, token: &token) as NSError? {
  247. 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)
  248. return false
  249. }
  250. NCManageDatabase.sharedInstance.setDirectoryE2ETokenLock(serverUrl: serverUrl, token: token! as String)
  251. if let error = NCNetworkingSync.sharedManager().markEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID) as NSError? {
  252. 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)
  253. return false
  254. }
  255. 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? {
  256. 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)
  257. return false
  258. }
  259. NCManageDatabase.sharedInstance.setDirectoryE2ETokenLock(serverUrl: serverUrl, token: "")
  260. return true
  261. }
  262. @objc func deletemarkEndToEndFolderEncrypted(_ url: String, fileID: String, serverUrl: String) -> Bool {
  263. var token = NCManageDatabase.sharedInstance.getDirectoryTokenLock(serverUrl: serverUrl) as NSString?
  264. if let error = NCNetworkingSync.sharedManager().lockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url , fileID: fileID, token: &token) as NSError? {
  265. 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)
  266. return false
  267. }
  268. NCManageDatabase.sharedInstance.setDirectoryE2ETokenLock(serverUrl: serverUrl, token: token! as String)
  269. if let error = NCNetworkingSync.sharedManager().deletemarkEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID) as NSError? {
  270. 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)
  271. return false
  272. }
  273. 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? {
  274. 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)
  275. return false
  276. }
  277. NCManageDatabase.sharedInstance.setDirectoryE2ETokenLock(serverUrl: serverUrl, token: "")
  278. return true
  279. }
  280. // --------------------------------------------------------------------------------------------
  281. // MARK: Manage Metadata
  282. // --------------------------------------------------------------------------------------------
  283. func getEndToEndMetadataSuccess(_ metadataNet: CCMetadataNet!) {
  284. guard let privateKey = CCUtility.getEndToEndPrivateKey(appDelegate.activeAccount) else {
  285. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: PrivareKey not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  286. return
  287. }
  288. guard let main = appDelegate.listMainVC[metadataNet.serverUrl] as? CCMain else {
  289. appDelegate.messageNotification("E2E Get Metadata", description: "Serious internal error: Main not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  290. return
  291. }
  292. let serverUrl = metadataNet.serverUrl + "/" + metadataNet.fileName
  293. if (decoderMetadata(metadataNet.encryptedMetadata, privateKey: privateKey, serverUrl: serverUrl) == false) {
  294. return
  295. }
  296. // Clear all date directory and reload data source
  297. NCManageDatabase.sharedInstance.setClearAllDateReadDirectory()
  298. main.reloadDatasource(serverUrl)
  299. }
  300. func getEndToEndMetadataFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  301. // Unauthorized
  302. if (errorCode == kOCErrorServerUnauthorized) {
  303. appDelegate.openLoginView(appDelegate.activeMain, loginType: loginModifyPasswordUser)
  304. } else if (errorCode != 404) {
  305. appDelegate.messageNotification("E2E Get metadata", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  306. }
  307. }
  308. @objc func getEndToEndMetadata(_ metadata: tableMetadata) {
  309. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  310. metadataNet.action = actionGetEndToEndMetadata;
  311. metadataNet.fileID = metadata.fileID;
  312. metadataNet.fileName = metadata.fileName;
  313. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  314. appDelegate.messageNotification("E2E Get metadata", description: "Serious internal error: ServerURL not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  315. return
  316. }
  317. metadataNet.serverUrl = serverUrl
  318. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  319. }
  320. // --------------------------------------------------------------------------------------------
  321. // MARK: Encode / Decode JSON Metadata
  322. // --------------------------------------------------------------------------------------------
  323. @objc func encoderMetadata(_ recordsE2eEncryption: [tableE2eEncryption], publicKey: String, version: Int) -> String? {
  324. let jsonEncoder = JSONEncoder.init()
  325. var files = [String: e2eMetadata.filesKey]()
  326. // Create "files"
  327. for recordE2eEncryption in recordsE2eEncryption {
  328. let plainEncrypted = recordE2eEncryption.key+"|"+recordE2eEncryption.fileName+"|"+recordE2eEncryption.mimeType+"|"+",\(recordE2eEncryption.version)"
  329. guard let encryptedData = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(plainEncrypted, publicKey: publicKey) else {
  330. appDelegate.messageNotification("E2E encore metadata", description: "Serious internal error in creation \"encrypted\" key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  331. return nil
  332. }
  333. let e2eMetadataFilesKey = e2eMetadata.filesKey(initializationVector: recordE2eEncryption.initializationVector, authenticationTag: recordE2eEncryption.authenticationTag, metadataKey: 0, encrypted: String(data: encryptedData, encoding: .utf8)!)
  334. files.updateValue(e2eMetadataFilesKey, forKey: recordE2eEncryption.fileNameIdentifier)
  335. }
  336. // Create "metadata"
  337. let e2eMetadataKey = e2eMetadata.metadataKey(metadataKeys: ["0":"dcccecfvdfvfvsfdvefvefvefvefvefv"], version: version)
  338. // Create final Json e2emetadata
  339. let e2emetadata = e2eMetadata(files: files, metadata: e2eMetadataKey, sharing: nil)
  340. do {
  341. let jsonData = try jsonEncoder.encode(e2emetadata)
  342. let jsonString = String(data: jsonData, encoding: .utf8)
  343. print("JSON String : " + jsonString!)
  344. return jsonString
  345. } catch let error {
  346. appDelegate.messageNotification("E2E encore metadata", description: "Serious internal error in encoding metadata ("+error.localizedDescription+")", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  347. }
  348. return nil
  349. }
  350. // let dataDecoded : NSData = NSData(base64Encoded: encrypted, options: NSData.Base64DecodingOptions(rawValue: 0))!
  351. @objc func decoderMetadata(_ e2eMetaDataJSON: String, privateKey: String, serverUrl: String) -> Bool {
  352. let jsonDecoder = JSONDecoder.init()
  353. let data = e2eMetaDataJSON.data(using: .utf8)
  354. do {
  355. let decode = try jsonDecoder.decode(e2eMetadata.self, from: data!)
  356. let files = decode.files
  357. let metadata = decode.metadata
  358. //let sharing = decode.sharing ---> V 2.0
  359. var decodeMetadataKeys = [String:String]()
  360. for metadataKeys in metadata.metadataKeys {
  361. guard let metadataKeysData : NSData = NSData(base64Encoded: metadataKeys.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
  362. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  363. return false
  364. }
  365. guard let metadataKey = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(metadataKeysData as Data!, privateKey: privateKey) else {
  366. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  367. return false
  368. }
  369. // Encode to Base64
  370. let metadataKeyData = Data(base64Encoded: metadataKey, options: NSData.Base64DecodingOptions(rawValue: 0))!
  371. let metadataKeyBase64 = String(data: metadataKeyData, encoding: .utf8)
  372. decodeMetadataKeys[metadataKeys.key] = metadataKeyBase64
  373. }
  374. for file in files {
  375. let fileNameIdentifier = file.key
  376. let elementOfFile = file.value as e2eMetadata.filesKey
  377. let encrypted = elementOfFile.encrypted
  378. let key = decodeMetadataKeys["\(elementOfFile.metadataKey)"]
  379. guard let decyptedMetadata = NCEndToEndEncryption.sharedManager().decryptMetadata(encrypted, key: key) else {
  380. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  381. return false
  382. }
  383. do {
  384. let decode = try jsonDecoder.decode(e2eMetadata.encrypted.self, from: decyptedMetadata.data(using: .utf8)!)
  385. let object = tableE2eEncryption()
  386. object.account = appDelegate.activeAccount
  387. object.authenticationTag = elementOfFile.authenticationTag
  388. object.fileName = decode.filename
  389. object.fileNameIdentifier = fileNameIdentifier
  390. object.key = decode.key
  391. object.initializationVector = elementOfFile.initializationVector
  392. object.mimeType = decode.mimetype
  393. object.serverUrl = serverUrl
  394. object.version = decode.version
  395. // Write file parameter for decrypted on DB
  396. if NCManageDatabase.sharedInstance.addE2eEncryption(object) == false {
  397. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal write DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  398. return false
  399. }
  400. // Write e2eMetaDataJSON on DB
  401. if NCManageDatabase.sharedInstance.setDirectoryE2EMetadataJSON(serverUrl: serverUrl, metadata: e2eMetaDataJSON) == false {
  402. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal write DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  403. return false
  404. }
  405. } catch let error {
  406. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata ("+error.localizedDescription+")", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  407. return false
  408. }
  409. }
  410. } catch let error {
  411. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata ("+error.localizedDescription+")", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  412. return false
  413. }
  414. return true
  415. }
  416. }