NCEndToEndInitialize.swift 18 KB

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