NCManageDatabase+E2EE.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //
  2. // NCManageDatabase+E2EE.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/01/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 UIKit
  25. import RealmSwift
  26. import NextcloudKit
  27. class tableE2eEncryptionLock: Object {
  28. @Persisted(primaryKey: true) var fileId = ""
  29. @Persisted var account = ""
  30. @Persisted var date = Date()
  31. @Persisted var serverUrl = ""
  32. @Persisted var e2eToken = ""
  33. }
  34. typealias tableE2eEncryption = tableE2eEncryptionV4
  35. class tableE2eEncryptionV4: Object {
  36. @Persisted(primaryKey: true) var primaryKey = ""
  37. @Persisted var account = ""
  38. @Persisted var authenticationTag: String = ""
  39. @Persisted var blob = "files"
  40. @Persisted var fileName = ""
  41. @Persisted var fileNameIdentifier = ""
  42. @Persisted var key = ""
  43. @Persisted var initializationVector = ""
  44. @Persisted var metadataKey = ""
  45. @Persisted var metadataKeyIndex: Int = 0
  46. @Persisted var version: String = ""
  47. @Persisted var mimeType = ""
  48. @Persisted var ocIdServerUrl: String = ""
  49. @Persisted var serverUrl = ""
  50. convenience init(account: String, ocIdServerUrl: String, fileNameIdentifier: String) {
  51. self.init()
  52. self.primaryKey = account + ocIdServerUrl + fileNameIdentifier
  53. self.account = account
  54. self.ocIdServerUrl = ocIdServerUrl
  55. self.fileNameIdentifier = fileNameIdentifier
  56. }
  57. }
  58. // MARK: -
  59. // MARK: Table V1, V1.2
  60. class tableE2eMetadata12: Object {
  61. @Persisted(primaryKey: true) var serverUrl = ""
  62. @Persisted var account = ""
  63. @Persisted var metadataKey = ""
  64. @Persisted var version: Double = 0
  65. }
  66. // MARK: -
  67. // MARK: Table V2
  68. typealias tableE2eMetadata = tableE2eMetadataV2
  69. class tableE2eMetadataV2: Object {
  70. @Persisted(primaryKey: true) var primaryKey = ""
  71. @Persisted var account = ""
  72. @Persisted var deleted: Bool = false
  73. @Persisted var folders = Map<String, String>()
  74. @Persisted var keyChecksums = List<String>()
  75. @Persisted var ocIdServerUrl: String = ""
  76. @Persisted var serverUrl: String = ""
  77. @Persisted var version: String = NCGlobal.shared.e2eeVersionV20
  78. convenience init(account: String, ocIdServerUrl: String) {
  79. self.init()
  80. self.account = account
  81. self.ocIdServerUrl = ocIdServerUrl
  82. self.primaryKey = account + ocIdServerUrl
  83. }
  84. }
  85. class tableE2eCounter: Object {
  86. @Persisted(primaryKey: true) var primaryKey: String
  87. @Persisted var account: String
  88. @Persisted var counter: Int
  89. @Persisted var ocIdServerUrl: String
  90. convenience init(account: String, ocIdServerUrl: String, counter: Int) {
  91. self.init()
  92. self.account = account
  93. self.ocIdServerUrl = ocIdServerUrl
  94. self.primaryKey = account + ocIdServerUrl
  95. self.counter = counter
  96. }
  97. }
  98. class tableE2eUsers: Object {
  99. @Persisted(primaryKey: true) var primaryKey = ""
  100. @Persisted var account = ""
  101. @Persisted var certificate = ""
  102. @Persisted var encryptedMetadataKey: String?
  103. @Persisted var metadataKey: Data?
  104. @Persisted var ocIdServerUrl: String = ""
  105. @Persisted var serverUrl: String = ""
  106. @Persisted var userId = ""
  107. convenience init(account: String, ocIdServerUrl: String, userId: String) {
  108. self.init()
  109. self.primaryKey = account + ocIdServerUrl + userId
  110. self.account = account
  111. self.ocIdServerUrl = ocIdServerUrl
  112. self.userId = userId
  113. }
  114. }
  115. extension NCManageDatabase {
  116. // MARK: -
  117. // MARK: tableE2eEncryption
  118. func addE2eEncryption(_ object: tableE2eEncryption) {
  119. do {
  120. let realm = try Realm()
  121. try realm.write {
  122. realm.add(object, update: .all)
  123. }
  124. } catch let error {
  125. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  126. }
  127. }
  128. func deleteE2eEncryption(predicate: NSPredicate) {
  129. do {
  130. let realm = try Realm()
  131. try realm.write {
  132. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  133. realm.delete(results)
  134. }
  135. } catch let error {
  136. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  137. }
  138. }
  139. func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  140. do {
  141. let realm = try Realm()
  142. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else { return nil }
  143. return tableE2eEncryption.init(value: result)
  144. } catch let error as NSError {
  145. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  146. }
  147. return nil
  148. }
  149. func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption] {
  150. do {
  151. let realm = try Realm()
  152. let results: Results<tableE2eEncryption>
  153. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  154. return Array(results.map { tableE2eEncryption.init(value: $0) })
  155. } catch let error as NSError {
  156. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  157. }
  158. return []
  159. }
  160. func renameFileE2eEncryption(account: String, serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  161. do {
  162. let realm = try Realm()
  163. try realm.write {
  164. guard let result = realm.objects(tableE2eEncryption.self).filter("account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", account, serverUrl, fileNameIdentifier).first else { return }
  165. result.fileName = newFileName
  166. realm.add(result, update: .all)
  167. }
  168. } catch let error as NSError {
  169. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  170. }
  171. }
  172. // MARK: -
  173. // MARK: Table e2e Encryption Lock
  174. func getE2ETokenLock(account: String, serverUrl: String) -> tableE2eEncryptionLock? {
  175. do {
  176. let realm = try Realm()
  177. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else { return nil }
  178. return tableE2eEncryptionLock.init(value: result)
  179. } catch let error as NSError {
  180. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  181. }
  182. return nil
  183. }
  184. func getE2EAllTokenLock(account: String) -> [tableE2eEncryptionLock] {
  185. do {
  186. let realm = try Realm()
  187. let results = realm.objects(tableE2eEncryptionLock.self).filter("account == %@", account)
  188. if results.isEmpty {
  189. return []
  190. } else {
  191. return Array(results.map { tableE2eEncryptionLock.init(value: $0) })
  192. }
  193. } catch let error as NSError {
  194. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  195. }
  196. return []
  197. }
  198. func setE2ETokenLock(account: String, serverUrl: String, fileId: String, e2eToken: String) {
  199. do {
  200. let realm = try Realm()
  201. try realm.write {
  202. let object = tableE2eEncryptionLock()
  203. object.account = account
  204. object.fileId = fileId
  205. object.serverUrl = serverUrl
  206. object.e2eToken = e2eToken
  207. realm.add(object, update: .all)
  208. }
  209. } catch let error {
  210. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  211. }
  212. }
  213. func deleteE2ETokenLock(account: String, serverUrl: String) {
  214. do {
  215. let realm = try Realm()
  216. try realm.write {
  217. if let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first {
  218. realm.delete(result)
  219. }
  220. }
  221. } catch let error {
  222. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  223. }
  224. }
  225. // MARK: -
  226. // MARK: V1
  227. func getE2eMetadata(account: String, serverUrl: String) -> tableE2eMetadata12? {
  228. do {
  229. let realm = try Realm()
  230. guard let result = realm.objects(tableE2eMetadata12.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else { return nil }
  231. return tableE2eMetadata12.init(value: result)
  232. } catch let error as NSError {
  233. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  234. }
  235. return nil
  236. }
  237. func setE2eMetadata(account: String, serverUrl: String, metadataKey: String, version: Double) {
  238. do {
  239. let realm = try Realm()
  240. try realm.write {
  241. let object = tableE2eMetadata12()
  242. object.account = account
  243. object.metadataKey = metadataKey
  244. object.serverUrl = serverUrl
  245. object.version = version
  246. realm.add(object, update: .all)
  247. }
  248. } catch let error {
  249. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  250. }
  251. }
  252. // MARK: -
  253. // MARK: V2
  254. func addE2EUsers(account: String,
  255. serverUrl: String,
  256. ocIdServerUrl: String,
  257. userId: String,
  258. certificate: String,
  259. encryptedMetadataKey: String?,
  260. metadataKey: Data?) {
  261. do {
  262. let realm = try Realm()
  263. try realm.write {
  264. let object = tableE2eUsers.init(account: account, ocIdServerUrl: ocIdServerUrl, userId: userId)
  265. object.certificate = certificate
  266. object.encryptedMetadataKey = encryptedMetadataKey
  267. object.metadataKey = metadataKey
  268. object.serverUrl = serverUrl
  269. realm.add(object, update: .all)
  270. }
  271. } catch let error {
  272. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  273. }
  274. }
  275. func deleteE2EUsers(account: String, ocIdServerUrl: String, userId: String) {
  276. do {
  277. let realm = try Realm()
  278. try realm.write {
  279. if let result = realm.objects(tableE2eUsers.self).filter("account == %@ AND ocIdServerUrl == %@ AND userId == %@", account, ocIdServerUrl, userId).first {
  280. realm.delete(result)
  281. }
  282. }
  283. } catch let error {
  284. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  285. }
  286. }
  287. func getE2EUsers(account: String, ocIdServerUrl: String) -> Results<tableE2eUsers>? {
  288. do {
  289. let realm = try Realm()
  290. return realm.objects(tableE2eUsers.self).filter("account == %@ AND ocIdServerUrl == %@", account, ocIdServerUrl)
  291. } catch let error as NSError {
  292. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  293. }
  294. return nil
  295. }
  296. func getE2EUser(account: String, ocIdServerUrl: String, userId: String) -> tableE2eUsers? {
  297. do {
  298. let realm = try Realm()
  299. return realm.objects(tableE2eUsers.self).filter("account == %@ && ocIdServerUrl == %@ AND userId == %@", account, ocIdServerUrl, userId).first
  300. } catch let error as NSError {
  301. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  302. }
  303. return nil
  304. }
  305. func getE2eMetadata(account: String, ocIdServerUrl: String) -> tableE2eMetadata? {
  306. do {
  307. let realm = try Realm()
  308. return realm.objects(tableE2eMetadata.self).filter("account == %@ && ocIdServerUrl == %@", account, ocIdServerUrl).first
  309. } catch let error as NSError {
  310. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  311. }
  312. return nil
  313. }
  314. func addE2eMetadata(account: String, serverUrl: String, ocIdServerUrl: String, keyChecksums: [String]?, deleted: Bool, folders: [String: String]?, version: String) {
  315. do {
  316. let realm = try Realm()
  317. try realm.write {
  318. let object = tableE2eMetadata.init(account: account, ocIdServerUrl: ocIdServerUrl)
  319. if let keyChecksums {
  320. object.keyChecksums.append(objectsIn: keyChecksums)
  321. }
  322. object.deleted = deleted
  323. let foldersDictionary = object.folders
  324. if let folders {
  325. for folder in folders {
  326. foldersDictionary[folder.key] = folder.value
  327. }
  328. }
  329. object.serverUrl = serverUrl
  330. object.version = version
  331. realm.add(object, update: .all)
  332. }
  333. } catch let error {
  334. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  335. }
  336. }
  337. func updateCounterE2eMetadata(account: String, ocIdServerUrl: String, counter: Int) {
  338. do {
  339. let realm = try Realm()
  340. try realm.write {
  341. let object = tableE2eCounter.init(account: account, ocIdServerUrl: ocIdServerUrl, counter: counter)
  342. realm.add(object, update: .all)
  343. }
  344. } catch let error {
  345. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  346. }
  347. }
  348. func getCounterE2eMetadata(account: String, ocIdServerUrl: String) -> Int? {
  349. do {
  350. let realm = try Realm()
  351. return realm.objects(tableE2eCounter.self).filter("account == %@ && ocIdServerUrl == %@", account, ocIdServerUrl).first?.counter
  352. } catch let error as NSError {
  353. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  354. }
  355. return nil
  356. }
  357. }