NCEndToEndMetadataV20.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //
  2. // NCEndToEndMetadataV20.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 09/08/23.
  6. // Copyright © 2023 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 Foundation
  24. import NextcloudKit
  25. import Gzip
  26. extension NCEndToEndMetadata {
  27. struct E2eeV20: Codable {
  28. struct Files: Codable {
  29. let authenticationTag: String
  30. let filename: String
  31. let key: String
  32. let mimetype: String
  33. let nonce: String
  34. }
  35. struct ciphertext: Codable {
  36. let counter: Int
  37. let deleted: Bool?
  38. let keyChecksums: [String]?
  39. let files: [String: Files]?
  40. let folders: [String: String]?
  41. }
  42. struct Metadata: Codable {
  43. let ciphertext: String
  44. let nonce: String
  45. let authenticationTag: String
  46. }
  47. struct Users: Codable {
  48. let userId: String
  49. let certificate: String
  50. let encryptedMetadataKey: String?
  51. let encryptedFiledropKey: String?
  52. }
  53. struct Filedrop: Codable {
  54. let ciphertext: String?
  55. let nonce: String?
  56. let authenticationTag: String?
  57. let users: [String: UsersFiledrop]?
  58. struct UsersFiledrop: Codable {
  59. let userId: String?
  60. let encryptedFiledropKey: String?
  61. }
  62. }
  63. let metadata: Metadata
  64. let users: [Users]?
  65. let filedrop: [String: Filedrop]?
  66. let version: String
  67. }
  68. struct E2eeV20Signature: Codable {
  69. struct Metadata: Codable {
  70. let ciphertext: String
  71. let nonce: String
  72. let authenticationTag: String
  73. }
  74. struct Users: Codable {
  75. let userId: String
  76. let certificate: String
  77. let encryptedMetadataKey: String?
  78. }
  79. let metadata: Metadata
  80. let users: [Users]?
  81. let version: String
  82. }
  83. // --------------------------------------------------------------------------------------------
  84. // MARK: Ecode JSON Metadata V2.0
  85. // --------------------------------------------------------------------------------------------
  86. func encodeMetadataV20(account: String, serverUrl: String, ocIdServerUrl: String, userId: String, addUserId: String?, addCertificate: String?, removeUserId: String?) -> (metadata: String?, signature: String?, counter: Int, error: NKError) {
  87. guard let keyGenerated = NCEndToEndEncryption.sharedManager()?.generateKey() as? Data,
  88. let directoryTop = NCUtility.shared.getDirectoryE2EETop(serverUrl: serverUrl, account: account) else {
  89. return (nil, nil, 0, NKError(errorCode: NCGlobal.shared.errorUnexpectedResponseFromDB, errorDescription: "_e2e_error_"))
  90. }
  91. let isDirectoryTop = NCUtility.shared.isDirectoryE2EETop(account: account, serverUrl: serverUrl)
  92. var metadataKey: String?
  93. var keyChecksums: [String] = []
  94. var usersCodable: [E2eeV20.Users] = []
  95. var filedropCodable: [String: E2eeV20.Filedrop] = [:]
  96. var folders: [String: String] = [:]
  97. var counter: Int = 1
  98. func addUser(userId: String?, certificate: String?) {
  99. guard let userId, let certificate else { return }
  100. let decryptedMetadataKey = keyGenerated
  101. let metadataKey = keyGenerated.base64EncodedString()
  102. if let metadataKeyEncrypted = NCEndToEndEncryption.sharedManager().encryptAsymmetricData(keyGenerated, certificate: certificate) {
  103. let encryptedMetadataKey = metadataKeyEncrypted.base64EncodedString()
  104. NCManageDatabase.shared.addE2EUsersV2(account: account, serverUrl: serverUrl, ocIdServerUrl: ocIdServerUrl, userId: userId, certificate: certificate, encryptedFiledropKey: nil, encryptedMetadataKey: encryptedMetadataKey, decryptedFiledropKey: nil, decryptedMetadataKey: decryptedMetadataKey, filedropKey: nil, metadataKey: metadataKey)
  105. }
  106. }
  107. if isDirectoryTop {
  108. addUser(userId: userId, certificate: CCUtility.getEndToEndCertificate(account))
  109. addUser(userId: addUserId, certificate: addCertificate)
  110. if let removeUserId {
  111. NCManageDatabase.shared.deleteE2EUsersV2(account: account, ocIdServerUrl: ocIdServerUrl, userId: removeUserId)
  112. }
  113. if let users = NCManageDatabase.shared.getE2EUsersV2(account: account, ocIdServerUrl: ocIdServerUrl) {
  114. for user in users {
  115. addUser(userId: user.userId, certificate: user.certificate)
  116. }
  117. }
  118. }
  119. if let e2eUsers = NCManageDatabase.shared.getE2EUsersV2(account: account, ocIdServerUrl: directoryTop.ocId) {
  120. for user in e2eUsers {
  121. if isDirectoryTop {
  122. usersCodable.append(E2eeV20.Users(userId: user.userId, certificate: user.certificate, encryptedMetadataKey: user.encryptedMetadataKey, encryptedFiledropKey: user.encryptedFiledropKey))
  123. }
  124. if let hash = NCEndToEndEncryption.sharedManager().createSHA256(user.decryptedMetadataKey) {
  125. keyChecksums.append(hash)
  126. }
  127. if let addUserId, user.userId == addUserId {
  128. metadataKey = user.metadataKey
  129. } else if user.userId == userId {
  130. metadataKey = user.metadataKey
  131. }
  132. }
  133. }
  134. if let resultCounter = NCManageDatabase.shared.getCounterE2eMetadataV2(account: account, ocIdServerUrl: ocIdServerUrl) {
  135. counter = resultCounter + 1
  136. }
  137. // Create ciphertext
  138. let e2eEncryptions = NCManageDatabase.shared.getE2eEncryptions(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  139. var filesCodable: [String: E2eeV20.Files] = [:]
  140. for e2eEncryption in e2eEncryptions {
  141. if e2eEncryption.blob == "files" {
  142. let file = E2eeV20.Files(authenticationTag: e2eEncryption.authenticationTag, filename: e2eEncryption.fileName, key: e2eEncryption.key, mimetype: e2eEncryption.mimeType, nonce: e2eEncryption.initializationVector)
  143. filesCodable.updateValue(file, forKey: e2eEncryption.fileNameIdentifier)
  144. } else if e2eEncryption.blob == "folders" {
  145. folders[e2eEncryption.fileNameIdentifier] = e2eEncryption.fileName
  146. }
  147. }
  148. let ciphertext = E2eeV20.ciphertext(counter: counter, deleted: false, keyChecksums: keyChecksums, files: filesCodable, folders: folders)
  149. var authenticationTag: NSString?
  150. var initializationVector: NSString?
  151. do {
  152. let json = try JSONEncoder().encode(ciphertext)
  153. let jsonZip = try json.gzipped()
  154. let ciphertext = NCEndToEndEncryption.sharedManager().encryptPayloadFile(jsonZip, key: metadataKey, initializationVector: &initializationVector, authenticationTag: &authenticationTag)
  155. guard var ciphertext, let initializationVector = initializationVector as? String, let authenticationTag = authenticationTag as? String else {
  156. return (nil, nil, counter, NKError(errorCode: NCGlobal.shared.errorE2EEEncryptPayloadFile, errorDescription: "_e2e_error_"))
  157. }
  158. // Add initializationVector [ANDROID]
  159. ciphertext = ciphertext + "|" + initializationVector
  160. let metadataCodable = E2eeV20.Metadata(ciphertext: ciphertext, nonce: initializationVector, authenticationTag: authenticationTag)
  161. let e2eeCodable = E2eeV20(metadata: metadataCodable, users: usersCodable, filedrop: filedropCodable, version: NCGlobal.shared.e2eeVersionV20)
  162. let e2eeData = try JSONEncoder().encode(e2eeCodable)
  163. e2eeData.printJson()
  164. let e2eeJson = String(data: e2eeData, encoding: .utf8)
  165. let signature = createSignature(account: account, userId: userId, metadata: metadataCodable, users: usersCodable, version: NCGlobal.shared.e2eeVersionV20, certificate: CCUtility.getEndToEndCertificate(account))
  166. return (e2eeJson, signature, counter, NKError())
  167. } catch let error {
  168. return (nil, nil, counter, NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription))
  169. }
  170. }
  171. // --------------------------------------------------------------------------------------------
  172. // MARK: Decode JSON Metadata V2.0
  173. // --------------------------------------------------------------------------------------------
  174. func decodeMetadataV20(_ json: String, signature: String?, serverUrl: String, account: String, ocIdServerUrl: String, urlBase: String, userId: String) -> NKError {
  175. guard let data = json.data(using: .utf8),
  176. let directoryTop = NCUtility.shared.getDirectoryE2EETop(serverUrl: serverUrl, account: account) else {
  177. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyDecodeMetadata, errorDescription: "_e2e_error_")
  178. }
  179. func addE2eEncryption(fileNameIdentifier: String, filename: String, authenticationTag: String, key: String, initializationVector: String, metadataKey: String, mimetype: String, blob: String) {
  180. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) {
  181. let object = tableE2eEncryption.init(account: account, ocIdServerUrl: ocIdServerUrl, fileNameIdentifier: fileNameIdentifier)
  182. object.authenticationTag = authenticationTag
  183. object.blob = blob
  184. object.fileName = filename
  185. object.key = key
  186. object.initializationVector = initializationVector
  187. object.metadataKey = metadataKey
  188. object.mimeType = mimetype
  189. object.serverUrl = serverUrl
  190. // Write file parameter for decrypted on DB
  191. NCManageDatabase.shared.addE2eEncryption(object)
  192. // Update metadata on tableMetadata
  193. metadata.fileNameView = filename
  194. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: filename, mimeType: metadata.contentType, directory: metadata.directory)
  195. metadata.contentType = results.mimeType
  196. metadata.iconName = results.iconName
  197. metadata.classFile = results.classFile
  198. NCManageDatabase.shared.addMetadata(metadata)
  199. }
  200. }
  201. do {
  202. let json = try JSONDecoder().decode(E2eeV20.self, from: data)
  203. let metadata = json.metadata
  204. let users = json.users
  205. let filedrop = json.filedrop
  206. let version = json.version as String? ?? NCGlobal.shared.e2eeVersionV20
  207. if let users {
  208. for user in users {
  209. var decryptedMetadataKey: Data?
  210. var decryptedFiledropKey: Data?
  211. var metadataKey: String?
  212. var filedropKey: String?
  213. if let encryptedMetadataKey = user.encryptedMetadataKey {
  214. let data = Data(base64Encoded: encryptedMetadataKey)
  215. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: CCUtility.getEndToEndPrivateKey(account)) {
  216. decryptedMetadataKey = decrypted
  217. metadataKey = decrypted.base64EncodedString()
  218. }
  219. }
  220. if let encryptedFiledropKey = user.encryptedFiledropKey {
  221. let data = Data(base64Encoded: encryptedFiledropKey)
  222. if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: CCUtility.getEndToEndPrivateKey(account)) {
  223. decryptedFiledropKey = decrypted
  224. filedropKey = decrypted.base64EncodedString()
  225. }
  226. }
  227. NCManageDatabase.shared.addE2EUsersV2(account: account,
  228. serverUrl: serverUrl,
  229. ocIdServerUrl: ocIdServerUrl,
  230. userId: user.userId,
  231. certificate: user.certificate,
  232. encryptedFiledropKey: user.encryptedFiledropKey,
  233. encryptedMetadataKey: user.encryptedMetadataKey,
  234. decryptedFiledropKey: decryptedFiledropKey,
  235. decryptedMetadataKey: decryptedMetadataKey,
  236. filedropKey: filedropKey,
  237. metadataKey: metadataKey)
  238. }
  239. }
  240. if let tableE2eUsersV2 = NCManageDatabase.shared.getE2EUsersV2(account: account, ocIdServerUrl: directoryTop.ocId, userId: userId),
  241. let metadataKey = tableE2eUsersV2.metadataKey,
  242. let decryptedMetadataKey = tableE2eUsersV2.decryptedMetadataKey {
  243. // SIGNATURE CHECK
  244. guard let signature,
  245. verifySignature(account: account, signature: signature, userId: tableE2eUsersV2.userId, metadata: metadata, users: users, version: version, certificate: tableE2eUsersV2.certificate) else {
  246. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyVerifySignature, errorDescription: "_e2e_error_")
  247. }
  248. // CIPHERTEXT
  249. guard let decrypted = NCEndToEndEncryption.sharedManager().decryptPayloadFile(metadata.ciphertext, key: metadataKey, initializationVector: metadata.nonce, authenticationTag: metadata.authenticationTag),
  250. decrypted.isGzipped else {
  251. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyCiphertext, errorDescription: "_e2e_error_")
  252. }
  253. let data = try decrypted.gunzipped()
  254. if let jsonText = String(data: data, encoding: .utf8) {
  255. print(jsonText)
  256. }
  257. let json = try JSONDecoder().decode(E2eeV20.ciphertext.self, from: data)
  258. // Check "checksums"
  259. guard let keyChecksums = json.keyChecksums,
  260. let hash = NCEndToEndEncryption.sharedManager().createSHA256(decryptedMetadataKey),
  261. keyChecksums.contains(hash) else {
  262. return NKError(errorCode: NCGlobal.shared.errorE2EEKeyChecksums, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  263. }
  264. print("\n\nCOUNTER -------------------------------")
  265. print("Counter: \(json.counter)")
  266. // Check "counter"
  267. if let resultCounter = NCManageDatabase.shared.getCounterE2eMetadataV2(account: account, ocIdServerUrl: ocIdServerUrl) {
  268. print("Counter saved: \(resultCounter)")
  269. if json.counter > resultCounter {
  270. return NKError(errorCode: NCGlobal.shared.errorE2EECounter, errorDescription: NSLocalizedString("_e2e_error_", comment: ""))
  271. }
  272. } else {
  273. print("Counter RESET")
  274. NCManageDatabase.shared.updateCounterE2eMetadataV2(account: account, ocIdServerUrl: ocIdServerUrl, counter: json.counter)
  275. }
  276. // Check "deleted"
  277. if let deleted = json.deleted, deleted {
  278. // TODO: We need to check deleted, id yes ???
  279. }
  280. NCManageDatabase.shared.addE2eMetadataV2(account: account, serverUrl: serverUrl, ocIdServerUrl: ocIdServerUrl, keyChecksums: json.keyChecksums, deleted: json.deleted ?? false, folders: json.folders, version: version)
  281. if let files = json.files {
  282. print("\nFILES ---------------------------------\n")
  283. for file in files {
  284. addE2eEncryption(fileNameIdentifier: file.key, filename: file.value.filename, authenticationTag: file.value.authenticationTag, key: file.value.key, initializationVector: file.value.nonce, metadataKey: metadataKey, mimetype: file.value.mimetype, blob: "files")
  285. print("filename: \(file.value.filename)")
  286. print("fileNameIdentifier: \(file.key)")
  287. print("mimetype: \(file.value.mimetype)")
  288. print("\n")
  289. }
  290. }
  291. if let folders = json.folders {
  292. print("FOLDERS--------------------------------\n")
  293. for folder in folders {
  294. addE2eEncryption(fileNameIdentifier: folder.key, filename: folder.value, authenticationTag: metadata.authenticationTag, key: metadataKey, initializationVector: metadata.nonce, metadataKey: metadataKey, mimetype: "httpd/unix-directory", blob: "folders")
  295. print("filename: \(folder.value)")
  296. print("fileNameIdentifier: \(folder.key)")
  297. print("\n")
  298. }
  299. }
  300. print("---------------------------------------\n\n")
  301. }
  302. } catch let error {
  303. return NKError(errorCode: NCGlobal.shared.errorE2EEJSon, errorDescription: error.localizedDescription)
  304. }
  305. return NKError()
  306. }
  307. // MARK: -
  308. func createSignature(account: String, userId: String, metadata: E2eeV20.Metadata, users: [E2eeV20.Users]?, version: String, certificate: String) -> String? {
  309. guard let users else { return nil }
  310. var usersSignatureCodable: [E2eeV20Signature.Users] = []
  311. for user in users {
  312. usersSignatureCodable.append(E2eeV20Signature.Users(userId: user.userId, certificate: user.certificate, encryptedMetadataKey: user.encryptedMetadataKey))
  313. }
  314. let signatureCodable = E2eeV20Signature(metadata: E2eeV20Signature.Metadata(ciphertext: metadata.ciphertext, nonce: metadata.nonce, authenticationTag: metadata.authenticationTag), users: usersSignatureCodable, version: version)
  315. do {
  316. let jsonEncoder = JSONEncoder()
  317. let json = try jsonEncoder.encode(signatureCodable)
  318. let dataSerialization = try JSONSerialization.jsonObject(with: json, options: [])
  319. let decoded = try? JSONSerialization.data(withJSONObject: dataSerialization, options: [.sortedKeys, .withoutEscapingSlashes])
  320. let base64 = decoded!.base64EncodedString()
  321. if let base64Data = base64.data(using: .utf8),
  322. let signatureData = NCEndToEndEncryption.sharedManager().generateSignatureCMS(base64Data, certificate: certificate, privateKey: CCUtility.getEndToEndPrivateKey(account), userId: userId) {
  323. return signatureData.base64EncodedString()
  324. }
  325. } catch {
  326. print("Error: \(error.localizedDescription)")
  327. }
  328. return nil
  329. }
  330. func verifySignature(account: String, signature: String, userId: String, metadata: E2eeV20.Metadata, users: [E2eeV20.Users]?, version: String, certificate: String) -> Bool {
  331. guard let users else { return false }
  332. var usersSignatureCodable: [E2eeV20Signature.Users] = []
  333. for user in users {
  334. usersSignatureCodable.append(E2eeV20Signature.Users(userId: user.userId, certificate: user.certificate, encryptedMetadataKey: user.encryptedMetadataKey))
  335. }
  336. let signatureCodable = E2eeV20Signature(metadata: E2eeV20Signature.Metadata(ciphertext: metadata.ciphertext, nonce: metadata.nonce, authenticationTag: metadata.authenticationTag), users: usersSignatureCodable, version: version)
  337. do {
  338. let jsonEncoder = JSONEncoder()
  339. let json = try jsonEncoder.encode(signatureCodable)
  340. let dataSerialization = try JSONSerialization.jsonObject(with: json, options: [])
  341. let decoded = try? JSONSerialization.data(withJSONObject: dataSerialization, options: [.sortedKeys, .withoutEscapingSlashes])
  342. let base64 = decoded!.base64EncodedString()
  343. if let base64Data = base64.data(using: .utf8),
  344. let signatureData = Data(base64Encoded: signature) {
  345. let certificates = users.map { $0.certificate }
  346. return NCEndToEndEncryption.sharedManager().verifySignatureCMS(signatureData, data: base64Data, certificates: certificates)
  347. }
  348. } catch {
  349. print("Error: \(error.localizedDescription)")
  350. }
  351. return false
  352. }
  353. }