NCEndToEndMetadata.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. //
  2. // NCEndToEndMetadata.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 13/11/17.
  6. // Copyright © 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 UIKit
  24. import NextcloudKit
  25. import Gzip
  26. class NCEndToEndMetadata: NSObject {
  27. struct E2eeV1: Codable {
  28. struct Metadata: Codable {
  29. let metadataKeys: [String: String]
  30. let version: Double
  31. }
  32. struct Encrypted: Codable {
  33. let key: String
  34. let filename: String
  35. let mimetype: String
  36. }
  37. struct Files: Codable {
  38. let initializationVector: String
  39. let authenticationTag: String?
  40. let metadataKey: Int
  41. let encrypted: String
  42. }
  43. let metadata: Metadata
  44. let files: [String: Files]?
  45. }
  46. struct E2eeV12: Codable {
  47. struct Metadata: Codable {
  48. let metadataKey: String
  49. let version: Double
  50. let checksum: String?
  51. }
  52. struct Encrypted: Codable {
  53. let key: String
  54. let filename: String
  55. let mimetype: String
  56. }
  57. struct Files: Codable {
  58. let initializationVector: String
  59. let authenticationTag: String?
  60. let encrypted: String
  61. }
  62. struct Filedrop: Codable {
  63. let initializationVector: String
  64. let authenticationTag: String?
  65. let encrypted: String
  66. let encryptedKey: String?
  67. let encryptedTag: String?
  68. let encryptedInitializationVector: String?
  69. }
  70. let metadata: Metadata
  71. let files: [String: Files]?
  72. let filedrop: [String: Filedrop]?
  73. }
  74. struct E2eeV20: Codable {
  75. struct Metadata: Codable {
  76. let ciphertext: String
  77. let nonce: String
  78. let authenticationTag: String
  79. let counter: Double?
  80. }
  81. struct Users: Codable {
  82. let userId: String
  83. let certificate: String
  84. let encryptedMetadataKey: String?
  85. let encryptedFiledropKey: String?
  86. }
  87. struct Filedrop: Codable {
  88. let ciphertext: String?
  89. let nonce: String?
  90. let authenticationTag: String?
  91. let users: [String: UsersFiledrop]?
  92. struct UsersFiledrop: Codable {
  93. let userId: String?
  94. let encryptedFiledropKey: String?
  95. }
  96. }
  97. let metadata: Metadata
  98. let users: [Users]
  99. let filedrop: [String: Filedrop]?
  100. let version: String
  101. }
  102. // --------------------------------------------------------------------------------------------
  103. // MARK: Encode JSON Metadata Bridge
  104. // --------------------------------------------------------------------------------------------
  105. func encoderMetadata(_ items: [tableE2eEncryption], account: String, serverUrl: String) -> (metadata: String?, signature: String?) {
  106. let e2EEApiVersion = NCGlobal.shared.capabilityE2EEApiVersion
  107. switch e2EEApiVersion {
  108. case "1.2":
  109. return encoderMetadataV12(items, account: account, serverUrl: serverUrl)
  110. case "2.0":
  111. return encoderMetadataV20(items, account: account, serverUrl: serverUrl)
  112. default:
  113. return (nil, nil)
  114. }
  115. }
  116. // --------------------------------------------------------------------------------------------
  117. // MARK: Ecode JSON Metadata V1.2
  118. // --------------------------------------------------------------------------------------------
  119. func encoderMetadataV12(_ items: [tableE2eEncryption], account: String, serverUrl: String) -> (metadata: String?, signature: String?) {
  120. let encoder = JSONEncoder()
  121. var metadataKey: String = ""
  122. let metadataVersion = 1.2
  123. var files: [String: E2eeV12.Files] = [:]
  124. var filesCodable: [String: E2eeV12.Files]?
  125. var filedrop: [String: E2eeV12.Filedrop] = [:]
  126. var filedropCodable: [String: E2eeV12.Filedrop]?
  127. let privateKey = CCUtility.getEndToEndPrivateKey(account)
  128. var fileNameIdentifiers: [String] = []
  129. // let shortVersion: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  130. // var filesCodable: [String: E2eeV12.Files] = [String: E2eeV12.Files]()
  131. // var filedropCodable: [String: E2eeV12.Filedrop] = [String: E2eeV12.Filedrop]()
  132. //
  133. // metadata
  134. //
  135. if items.isEmpty, let key = NCEndToEndEncryption.sharedManager()?.generateKey() as? NSData {
  136. if let key = key.base64EncodedString().data(using: .utf8)?.base64EncodedString(),
  137. let metadataKeyEncrypted = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(key, publicKey: nil, privateKey: privateKey) {
  138. metadataKey = metadataKeyEncrypted.base64EncodedString()
  139. }
  140. } else if let metadatakey = (items.first!.metadataKey.data(using: .utf8)?.base64EncodedString()),
  141. let metadataKeyEncrypted = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(metadatakey, publicKey: nil, privateKey: privateKey) {
  142. metadataKey = metadataKeyEncrypted.base64EncodedString()
  143. }
  144. for item in items {
  145. //
  146. // files
  147. //
  148. if item.blob == "files" {
  149. let encrypted = E2eeV12.Encrypted(key: item.key, filename: item.fileName, mimetype: item.mimeType)
  150. do {
  151. // Create "encrypted"
  152. let json = try encoder.encode(encrypted)
  153. if let encrypted = NCEndToEndEncryption.sharedManager().encryptPayloadFile(String(data: json, encoding: .utf8), key: item.metadataKey) {
  154. let record = E2eeV12.Files(initializationVector: item.initializationVector, authenticationTag: item.authenticationTag, encrypted: encrypted)
  155. files.updateValue(record, forKey: item.fileNameIdentifier)
  156. }
  157. fileNameIdentifiers.append(item.fileNameIdentifier)
  158. } catch let error {
  159. print("Serious internal error in encoding metadata (" + error.localizedDescription + ")")
  160. return (nil, nil)
  161. }
  162. }
  163. //
  164. // filedrop
  165. //
  166. if item.blob == "filedrop" {
  167. var encryptedKey: String?
  168. var encryptedInitializationVector: NSString?
  169. var encryptedTag: NSString?
  170. if let metadataKeyFiledrop = (item.metadataKeyFiledrop.data(using: .utf8)?.base64EncodedString()),
  171. let metadataKeyEncrypted = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(metadataKeyFiledrop, publicKey: nil, privateKey: privateKey) {
  172. encryptedKey = metadataKeyEncrypted.base64EncodedString()
  173. }
  174. let encrypted = E2eeV12.Encrypted(key: item.key, filename: item.fileName, mimetype: item.mimeType)
  175. do {
  176. // Create "encrypted"
  177. let json = try encoder.encode(encrypted)
  178. if let encrypted = NCEndToEndEncryption.sharedManager().encryptPayloadFile(String(data: json, encoding: .utf8), key: item.metadataKeyFiledrop, initializationVector: &encryptedInitializationVector, authenticationTag: &encryptedTag) {
  179. let record = E2eeV12.Filedrop(initializationVector: item.initializationVector, authenticationTag: item.authenticationTag, encrypted: encrypted, encryptedKey: encryptedKey, encryptedTag: encryptedTag as? String, encryptedInitializationVector: encryptedInitializationVector as? String)
  180. filedrop.updateValue(record, forKey: item.fileNameIdentifier)
  181. }
  182. } catch let error {
  183. print("Serious internal error in encoding metadata (" + error.localizedDescription + ")")
  184. return (nil, nil)
  185. }
  186. }
  187. }
  188. // Create checksum
  189. let passphrase = CCUtility.getEndToEndPassphrase(account).replacingOccurrences(of: " ", with: "")
  190. let checksum = NCEndToEndEncryption.sharedManager().createSHA256(passphrase + fileNameIdentifiers.sorted().joined() + metadataKey)
  191. // Create Json
  192. let metadata = E2eeV12.Metadata(metadataKey: metadataKey, version: metadataVersion, checksum: checksum)
  193. if !files.isEmpty { filesCodable = files }
  194. if !filedrop.isEmpty { filedropCodable = filedrop }
  195. let e2ee = E2eeV12(metadata: metadata, files: filesCodable, filedrop: filedropCodable)
  196. do {
  197. let data = try encoder.encode(e2ee)
  198. data.printJson()
  199. let jsonString = String(data: data, encoding: .utf8)
  200. // Updated metadata to 1.2
  201. if NCManageDatabase.shared.getE2eMetadata(account: account, serverUrl: serverUrl) == nil {
  202. NCManageDatabase.shared.setE2eMetadata(account: account, serverUrl: serverUrl, metadataKey: metadataKey, version: metadataVersion)
  203. }
  204. return (jsonString, nil)
  205. } catch let error {
  206. print("Serious internal error in encoding e2ee (" + error.localizedDescription + ")")
  207. return (nil, nil)
  208. }
  209. }
  210. // --------------------------------------------------------------------------------------------
  211. // MARK: Ecode JSON Metadata V2.0
  212. // --------------------------------------------------------------------------------------------
  213. func encoderMetadataV20(_ items: [tableE2eEncryption], account: String, serverUrl: String) -> (metadata: String?, signature: String?) {
  214. return (nil, nil)
  215. }
  216. // --------------------------------------------------------------------------------------------
  217. // MARK: Decode JSON Metadata Bridge
  218. // --------------------------------------------------------------------------------------------
  219. func decoderMetadata(_ json: String, serverUrl: String, account: String, urlBase: String, userId: String, ownerId: String?) -> NKError {
  220. guard let data = json.data(using: .utf8) else {
  221. return (NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decoding JSON"))
  222. }
  223. data.printJson()
  224. let decoder = JSONDecoder()
  225. if (try? decoder.decode(E2eeV1.self, from: data)) != nil {
  226. return decoderMetadataV1(json, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId)
  227. } else if (try? decoder.decode(E2eeV12.self, from: data)) != nil {
  228. return decoderMetadataV12(json, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, ownerId: ownerId)
  229. } else if (try? decoder.decode(E2eeV20.self, from: data)) != nil {
  230. return decoderMetadataV20(json, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, ownerId: ownerId)
  231. } else {
  232. return NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "Server E2EE version " + NCGlobal.shared.capabilityE2EEApiVersion + ", not compatible")
  233. }
  234. }
  235. // --------------------------------------------------------------------------------------------
  236. // MARK: Decode JSON Metadata V2.0
  237. // --------------------------------------------------------------------------------------------
  238. func decoderMetadataV20(_ json: String, serverUrl: String, account: String, urlBase: String, userId: String, ownerId: String?) -> NKError {
  239. guard let data = json.data(using: .utf8) else {
  240. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decoding JSON")
  241. }
  242. func addE2eEncryption(fileNameIdentifier: String, filename: String, authenticationTag: String?, key: String, initializationVector: String, metadataKey: String, mimetype: String) {
  243. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
  244. let object = tableE2eEncryption()
  245. object.account = account
  246. object.authenticationTag = authenticationTag ?? ""
  247. object.blob = "files"
  248. object.fileName = filename
  249. object.fileNameIdentifier = fileNameIdentifier
  250. object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: filename, serverUrl: serverUrl, urlBase: urlBase, userId: userId, account: account)
  251. object.key = key
  252. object.initializationVector = initializationVector
  253. object.metadataKey = metadataKey
  254. object.mimeType = mimetype
  255. object.serverUrl = serverUrl
  256. // Write file parameter for decrypted on DB
  257. NCManageDatabase.shared.addE2eEncryption(object)
  258. // Update metadata on tableMetadata
  259. metadata.fileNameView = filename
  260. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: filename, mimeType: metadata.contentType, directory: metadata.directory)
  261. metadata.contentType = results.mimeType
  262. metadata.iconName = results.iconName
  263. metadata.classFile = results.classFile
  264. NCManageDatabase.shared.addMetadata(metadata)
  265. }
  266. }
  267. let decoder = JSONDecoder()
  268. let privateKey = CCUtility.getEndToEndPrivateKey(account)
  269. do {
  270. let json = try decoder.decode(E2eeV20.self, from: data)
  271. let metadata = json.metadata
  272. let users = json.users
  273. let filedrop = json.filedrop
  274. let version = json.version as String? ?? "2.0"
  275. // DATA
  276. NCManageDatabase.shared.deleteE2eMetadataV2(account: account, serverUrl: serverUrl)
  277. NCManageDatabase.shared.deleteE2EUsersV2(account: account, serverUrl: serverUrl)
  278. NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  279. //
  280. // users
  281. //
  282. for user in users {
  283. var decryptedMetadataKey: Data?
  284. var decryptedFiledropKey: Data?
  285. var metadataKey: String?
  286. var filedropKey: String?
  287. if let encryptedMetadataKey = user.encryptedMetadataKey {
  288. let data = Data(base64Encoded: encryptedMetadataKey)
  289. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: privateKey) {
  290. decryptedMetadataKey = decrypted
  291. metadataKey = decrypted.base64EncodedString()
  292. }
  293. }
  294. if let encryptedFiledropKey = user.encryptedFiledropKey {
  295. let data = Data(base64Encoded: encryptedFiledropKey)
  296. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: privateKey) {
  297. decryptedFiledropKey = decrypted
  298. filedropKey = decrypted.base64EncodedString()
  299. }
  300. }
  301. NCManageDatabase.shared.setE2EUsersV2(account: account, serverUrl: serverUrl, userId: user.userId, certificate: user.certificate, encryptedFiledropKey: user.encryptedFiledropKey, encryptedMetadataKey: user.encryptedMetadataKey, decryptedFiledropKey: decryptedFiledropKey, decryptedMetadataKey: decryptedMetadataKey, filedropKey: filedropKey, metadataKey: metadataKey)
  302. }
  303. //
  304. // metadata
  305. //
  306. if let tableE2eUsersV2 = NCManageDatabase.shared.getE2EUsersV2(account: account, serverUrl: serverUrl, userId: userId), let metadataKey = tableE2eUsersV2.metadataKey {
  307. if let decrypted = NCEndToEndEncryption.sharedManager().decryptPayloadFile(metadata.ciphertext, key: tableE2eUsersV2.metadataKey, initializationVector: metadata.nonce, authenticationTag: metadata.authenticationTag) {
  308. if decrypted.isGzipped {
  309. do {
  310. let data = try decrypted.gunzipped()
  311. if let jsonText = String(data: data, encoding: .utf8) {
  312. print(jsonText)
  313. }
  314. if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
  315. let keyChecksums = json["keyChecksums"] as? [String]
  316. let deleted = json["deleted"] as? Bool ?? false
  317. let counter = json["counter"] as? Int ?? 0
  318. // Signature
  319. if let keyChecksums,
  320. let hash = NCEndToEndEncryption.sharedManager().createSHA256(from: tableE2eUsersV2.decryptedMetadataKey),
  321. !keyChecksums.contains(hash) {
  322. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyChecksums, errorDescription: NSLocalizedString("_e2ee_signature_error_", comment: ""))
  323. }
  324. NCManageDatabase.shared.setE2eMetadataV2(account: account, serverUrl: serverUrl, keyChecksums: keyChecksums, deleted: deleted, counter: counter, folders: json["folders"] as? [String: String], version: version)
  325. if let files = json["files"] as? [String: Any] {
  326. for file in files {
  327. let uid = file.key
  328. if let dic = file.value as? [String: String] {
  329. if let authenticationTag = dic["authenticationTag"],
  330. let nonce = dic["nonce"],
  331. let mimetype = dic["mimetype"],
  332. let key = dic["key"],
  333. let filename = dic["filename"] {
  334. addE2eEncryption(fileNameIdentifier: uid, filename: filename, authenticationTag: authenticationTag, key: key, initializationVector: nonce, metadataKey: metadataKey, mimetype: mimetype)
  335. }
  336. }
  337. }
  338. }
  339. if let folders = json["folders"] as? [String: String] {
  340. for folder in folders {
  341. addE2eEncryption(fileNameIdentifier: folder.key, filename: folder.value, authenticationTag: metadata.authenticationTag, key: metadataKey, initializationVector: metadata.nonce, metadataKey: metadataKey, mimetype: "httpd/unix-directory")
  342. }
  343. }
  344. }
  345. } catch let error {
  346. return NKError(error: error)
  347. }
  348. } else {
  349. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error unzip ciphertext")
  350. }
  351. } else {
  352. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decrypt ciphertext")
  353. }
  354. }
  355. /* TEST CMS
  356. if let cmsData = NCEndToEndEncryption.sharedManager().generateSignatureCMS(data, certificate: CCUtility.getEndToEndCertificate(account), privateKey: CCUtility.getEndToEndPrivateKey(account), publicKey: CCUtility.getEndToEndPublicKey(account), userId: userId) {
  357. let cms = cmsData.base64EncodedString()
  358. print(cms)
  359. let cmsTest = "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"
  360. let data = Data(base64Encoded: cmsTest)
  361. NCEndToEndEncryption.sharedManager().verifySignatureCMS(data, data: nil, publicKey: CCUtility.getEndToEndPublicKey(account), userId: userId)
  362. }
  363. */
  364. } catch let error {
  365. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: error.localizedDescription)
  366. }
  367. return NKError()
  368. }
  369. // --------------------------------------------------------------------------------------------
  370. // MARK: Decode JSON Metadata V1.2
  371. // --------------------------------------------------------------------------------------------
  372. func decoderMetadataV12(_ json: String, serverUrl: String, account: String, urlBase: String, userId: String, ownerId: String?) -> NKError {
  373. guard let data = json.data(using: .utf8) else {
  374. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decoding JSON")
  375. }
  376. let decoder = JSONDecoder()
  377. let privateKey = CCUtility.getEndToEndPrivateKey(account)
  378. var metadataVersion: Double = 0
  379. var metadataKey = ""
  380. do {
  381. let json = try decoder.decode(E2eeV12.self, from: data)
  382. let metadata = json.metadata
  383. let files = json.files
  384. let filedrop = json.filedrop
  385. var fileNameIdentifiers: [String] = []
  386. metadataVersion = metadata.version
  387. //
  388. // metadata
  389. //
  390. let data = Data(base64Encoded: metadata.metadataKey)
  391. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: privateKey),
  392. let keyData = Data(base64Encoded: decrypted),
  393. let key = String(data: keyData, encoding: .utf8) {
  394. metadataKey = key
  395. } else {
  396. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decrypt metadataKey")
  397. }
  398. // DATA
  399. NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  400. //
  401. // files
  402. //
  403. if let files = files {
  404. for file in files {
  405. let fileNameIdentifier = file.key
  406. let files = file.value as E2eeV12.Files
  407. let encrypted = files.encrypted
  408. let authenticationTag = files.authenticationTag
  409. let initializationVector = files.initializationVector
  410. fileNameIdentifiers.append(fileNameIdentifier)
  411. if let decrypted = NCEndToEndEncryption.sharedManager().decryptPayloadFile(encrypted, key: metadataKey),
  412. let decryptedData = Data(base64Encoded: decrypted) {
  413. do {
  414. decryptedData.printJson()
  415. let encrypted = try decoder.decode(E2eeV12.Encrypted.self, from: decryptedData)
  416. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
  417. let object = tableE2eEncryption()
  418. object.account = account
  419. object.authenticationTag = authenticationTag ?? ""
  420. object.blob = "files"
  421. object.fileName = encrypted.filename
  422. object.fileNameIdentifier = fileNameIdentifier
  423. object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: encrypted.filename, serverUrl: serverUrl, urlBase: urlBase, userId: userId, account: account)
  424. object.key = encrypted.key
  425. object.initializationVector = initializationVector
  426. object.metadataKey = metadataKey
  427. object.metadataVersion = metadataVersion
  428. object.mimeType = encrypted.mimetype
  429. object.serverUrl = serverUrl
  430. // Write file parameter for decrypted on DB
  431. NCManageDatabase.shared.addE2eEncryption(object)
  432. // Update metadata on tableMetadata
  433. metadata.fileNameView = encrypted.filename
  434. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory)
  435. metadata.contentType = results.mimeType
  436. metadata.iconName = results.iconName
  437. metadata.classFile = results.classFile
  438. NCManageDatabase.shared.addMetadata(metadata)
  439. }
  440. } catch let error {
  441. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decrypt file: " + error.localizedDescription)
  442. }
  443. }
  444. }
  445. }
  446. //
  447. // filedrop
  448. //
  449. if let filedrop = filedrop {
  450. for filedrop in filedrop {
  451. let fileNameIdentifier = filedrop.key
  452. let filedrop = filedrop.value as E2eeV12.Filedrop
  453. var metadataKeyFiledrop: String?
  454. if let encryptedKey = filedrop.encryptedKey,
  455. let data = Data(base64Encoded: encryptedKey),
  456. let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: privateKey) {
  457. let keyData = Data(base64Encoded: decrypted)
  458. metadataKeyFiledrop = String(data: keyData!, encoding: .utf8)
  459. }
  460. if let decrypted = NCEndToEndEncryption.sharedManager().decryptPayloadFile(filedrop.encrypted, key: metadataKeyFiledrop, initializationVector: filedrop.encryptedInitializationVector, authenticationTag: filedrop.encryptedTag),
  461. let decryptedData = Data(base64Encoded: decrypted) {
  462. do {
  463. decryptedData.printJson()
  464. let encrypted = try decoder.decode(E2eeV1.Encrypted.self, from: decryptedData)
  465. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
  466. let object = tableE2eEncryption()
  467. object.account = account
  468. object.authenticationTag = filedrop.authenticationTag ?? ""
  469. object.blob = "filedrop"
  470. object.fileName = encrypted.filename
  471. object.fileNameIdentifier = fileNameIdentifier
  472. object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: encrypted.filename, serverUrl: serverUrl, urlBase: urlBase, userId: userId, account: account)
  473. object.key = encrypted.key
  474. object.metadataKeyFiledrop = metadataKeyFiledrop ?? ""
  475. object.initializationVector = filedrop.initializationVector
  476. object.metadataKey = metadataKey
  477. object.metadataVersion = metadataVersion
  478. object.mimeType = encrypted.mimetype
  479. object.serverUrl = serverUrl
  480. // Write file parameter for decrypted on DB
  481. NCManageDatabase.shared.addE2eEncryption(object)
  482. // Update metadata on tableMetadata
  483. metadata.fileNameView = encrypted.filename
  484. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory)
  485. metadata.contentType = results.mimeType
  486. metadata.iconName = results.iconName
  487. metadata.classFile = results.classFile
  488. NCManageDatabase.shared.addMetadata(metadata)
  489. }
  490. } catch let error {
  491. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decrypt filedrop: " + error.localizedDescription)
  492. }
  493. }
  494. }
  495. }
  496. // verify checksum
  497. let passphrase = CCUtility.getEndToEndPassphrase(account).replacingOccurrences(of: " ", with: "")
  498. let checksum = NCEndToEndEncryption.sharedManager().createSHA256(passphrase + fileNameIdentifiers.sorted().joined() + metadata.metadataKey)
  499. if metadata.checksum != checksum {
  500. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error checksum")
  501. }
  502. } catch let error {
  503. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: error.localizedDescription)
  504. }
  505. return NKError()
  506. }
  507. // --------------------------------------------------------------------------------------------
  508. // MARK: Decode JSON Metadata V1.1
  509. // --------------------------------------------------------------------------------------------
  510. func decoderMetadataV1(_ json: String, serverUrl: String, account: String, urlBase: String, userId: String) -> NKError {
  511. guard let data = json.data(using: .utf8) else {
  512. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decoding JSON")
  513. }
  514. let decoder = JSONDecoder()
  515. let privateKey = CCUtility.getEndToEndPrivateKey(account)
  516. var metadataVersion: Double = 0
  517. do {
  518. let json = try decoder.decode(E2eeV1.self, from: data)
  519. let metadata = json.metadata
  520. let files = json.files
  521. var metadataKeys: [String: String] = [:]
  522. metadataVersion = metadata.version
  523. // DATA
  524. NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  525. //
  526. // metadata
  527. //
  528. for metadataKey in metadata.metadataKeys {
  529. let data = Data(base64Encoded: metadataKey.value)
  530. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: privateKey),
  531. let keyData = Data(base64Encoded: decrypted) {
  532. let key = String(data: keyData, encoding: .utf8)
  533. metadataKeys[metadataKey.key] = key
  534. }
  535. }
  536. //
  537. // verify version
  538. //
  539. if let tableE2eMetadata = NCManageDatabase.shared.getE2eMetadata(account: account, serverUrl: serverUrl) {
  540. if tableE2eMetadata.version > metadataVersion {
  541. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error verify version \(tableE2eMetadata.version)")
  542. }
  543. }
  544. //
  545. // files
  546. //
  547. if let files = files {
  548. for files in files {
  549. let fileNameIdentifier = files.key
  550. let files = files.value as E2eeV1.Files
  551. let encrypted = files.encrypted
  552. let authenticationTag = files.authenticationTag
  553. guard let metadataKey = metadataKeys["\(files.metadataKey)"] else { continue }
  554. let metadataKeyIndex = files.metadataKey
  555. let initializationVector = files.initializationVector
  556. if let decrypted = NCEndToEndEncryption.sharedManager().decryptPayloadFile(encrypted, key: metadataKey),
  557. let decryptedData = Data(base64Encoded: decrypted) {
  558. do {
  559. let encrypted = try decoder.decode(E2eeV1.Encrypted.self, from: decryptedData)
  560. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
  561. let object = tableE2eEncryption()
  562. object.account = account
  563. object.authenticationTag = authenticationTag ?? ""
  564. object.blob = "files"
  565. object.fileName = encrypted.filename
  566. object.fileNameIdentifier = fileNameIdentifier
  567. object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: encrypted.filename, serverUrl: serverUrl, urlBase: urlBase, userId: userId, account: account)
  568. object.key = encrypted.key
  569. object.initializationVector = initializationVector
  570. object.metadataKey = metadataKey
  571. object.metadataKeyIndex = metadataKeyIndex
  572. object.metadataVersion = metadataVersion
  573. object.mimeType = encrypted.mimetype
  574. object.serverUrl = serverUrl
  575. // Write file parameter for decrypted on DB
  576. NCManageDatabase.shared.addE2eEncryption(object)
  577. // Update metadata on tableMetadata
  578. metadata.fileNameView = encrypted.filename
  579. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory)
  580. metadata.contentType = results.mimeType
  581. metadata.iconName = results.iconName
  582. metadata.classFile = results.classFile
  583. NCManageDatabase.shared.addMetadata(metadata)
  584. }
  585. } catch let error {
  586. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: "Error decrypt file: " + error.localizedDescription)
  587. }
  588. }
  589. }
  590. }
  591. } catch let error {
  592. return NKError(errorCode: NCGlobal.shared.errorE2EE, errorDescription: error.localizedDescription)
  593. }
  594. return NKError()
  595. }
  596. }