NCEndToEndInitialize.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. //
  2. // NCEndToEndInitialize.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/04/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. @objc protocol NCEndToEndInitializeDelegate {
  26. func endToEndInitializeSuccess()
  27. }
  28. class NCEndToEndInitialize: NSObject {
  29. @objc weak var delegate: NCEndToEndInitializeDelegate?
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. var extractedPublicKey: String?
  32. override init() {
  33. }
  34. // --------------------------------------------------------------------------------------------
  35. // MARK: Initialize
  36. // --------------------------------------------------------------------------------------------
  37. @objc func initEndToEndEncryption() {
  38. // Clear all keys
  39. CCUtility.clearAllKeysEnd(toEnd: appDelegate.account)
  40. self.getPublicKey()
  41. }
  42. @objc func statusOfService(completion: @escaping (_ error: NKError?) -> Void) {
  43. NextcloudKit.shared.getE2EECertificate { _, _, _, _, error in
  44. completion(error)
  45. }
  46. }
  47. func getPublicKey() {
  48. NextcloudKit.shared.getE2EECertificate { account, certificate, _, _, error in
  49. if error == .success && account == self.appDelegate.account {
  50. CCUtility.setEndToEndCertificate(account, certificate: certificate)
  51. self.extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate)
  52. // Request PrivateKey chiper to Server
  53. self.getPrivateKeyCipher()
  54. } else if error != .success {
  55. switch error.errorCode {
  56. case NCGlobal.shared.errorBadRequest:
  57. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  58. NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  59. case NCGlobal.shared.errorResourceNotFound:
  60. guard let csr = NCEndToEndEncryption.sharedManager().createCSR(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData()) else {
  61. let error = NKError(errorCode: error.errorCode, errorDescription: "Error to create Csr")
  62. NCContentPresenter.shared.messageNotification("E2E Csr", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  63. return
  64. }
  65. NextcloudKit.shared.signE2EECertificate(certificate: csr) { account, certificate, data, error in
  66. if error == .success && account == self.appDelegate.account {
  67. // TEST publicKey
  68. let extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate)
  69. if extractedPublicKey != NCEndToEndEncryption.sharedManager().generatedPublicKey {
  70. let error = NKError(errorCode: error.errorCode, errorDescription: "error: the public key is incorrect")
  71. NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  72. } else {
  73. CCUtility.setEndToEndCertificate(account, certificate: certificate)
  74. // Request PrivateKey chiper to Server
  75. self.getPrivateKeyCipher()
  76. }
  77. } else if error != .success {
  78. switch error.errorCode {
  79. case NCGlobal.shared.errorBadRequest:
  80. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  81. NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  82. case NCGlobal.shared.errorConflict:
  83. let error = NKError(errorCode: error.errorCode, errorDescription: "conflict: a public key for the user already exists")
  84. NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  85. default:
  86. NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  87. }
  88. }
  89. }
  90. case NCGlobal.shared.errorConflict:
  91. let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the public keys")
  92. NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  93. default:
  94. NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  95. }
  96. }
  97. }
  98. }
  99. func getPrivateKeyCipher() {
  100. // Request PrivateKey chiper to Server
  101. NextcloudKit.shared.getE2EEPrivateKey { account, privateKeyChiper, data, error in
  102. if error == .success && account == self.appDelegate.account {
  103. // request Passphrase
  104. var passphraseTextField: UITextField?
  105. let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
  106. let ok = UIAlertAction(title: "OK", style: .default, handler: { _ -> Void in
  107. let passphrase = passphraseTextField?.text
  108. let publicKey = CCUtility.getEndToEndCertificate(self.appDelegate.account)
  109. if let privateKeyData = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(privateKeyChiper, passphrase: passphrase, publicKey: publicKey, iterationCount: 1024)),
  110. let keyData = Data(base64Encoded: privateKeyData) {
  111. let privateKey = String(data: keyData, encoding: .utf8)
  112. CCUtility.setEndToEndPrivateKey(self.appDelegate.account, privateKey: privateKey)
  113. } else {
  114. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "Serious internal error to decrypt Private Key")
  115. NCContentPresenter.shared.messageNotification("E2E decrypt privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  116. return
  117. }
  118. // Save to keychain
  119. CCUtility.setEndToEndPassphrase(self.appDelegate.account, passphrase: passphrase)
  120. // request server publicKey
  121. NextcloudKit.shared.getE2EEPublicKey { account, publicKey, data, error in
  122. if error == .success && account == self.appDelegate.account {
  123. CCUtility.setEndToEndPublicKey(account, publicKey: publicKey)
  124. // Clear Table
  125. NCManageDatabase.shared.clearTable(tableDirectory.self, account: account)
  126. NCManageDatabase.shared.clearTable(tableE2eEncryption.self, account: account)
  127. NCManageDatabase.shared.clearTable(tableE2eEncryptionLock.self, account: account)
  128. NCManageDatabase.shared.clearTable(tableE2eMetadata.self, account: account)
  129. NCManageDatabase.shared.clearTable(tableE2eMetadataV2.self, account: account)
  130. NCManageDatabase.shared.clearTable(tableE2eUsersV2.self, account: account)
  131. self.delegate?.endToEndInitializeSuccess()
  132. } else if error != .success {
  133. switch error.errorCode {
  134. case NCGlobal.shared.errorBadRequest:
  135. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  136. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  137. case NCGlobal.shared.errorResourceNotFound:
  138. let error = NKError(errorCode: error.errorCode, errorDescription: "Server publickey doesn't exists")
  139. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  140. case NCGlobal.shared.errorConflict:
  141. let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the Server publickey")
  142. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  143. default:
  144. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  145. }
  146. }
  147. }
  148. })
  149. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ -> Void in
  150. }
  151. alertController.addAction(ok)
  152. alertController.addAction(cancel)
  153. alertController.addTextField { textField -> Void in
  154. passphraseTextField = textField
  155. passphraseTextField?.placeholder = NSLocalizedString("_enter_passphrase_", comment: "")
  156. }
  157. self.appDelegate.window?.rootViewController?.present(alertController, animated: true)
  158. } else if error != .success {
  159. switch error.errorCode {
  160. case NCGlobal.shared.errorBadRequest:
  161. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  162. NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  163. case NCGlobal.shared.errorResourceNotFound:
  164. // message
  165. guard let e2ePassphrase = NYMnemonic.generateString(128, language: "english") else { return }
  166. let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase
  167. let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
  168. let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { _ in
  169. self.createNewE2EE(e2ePassphrase: e2ePassphrase, error: error, copyPassphrase: false)
  170. }
  171. let copyAction = UIAlertAction(title: NSLocalizedString("_ok_copy_passphrase_", comment: ""), style: .default) { _ in
  172. self.createNewE2EE(e2ePassphrase: e2ePassphrase, error: error, copyPassphrase: true)
  173. }
  174. alertController.addAction(OKAction)
  175. alertController.addAction(copyAction)
  176. self.appDelegate.window?.rootViewController?.present(alertController, animated: true)
  177. case NCGlobal.shared.errorConflict:
  178. let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the private key")
  179. NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  180. default:
  181. NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  182. }
  183. }
  184. }
  185. }
  186. func createNewE2EE(e2ePassphrase: String, error: NKError, copyPassphrase: Bool) {
  187. var privateKeyString: NSString?
  188. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData(), passphrase: e2ePassphrase, privateKey: &privateKeyString, iterationCount: 1024) else {
  189. let error = NKError(errorCode: error.errorCode, errorDescription: "Serious internal error to create PrivateKey chiper")
  190. NCContentPresenter.shared.messageNotification("E2E privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  191. return
  192. }
  193. // privateKeyChiper
  194. print(privateKeyChiper)
  195. NextcloudKit.shared.storeE2EEPrivateKey(privateKey: privateKeyChiper) { account, privateKey, data, error in
  196. if error == .success && account == self.appDelegate.account {
  197. CCUtility.setEndToEndPrivateKey(account, privateKey: privateKeyString! as String)
  198. CCUtility.setEndToEndPassphrase(account, passphrase: e2ePassphrase)
  199. // request server publicKey
  200. NextcloudKit.shared.getE2EEPublicKey { account, publicKey, data, error in
  201. if error == .success && account == self.appDelegate.account {
  202. CCUtility.setEndToEndPublicKey(account, publicKey: publicKey)
  203. // Clear Table
  204. NCManageDatabase.shared.clearTable(tableDirectory.self, account: account)
  205. NCManageDatabase.shared.clearTable(tableE2eEncryption.self, account: account)
  206. NCManageDatabase.shared.clearTable(tableE2eEncryptionLock.self, account: account)
  207. NCManageDatabase.shared.clearTable(tableE2eMetadata.self, account: account)
  208. NCManageDatabase.shared.clearTable(tableE2eMetadataV2.self, account: account)
  209. NCManageDatabase.shared.clearTable(tableE2eUsersV2.self, account: account)
  210. if copyPassphrase {
  211. UIPasteboard.general.string = e2ePassphrase
  212. }
  213. self.delegate?.endToEndInitializeSuccess()
  214. } else if error != .success {
  215. switch error.errorCode {
  216. case NCGlobal.shared.errorBadRequest:
  217. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  218. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  219. case NCGlobal.shared.errorResourceNotFound:
  220. let error = NKError(errorCode: error.errorCode, errorDescription: "Server publickey doesn't exists")
  221. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  222. case NCGlobal.shared.errorConflict:
  223. let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the Server publickey")
  224. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  225. default:
  226. NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  227. }
  228. }
  229. }
  230. } else if error != .success {
  231. switch error.errorCode {
  232. case NCGlobal.shared.errorBadRequest:
  233. let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
  234. NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  235. case NCGlobal.shared.errorConflict:
  236. let error = NKError(errorCode: error.errorCode, errorDescription: "conflict: a private key for the user already exists")
  237. NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  238. default:
  239. NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  240. }
  241. }
  242. }
  243. }
  244. }