NCEndToEndMetadata.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. //
  2. // NCEndToEndMetadata.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 13/11/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 NCEndToEndMetadata : NSObject {
  25. struct e2eMetadata: Codable {
  26. struct metadataKeyCodable: Codable {
  27. let metadataKeys: [String: String]
  28. let version: Int
  29. }
  30. struct sharingCodable: Codable {
  31. let recipient: [String: String]
  32. }
  33. struct encryptedFileAttributes: Codable {
  34. let key: String
  35. let filename: String
  36. let mimetype: String
  37. let version: Int
  38. }
  39. struct filesCodable: Codable {
  40. let initializationVector: String
  41. let authenticationTag: String
  42. let metadataKey: Int // Number of metadataKey
  43. let encrypted: String // encryptedFileAttributes
  44. }
  45. let files: [String: filesCodable]
  46. let metadata: metadataKeyCodable
  47. let sharing: sharingCodable?
  48. }
  49. @objc static let sharedInstance: NCEndToEndMetadata = {
  50. let instance = NCEndToEndMetadata()
  51. return instance
  52. }()
  53. // --------------------------------------------------------------------------------------------
  54. // MARK: Encode / Decode JSON Metadata
  55. // --------------------------------------------------------------------------------------------
  56. @objc func encoderMetadata(_ recordsE2eEncryption: [tableE2eEncryption], privateKey: String, serverUrl: String, metadataKey: String) -> String? {
  57. let jsonEncoder = JSONEncoder.init()
  58. var files = [String: e2eMetadata.filesCodable]()
  59. var version = 1
  60. var keyGenerated = ""
  61. // Generate Key
  62. if (metadataKey == "") {
  63. keyGenerated = NCEndToEndEncryption.sharedManager().generateKey(16).base64EncodedString() // AES_KEY_128_LENGTH
  64. } else {
  65. keyGenerated = metadataKey
  66. }
  67. // Double Encode64 for Android compatibility OMG
  68. let key = (keyGenerated.data(using: .utf8)?.base64EncodedString())!
  69. guard let metadataKeyEncryptedData = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(key, publicKey: nil, privateKey: privateKey) else {
  70. return nil
  71. }
  72. let metadataKeyBase64 = metadataKeyEncryptedData.base64EncodedString()
  73. // Create "files"
  74. for recordE2eEncryption in recordsE2eEncryption {
  75. let encrypted = e2eMetadata.encryptedFileAttributes(key: recordE2eEncryption.key, filename: recordE2eEncryption.fileName, mimetype: recordE2eEncryption.mimeType, version: recordE2eEncryption.version)
  76. do {
  77. // Create "encrypted"
  78. let encryptedJsonData = try jsonEncoder.encode(encrypted)
  79. let encryptedJsonString = String(data: encryptedJsonData, encoding: .utf8)
  80. guard let encryptedEncryptedJson = NCEndToEndEncryption.sharedManager().encryptEncryptedJson(encryptedJsonString, key: keyGenerated) else {
  81. print("Serious internal error in encoding metadata")
  82. return nil
  83. }
  84. let e2eMetadataFilesKey = e2eMetadata.filesCodable(initializationVector: recordE2eEncryption.initializationVector, authenticationTag: recordE2eEncryption.authenticationTag, metadataKey: 0, encrypted: encryptedEncryptedJson)
  85. files.updateValue(e2eMetadataFilesKey, forKey: recordE2eEncryption.fileNameIdentifier)
  86. } catch let error {
  87. print("Serious internal error in encoding metadata ("+error.localizedDescription+")")
  88. return nil
  89. }
  90. version = recordE2eEncryption.version
  91. }
  92. // Create "metadataKey" with encrypted maetadatakey
  93. let e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: ["0":metadataKeyBase64], version: version)
  94. // Create final Json e2emetadata
  95. let e2emetadata = e2eMetadata(files: files, metadata: e2eMetadataKey, sharing: nil)
  96. do {
  97. // Write metadataKey on DB
  98. if NCManageDatabase.sharedInstance.setDirectoryE2EMetadataKey(serverUrl: serverUrl, metadataKey: keyGenerated) == false {
  99. return nil
  100. }
  101. let jsonData = try jsonEncoder.encode(e2emetadata)
  102. let jsonString = String(data: jsonData, encoding: .utf8)
  103. print("JSON String : " + jsonString!)
  104. return jsonString
  105. } catch let error {
  106. print("Serious internal error in encoding metadata ("+error.localizedDescription+")")
  107. return nil
  108. }
  109. }
  110. @objc func decoderMetadata(_ e2eMetaDataJSON: String, privateKey: String, serverUrl: String, account: String, url: String) -> Bool {
  111. let jsonDecoder = JSONDecoder.init()
  112. let data = e2eMetaDataJSON.data(using: .utf8)
  113. do {
  114. let decode = try jsonDecoder.decode(e2eMetadata.self, from: data!)
  115. let files = decode.files
  116. let metadata = decode.metadata
  117. //let sharing = decode.sharing ---> V 2.0
  118. var metadataKeysDictionary = [String:String]()
  119. for metadataKeyDictionaryEncrypted in metadata.metadataKeys {
  120. guard let metadataKeyEncryptedData : NSData = NSData(base64Encoded: metadataKeyDictionaryEncrypted.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
  121. return false
  122. }
  123. guard let metadataKeyBase64 = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(metadataKeyEncryptedData as Data!, privateKey: privateKey) else {
  124. return false
  125. }
  126. // Initialize a `Data` from a Base-64 encoded String
  127. let metadataKeyBase64Data = Data(base64Encoded: metadataKeyBase64, options: NSData.Base64DecodingOptions(rawValue: 0))!
  128. let metadataKey = String(data: metadataKeyBase64Data, encoding: .utf8)
  129. metadataKeysDictionary[metadataKeyDictionaryEncrypted.key] = metadataKey
  130. }
  131. for file in files {
  132. let fileNameIdentifier = file.key
  133. let filesCodable = file.value as e2eMetadata.filesCodable
  134. let encrypted = filesCodable.encrypted
  135. let key = metadataKeysDictionary["\(filesCodable.metadataKey)"]
  136. guard let encryptedFileAttributesJson = NCEndToEndEncryption.sharedManager().decryptEncryptedJson(encrypted, key: key) else {
  137. return false
  138. }
  139. do {
  140. let encryptedFileAttributes = try jsonDecoder.decode(e2eMetadata.encryptedFileAttributes.self, from: encryptedFileAttributesJson.data(using: .utf8)!)
  141. let object = tableE2eEncryption()
  142. object.account = account
  143. object.authenticationTag = filesCodable.authenticationTag
  144. object.fileName = encryptedFileAttributes.filename
  145. object.fileNameIdentifier = fileNameIdentifier
  146. object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: encryptedFileAttributes.filename, serverUrl: serverUrl, activeUrl: url)
  147. object.key = encryptedFileAttributes.key
  148. object.initializationVector = filesCodable.initializationVector
  149. object.mimeType = encryptedFileAttributes.mimetype
  150. object.serverUrl = serverUrl
  151. object.version = encryptedFileAttributes.version
  152. // Write file parameter for decrypted on DB
  153. if NCManageDatabase.sharedInstance.addE2eEncryption(object) == false {
  154. return false
  155. }
  156. // Write metadataKey on DB
  157. if NCManageDatabase.sharedInstance.setDirectoryE2EMetadataKey(serverUrl: serverUrl, metadataKey: key!) == false {
  158. return false
  159. }
  160. } catch let error {
  161. print("Serious internal error in decoding metadata ("+error.localizedDescription+")")
  162. return false
  163. }
  164. }
  165. } catch let error {
  166. print("Serious internal error in decoding metadata ("+error.localizedDescription+")")
  167. return false
  168. }
  169. return true
  170. }
  171. }