NCEndToEndInitialize.swift 18 KB

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