NCEndToEndMetadataV1.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. //
  2. // NCEndToEndMetadataV1.swift
  3. // Created by Marino Faggiana on 09/08/23.
  4. // Copyright © 2023 Marino Faggiana. All rights reserved.
  5. //
  6. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  7. //
  8. // This program is free software: you can redistribute it and/or modify
  9. // it under the terms of the GNU General Public License as published by
  10. // the Free Software Foundation, either version 3 of the License, or
  11. // (at your option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU General Public License
  19. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. //
  21. import Foundation
  22. import UIKit
  23. import NextcloudKit
  24. extension NCEndToEndMetadata {
  25. struct E2eeV1: Codable {
  26. struct Metadata: Codable {
  27. let metadataKeys: [String: String]
  28. let version: Double
  29. }
  30. struct Encrypted: Codable {
  31. let key: String
  32. let filename: String
  33. let mimetype: String
  34. }
  35. struct Files: Codable {
  36. let initializationVector: String
  37. let authenticationTag: String?
  38. let metadataKey: Int
  39. let encrypted: String
  40. }
  41. let metadata: Metadata
  42. let files: [String: Files]?
  43. }
  44. struct E2eeV12: Codable {
  45. struct Metadata: Codable {
  46. let metadataKey: String
  47. let version: Double
  48. let checksum: String?
  49. }
  50. struct Encrypted: Codable {
  51. let key: String
  52. let filename: String
  53. let mimetype: String
  54. }
  55. struct Files: Codable {
  56. let initializationVector: String
  57. let authenticationTag: String?
  58. let encrypted: String
  59. }
  60. struct Filedrop: Codable {
  61. let initializationVector: String
  62. let authenticationTag: String?
  63. let encrypted: String
  64. let encryptedKey: String?
  65. let encryptedTag: String?
  66. let encryptedInitializationVector: String?
  67. }
  68. let metadata: Metadata
  69. let files: [String: Files]?
  70. let filedrop: [String: Filedrop]?
  71. }
  72. // --------------------------------------------------------------------------------------------
  73. // MARK: Ecode JSON Metadata V1.2
  74. // --------------------------------------------------------------------------------------------
  75. func encodeMetadataV12(account: String, serverUrl: String, ocIdServerUrl: String) -> (metadata: String?, signature: String?, counter: Int, error: NKError) {
  76. let encoder = JSONEncoder()
  77. var metadataKey: String = ""
  78. let metadataVersion = 1.2
  79. var files: [String: E2eeV12.Files] = [:]
  80. var filesCodable: [String: E2eeV12.Files]?
  81. var filedrop: [String: E2eeV12.Filedrop] = [:]
  82. var filedropCodable: [String: E2eeV12.Filedrop]?
  83. let privateKey = NCKeychain().getEndToEndPrivateKey(account: account)
  84. var fileNameIdentifiers: [String] = []
  85. let e2eEncryptions = self.database.getE2eEncryptions(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  86. //
  87. // metadata
  88. //
  89. if e2eEncryptions.isEmpty, let key = NCEndToEndEncryption.shared().generateKey() as? NSData {
  90. if let key = key.base64EncodedString().data(using: .utf8)?.base64EncodedString().data(using: .utf8),
  91. let metadataKeyEncrypted = NCEndToEndEncryption.shared().encryptAsymmetricData(key, privateKey: privateKey) {
  92. metadataKey = metadataKeyEncrypted.base64EncodedString()
  93. }
  94. } else if let metadatakey = (e2eEncryptions.first!.metadataKey.data(using: .utf8)?.base64EncodedString().data(using: .utf8)),
  95. let metadataKeyEncrypted = NCEndToEndEncryption.shared().encryptAsymmetricData(metadatakey, privateKey: privateKey) {
  96. metadataKey = metadataKeyEncrypted.base64EncodedString()
  97. }
  98. for e2eEncryption in e2eEncryptions {
  99. //
  100. // files & folders
  101. //
  102. if e2eEncryption.blob == "files" || e2eEncryption.blob == "folders" {
  103. let encrypted = E2eeV12.Encrypted(key: e2eEncryption.key, filename: e2eEncryption.fileName, mimetype: e2eEncryption.mimeType)
  104. do {
  105. // Create "encrypted"
  106. var json = try encoder.encode(encrypted)
  107. json = json.base64EncodedString().data(using: .utf8)!
  108. if let encrypted = NCEndToEndEncryption.shared().encryptPayloadFile(json, key: e2eEncryption.metadataKey) {
  109. let record = E2eeV12.Files(initializationVector: e2eEncryption.initializationVector, authenticationTag: e2eEncryption.authenticationTag, encrypted: encrypted)
  110. files.updateValue(record, forKey: e2eEncryption.fileNameIdentifier)
  111. }
  112. fileNameIdentifiers.append(e2eEncryption.fileNameIdentifier)
  113. } catch let error {
  114. return (nil, nil, 0, NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription))
  115. }
  116. }
  117. //
  118. // filedrop
  119. //
  120. if e2eEncryption.blob == "filedrop" {
  121. var encryptedKey: String?
  122. var encryptedInitializationVector: NSString?
  123. var encryptedTag: NSString?
  124. if let metadataKeyFiledrop = (e2eEncryption.metadataKey.data(using: .utf8)?.base64EncodedString().data(using: .utf8)),
  125. let metadataKeyEncrypted = NCEndToEndEncryption.shared().encryptAsymmetricData(metadataKeyFiledrop, privateKey: privateKey) {
  126. encryptedKey = metadataKeyEncrypted.base64EncodedString()
  127. }
  128. let encrypted = E2eeV12.Encrypted(key: e2eEncryption.key, filename: e2eEncryption.fileName, mimetype: e2eEncryption.mimeType)
  129. do {
  130. // Create "encrypted"
  131. var json = try encoder.encode(encrypted)
  132. json = json.base64EncodedString().data(using: .utf8)!
  133. if let encrypted = NCEndToEndEncryption.shared().encryptPayloadFile(json, key: e2eEncryption.metadataKey, initializationVector: &encryptedInitializationVector, authenticationTag: &encryptedTag) {
  134. let record = E2eeV12.Filedrop(initializationVector: e2eEncryption.initializationVector, authenticationTag: e2eEncryption.authenticationTag, encrypted: encrypted, encryptedKey: encryptedKey, encryptedTag: encryptedTag as? String, encryptedInitializationVector: encryptedInitializationVector as? String)
  135. filedrop.updateValue(record, forKey: e2eEncryption.fileNameIdentifier)
  136. }
  137. } catch let error {
  138. return (nil, nil, 0, NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription))
  139. }
  140. }
  141. }
  142. // Create checksum
  143. let passphrase = NCKeychain().getEndToEndPassphrase(account: account)?.replacingOccurrences(of: " ", with: "") ?? ""
  144. let dataChecksum = (passphrase + fileNameIdentifiers.sorted().joined() + metadataKey).data(using: .utf8)
  145. let checksum = NCEndToEndEncryption.shared().createSHA256(dataChecksum)
  146. // Create Json
  147. let metadata = E2eeV12.Metadata(metadataKey: metadataKey, version: metadataVersion, checksum: checksum)
  148. if !files.isEmpty { filesCodable = files }
  149. if !filedrop.isEmpty { filedropCodable = filedrop }
  150. let e2ee = E2eeV12(metadata: metadata, files: filesCodable, filedrop: filedropCodable)
  151. do {
  152. let data = try encoder.encode(e2ee)
  153. data.printJson()
  154. let jsonString = String(data: data, encoding: .utf8)
  155. // Updated metadata to 1.2
  156. if self.database.getE2eMetadata(account: account, serverUrl: serverUrl) == nil {
  157. self.database.setE2eMetadata(account: account, serverUrl: serverUrl, metadataKey: metadataKey, version: metadataVersion)
  158. }
  159. return (jsonString, nil, 0, NKError())
  160. } catch let error {
  161. return (nil, nil, 0, NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription))
  162. }
  163. }
  164. // --------------------------------------------------------------------------------------------
  165. // MARK: Decode JSON Metadata V1.2
  166. // --------------------------------------------------------------------------------------------
  167. func decodeMetadataV12(_ json: String, serverUrl: String, ocIdServerUrl: String, session: NCSession.Session) -> NKError {
  168. guard let data = json.data(using: .utf8) else {
  169. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: "_e2e_error_")
  170. }
  171. let decoder = JSONDecoder()
  172. let privateKey = NCKeychain().getEndToEndPrivateKey(account: session.account)
  173. var metadataVersion: Double = 0
  174. var metadataKey = ""
  175. do {
  176. let json = try decoder.decode(E2eeV12.self, from: data)
  177. let metadata = json.metadata
  178. let files = json.files
  179. let filedrop = json.filedrop
  180. var fileNameIdentifiers: [String] = []
  181. metadataVersion = metadata.version
  182. //
  183. // metadata
  184. //
  185. let data = Data(base64Encoded: metadata.metadataKey)
  186. if let decrypted = NCEndToEndEncryption.shared().decryptAsymmetricData(data, privateKey: privateKey),
  187. let keyData = Data(base64Encoded: decrypted),
  188. let key = String(data: keyData, encoding: .utf8) {
  189. metadataKey = key
  190. } else {
  191. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyDecodeMetadata, errorDescription: "_e2e_error_")
  192. }
  193. // DATA
  194. self.database.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", session.account, serverUrl))
  195. //
  196. // files
  197. //
  198. if let files = files {
  199. for file in files {
  200. let fileNameIdentifier = file.key
  201. let files = file.value as E2eeV12.Files
  202. let encrypted = files.encrypted
  203. let authenticationTag = files.authenticationTag
  204. let initializationVector = files.initializationVector
  205. fileNameIdentifiers.append(fileNameIdentifier)
  206. if let decrypted = NCEndToEndEncryption.shared().decryptPayloadFile(encrypted, key: metadataKey),
  207. let decryptedData = Data(base64Encoded: decrypted) {
  208. do {
  209. decryptedData.printJson()
  210. let encrypted = try decoder.decode(E2eeV12.Encrypted.self, from: decryptedData)
  211. if let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", session.account, fileNameIdentifier)) {
  212. let object = tableE2eEncryption.init(account: session.account, ocIdServerUrl: ocIdServerUrl, fileNameIdentifier: fileNameIdentifier)
  213. object.authenticationTag = authenticationTag ?? ""
  214. object.blob = "files"
  215. object.fileName = encrypted.filename
  216. object.key = encrypted.key
  217. object.initializationVector = initializationVector
  218. object.metadataKey = metadataKey
  219. object.version = "\(metadataVersion)"
  220. object.mimeType = encrypted.mimetype
  221. object.serverUrl = serverUrl
  222. // Write file parameter for decrypted on DB
  223. self.database.addE2eEncryption(object)
  224. // Update metadata on tableMetadata
  225. metadata.fileNameView = encrypted.filename
  226. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory, account: session.account)
  227. metadata.contentType = results.mimeType
  228. metadata.iconName = results.iconName
  229. metadata.classFile = results.classFile
  230. self.database.addMetadata(metadata)
  231. }
  232. } catch let error {
  233. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  234. }
  235. }
  236. }
  237. }
  238. //
  239. // filedrop
  240. //
  241. if let filedrop = filedrop {
  242. for filedrop in filedrop {
  243. let fileNameIdentifier = filedrop.key
  244. let filedrop = filedrop.value as E2eeV12.Filedrop
  245. var metadataKeyFiledrop: String?
  246. if let encryptedKey = filedrop.encryptedKey,
  247. let data = Data(base64Encoded: encryptedKey),
  248. let decrypted = NCEndToEndEncryption.shared().decryptAsymmetricData(data, privateKey: privateKey) {
  249. let keyData = Data(base64Encoded: decrypted)
  250. metadataKeyFiledrop = String(data: keyData!, encoding: .utf8)
  251. }
  252. if let decrypted = NCEndToEndEncryption.shared().decryptPayloadFile(filedrop.encrypted, key: metadataKeyFiledrop, initializationVector: filedrop.encryptedInitializationVector, authenticationTag: filedrop.encryptedTag),
  253. let decryptedData = Data(base64Encoded: decrypted) {
  254. do {
  255. decryptedData.printJson()
  256. let encrypted = try decoder.decode(E2eeV1.Encrypted.self, from: decryptedData)
  257. if let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", session.account, fileNameIdentifier)) {
  258. let object = tableE2eEncryption.init(account: session.account, ocIdServerUrl: ocIdServerUrl, fileNameIdentifier: fileNameIdentifier)
  259. object.authenticationTag = filedrop.authenticationTag ?? ""
  260. object.blob = "filedrop"
  261. object.fileName = encrypted.filename
  262. object.key = encrypted.key
  263. object.initializationVector = filedrop.initializationVector
  264. object.metadataKey = metadataKey
  265. object.version = "\(metadataVersion)"
  266. object.mimeType = encrypted.mimetype
  267. object.serverUrl = serverUrl
  268. // Write file parameter for decrypted on DB
  269. self.database.addE2eEncryption(object)
  270. // Update metadata on tableMetadata
  271. metadata.fileNameView = encrypted.filename
  272. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory, account: session.account)
  273. metadata.contentType = results.mimeType
  274. metadata.iconName = results.iconName
  275. metadata.classFile = results.classFile
  276. self.database.addMetadata(metadata)
  277. }
  278. } catch let error {
  279. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  280. }
  281. }
  282. }
  283. }
  284. // verify checksum
  285. let passphrase = NCKeychain().getEndToEndPassphrase(account: session.account)?.replacingOccurrences(of: " ", with: "") ?? ""
  286. let dataChecksum = (passphrase + fileNameIdentifiers.sorted().joined() + metadata.metadataKey).data(using: .utf8)
  287. let checksum = NCEndToEndEncryption.shared().createSHA256(dataChecksum)
  288. if metadata.checksum != checksum {
  289. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyChecksums, errorDescription: "_e2e_error_")
  290. }
  291. } catch let error {
  292. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  293. }
  294. return NKError()
  295. }
  296. // --------------------------------------------------------------------------------------------
  297. // MARK: Decode JSON Metadata V1.1
  298. // --------------------------------------------------------------------------------------------
  299. func decodeMetadataV1(_ json: String, serverUrl: String, ocIdServerUrl: String, session: NCSession.Session) -> NKError {
  300. guard let data = json.data(using: .utf8) else {
  301. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: "_e2e_error_")
  302. }
  303. let decoder = JSONDecoder()
  304. let privateKey = NCKeychain().getEndToEndPrivateKey(account: session.account)
  305. var metadataVersion: Double = 0
  306. do {
  307. let json = try decoder.decode(E2eeV1.self, from: data)
  308. let metadata = json.metadata
  309. let files = json.files
  310. var metadataKeys: [String: String] = [:]
  311. metadataVersion = metadata.version
  312. // DATA
  313. self.database.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", session.account, serverUrl))
  314. //
  315. // metadata
  316. //
  317. for metadataKey in metadata.metadataKeys {
  318. let data = Data(base64Encoded: metadataKey.value)
  319. if let decrypted = NCEndToEndEncryption.shared().decryptAsymmetricData(data, privateKey: privateKey),
  320. let keyData = Data(base64Encoded: decrypted) {
  321. let key = String(data: keyData, encoding: .utf8)
  322. metadataKeys[metadataKey.key] = key
  323. }
  324. }
  325. //
  326. // verify version
  327. //
  328. if let tableE2eMetadata = self.database.getE2eMetadata(account: session.account, serverUrl: serverUrl) {
  329. if tableE2eMetadata.version > metadataVersion {
  330. return NKError(errorCode: NCGlobal.shared.errorE2EEVersion, errorDescription: "Version \(tableE2eMetadata.version)")
  331. }
  332. }
  333. //
  334. // files
  335. //
  336. if let files = files {
  337. for files in files {
  338. let fileNameIdentifier = files.key
  339. let files = files.value as E2eeV1.Files
  340. let encrypted = files.encrypted
  341. let authenticationTag = files.authenticationTag
  342. guard let metadataKey = metadataKeys["\(files.metadataKey)"] else { continue }
  343. let metadataKeyIndex = files.metadataKey
  344. let initializationVector = files.initializationVector
  345. if let decrypted = NCEndToEndEncryption.shared().decryptPayloadFile(encrypted, key: metadataKey),
  346. let decryptedData = Data(base64Encoded: decrypted) {
  347. do {
  348. let encrypted = try decoder.decode(E2eeV1.Encrypted.self, from: decryptedData)
  349. if let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", session.account, fileNameIdentifier)) {
  350. let object = tableE2eEncryption.init(account: session.account, ocIdServerUrl: ocIdServerUrl, fileNameIdentifier: fileNameIdentifier)
  351. object.authenticationTag = authenticationTag ?? ""
  352. object.blob = "files"
  353. object.fileName = encrypted.filename
  354. object.key = encrypted.key
  355. object.initializationVector = initializationVector
  356. object.metadataKey = metadataKey
  357. object.metadataKeyIndex = metadataKeyIndex
  358. object.version = "\(metadataVersion)"
  359. object.mimeType = encrypted.mimetype
  360. object.serverUrl = serverUrl
  361. // Write file parameter for decrypted on DB
  362. self.database.addE2eEncryption(object)
  363. // Update metadata on tableMetadata
  364. metadata.fileNameView = encrypted.filename
  365. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: encrypted.filename, mimeType: metadata.contentType, directory: metadata.directory, account: session.account)
  366. metadata.contentType = results.mimeType
  367. metadata.iconName = results.iconName
  368. metadata.classFile = results.classFile
  369. self.database.addMetadata(metadata)
  370. }
  371. } catch let error {
  372. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  373. }
  374. }
  375. }
  376. }
  377. } catch let error {
  378. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  379. }
  380. return NKError()
  381. }
  382. }