NCManageEndToEndEncryption.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. //
  2. // NCManageEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 13/10/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 "NCManageEndToEndEncryption.h"
  24. #import "NSNotificationCenter+MainThread.h"
  25. #import <LocalAuthentication/LocalAuthentication.h>
  26. #import <TOPasscodeViewController/TOPasscodeViewController.h>
  27. #import "NCBridgeSwift.h"
  28. #import "CCUtility.h"
  29. @interface NCManageEndToEndEncryption () <NCEndToEndInitializeDelegate, TOPasscodeViewControllerDelegate>
  30. {
  31. AppDelegate *appDelegate;
  32. NSString *passcodeType;
  33. TOPasscodeViewController *passcodeViewController;
  34. }
  35. @end
  36. @implementation NCManageEndToEndEncryption
  37. - (void)initializeForm:(NKError *)error
  38. {
  39. XLFormDescriptor *form = [XLFormDescriptor formDescriptor];
  40. XLFormSectionDescriptor *section;
  41. XLFormRowDescriptor *row;
  42. BOOL isE2EEEnabled = [[NCManageDatabase shared] getCapabilitiesServerBoolWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesE2EEEnabled exists:false];
  43. NSString *versionE2EE = [[NCManageDatabase shared] getCapabilitiesServerStringWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesE2EEApiVersion];
  44. if (![versionE2EE isEqual:[[NCGlobal shared] e2eeVersion]] && isE2EEEnabled) {
  45. NKError *error = [[NKError alloc] initWithErrorCode:NCGlobal.shared.errorInternalError errorDescription:@"_err_e2ee_app_version_"];
  46. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" error:error delay:[[NCGlobal shared] dismissAfterSecond] type:messageTypeError];
  47. }
  48. if ([CCUtility isEndToEndEnabled:appDelegate.account]) {
  49. // Section SERVICE ACTIVATED -------------------------------------------------
  50. section = [XLFormSectionDescriptor formSection];
  51. section.footerTitle = [NSString stringWithFormat:@"End-to-End Encryption %@", versionE2EE];
  52. [form addFormSection:section];
  53. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"serviceActivated" rowType:XLFormRowDescriptorTypeInfo title:NSLocalizedString(@"_e2e_settings_activated_", nil)];
  54. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  55. [row.cellConfig setObject:[[UIImage imageNamed:@"checkmark.circle.fill"] imageWithColor:[UIColor greenColor] size:25] forKey:@"imageView.image"];
  56. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  57. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  58. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  59. [section addFormRow:row];
  60. // Section PASSPHRASE -------------------------------------------------
  61. section = [XLFormSectionDescriptor formSection];
  62. [form addFormSection:section];
  63. // Read Passphrase
  64. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"readPassphrase" rowType:XLFormRowDescriptorTypeButton title:NSLocalizedString(@"_e2e_settings_read_passphrase_", nil)];
  65. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  66. [row.cellConfig setObject:[[UIImage imageNamed:@"e2eReadPassphrase"] imageWithColor:NCBrandColor.shared.gray size:25] forKey:@"imageView.image"];
  67. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  68. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  69. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  70. row.action.formSelector = @selector(readPassphrase:);
  71. [section addFormRow:row];
  72. // Section DELETE -------------------------------------------------
  73. section = [XLFormSectionDescriptor formSection];
  74. [form addFormSection:section];
  75. // remove locally Encryption
  76. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"removeLocallyEncryption" rowType:XLFormRowDescriptorTypeButton title:NSLocalizedString(@"_e2e_settings_remove_", nil)];
  77. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  78. [row.cellConfig setObject:[[UIImage imageNamed:@"lock"] imageWithColor:NCBrandColor.shared.gray size:25] forKey:@"imageView.image"];
  79. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  80. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  81. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  82. row.action.formSelector = @selector(removeLocallyEncryption:);
  83. [section addFormRow:row];
  84. } else {
  85. // Section START E2E -------------------------------------------------
  86. section = [XLFormSectionDescriptor formSection];
  87. if (error == nil) {
  88. section.footerTitle = NSLocalizedString(@"_status_in_progress_", nil);
  89. } else if (error.errorCode == 0) {
  90. section.footerTitle = NSLocalizedString(@"_status_e2ee_on_server_", nil);
  91. } else {
  92. section.footerTitle = NSLocalizedString(@"_status_e2ee_not_setup_", nil);
  93. }
  94. [form addFormSection:section];
  95. // Start e2e
  96. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"startE2E" rowType:XLFormRowDescriptorTypeButton title:NSLocalizedString(@"_e2e_settings_start_", nil)];
  97. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  98. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  99. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  100. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  101. row.action.formSelector = @selector(startE2E:);
  102. [section addFormRow:row];
  103. }
  104. #ifdef DEBUG
  105. // Section DELETE KEYS -------------------------------------------------
  106. section = [XLFormSectionDescriptor formSectionWithTitle:NSLocalizedString(@"Delete server keys ", nil)];
  107. [form addFormSection:section];
  108. // Delete publicKey
  109. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"deleteCertificate" rowType:XLFormRowDescriptorTypeButton title:NSLocalizedString(@"Delete certificate", nil)];
  110. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  111. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  112. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  113. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  114. row.action.formSelector = @selector(deleteCertificate:);
  115. [section addFormRow:row];
  116. // Delete privateKey
  117. row = [XLFormRowDescriptor formRowDescriptorWithTag:@"deletePrivateKey" rowType:XLFormRowDescriptorTypeButton title:NSLocalizedString(@"Delete PrivateKey", nil)];
  118. row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor;
  119. [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"];
  120. [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"];
  121. [row.cellConfig setObject:@(NSTextAlignmentLeft) forKey:@"textLabel.textAlignment"];
  122. row.action.formSelector = @selector(deletePrivateKey:);
  123. [section addFormRow:row];
  124. #endif
  125. self.tableView.showsVerticalScrollIndicator = NO;
  126. self.form = form;
  127. }
  128. // MARK: - View Life Cycle
  129. - (void)viewDidLoad
  130. {
  131. [super viewDidLoad];
  132. self.title = NSLocalizedString(@"_e2e_settings_", nil);
  133. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  134. self.view.backgroundColor = UIColor.systemGroupedBackgroundColor;
  135. self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;
  136. // E2EE
  137. self.endToEndInitialize = [NCEndToEndInitialize new];
  138. self.endToEndInitialize.delegate = self;
  139. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:NCGlobal.shared.notificationCenterApplicationDidEnterBackground object:nil];
  140. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initialize) name:NCGlobal.shared.notificationCenterInitialize object:nil];
  141. [self initializeForm:nil];
  142. /*
  143. NKRequestOptions *options = [[NKRequestOptions alloc] initWithEndpoint:nil customHeader:nil customUserAgent:nil contentType:nil e2eToken: nil timeout:30 queue:dispatch_get_main_queue()];
  144. [[NextcloudKit shared] getE2EECertificateWithOptions:options completionHandler:^(NSString* account, NSString *certificate, NSData *data, NKError *error) {
  145. }];
  146. */
  147. }
  148. - (void)viewWillAppear:(BOOL)animated
  149. {
  150. [super viewWillAppear:animated];
  151. appDelegate.activeViewController = self;
  152. [[NCEndToEndInitialize alloc] statusOfServiceWithCompletion:^(NKError * error) {
  153. [self initializeForm:error];
  154. }];
  155. }
  156. #pragma mark - NotificationCenter
  157. - (void)applicationDidEnterBackground
  158. {
  159. if (passcodeViewController.view.window != nil) {
  160. [passcodeViewController dismissViewControllerAnimated:true completion:nil];
  161. }
  162. }
  163. - (void)initialize
  164. {
  165. [[self navigationController] popViewControllerAnimated:YES];
  166. }
  167. #pragma mark - Action
  168. - (void)startE2E:(XLFormRowDescriptor *)sender
  169. {
  170. [self deselectFormRow:sender];
  171. if ([[CCUtility getPasscode] length]) {
  172. [self passcodeType:@"startE2E"];
  173. } else {
  174. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:NSLocalizedString(@"_e2e_settings_lock_not_active_", nil) preferredStyle:UIAlertControllerStyleAlert];
  175. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK action") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  176. }];
  177. [alertController addAction:okAction];
  178. [self presentViewController:alertController animated:YES completion:nil];
  179. }
  180. }
  181. - (void)readPassphrase:(XLFormRowDescriptor *)sender
  182. {
  183. [self deselectFormRow:sender];
  184. if ([[CCUtility getPasscode] length]) {
  185. [self passcodeType:@"readPassphrase"];
  186. } else {
  187. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:NSLocalizedString(@"_e2e_settings_lock_not_active_", nil) preferredStyle:UIAlertControllerStyleAlert];
  188. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK action") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  189. }];
  190. [alertController addAction:okAction];
  191. [self presentViewController:alertController animated:YES completion:nil];
  192. }
  193. }
  194. - (void)removeLocallyEncryption:(XLFormRowDescriptor *)sender
  195. {
  196. [self deselectFormRow:sender];
  197. if ([[CCUtility getPasscode] length]) {
  198. [self passcodeType:@"removeLocallyEncryption"];
  199. } else {
  200. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:NSLocalizedString(@"_e2e_settings_lock_not_active_", nil) preferredStyle:UIAlertControllerStyleAlert];
  201. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK action") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  202. }];
  203. [alertController addAction:okAction];
  204. [self presentViewController:alertController animated:YES completion:nil];
  205. }
  206. }
  207. #pragma mark - Passcode -
  208. - (void)passcodeType:(NSString *)type
  209. {
  210. LAContext *laContext = [LAContext new];
  211. NSError *error;
  212. if ([[CCUtility getPasscode] length] > 0) {
  213. passcodeViewController = [[TOPasscodeViewController alloc] initPasscodeType:TOPasscodeTypeSixDigits allowCancel:true];
  214. passcodeViewController.delegate = self;
  215. passcodeViewController.keypadButtonShowLettering = false;
  216. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  217. if (error == NULL) {
  218. if (laContext.biometryType == LABiometryTypeFaceID) {
  219. passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  220. passcodeViewController.allowBiometricValidation = true;
  221. passcodeViewController.automaticallyPromptForBiometricValidation = true;
  222. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  223. passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  224. passcodeViewController.allowBiometricValidation = true;
  225. passcodeViewController.automaticallyPromptForBiometricValidation = true;
  226. } else {
  227. NSLog(@"No Biometric support");
  228. }
  229. }
  230. }
  231. // Type of passcode
  232. passcodeType = type;
  233. [self presentViewController:passcodeViewController animated:YES completion:nil];
  234. }
  235. }
  236. - (void)didTapCancelInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  237. {
  238. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  239. }
  240. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  241. {
  242. if ([code isEqualToString:[CCUtility getPasscode]]) {
  243. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  244. [self passcodeCorrectCode];
  245. });
  246. return YES;
  247. }
  248. return NO;
  249. }
  250. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  251. {
  252. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions shared] brand] reply:^(BOOL success, NSError * _Nullable error) {
  253. if (success) {
  254. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  255. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  256. [self passcodeCorrectCode];
  257. });
  258. }
  259. }];
  260. }
  261. -(void)passcodeCorrectCode {
  262. if ([passcodeType isEqualToString:@"startE2E"]) {
  263. [self.endToEndInitialize initEndToEndEncryption];
  264. } else if ([passcodeType isEqualToString:@"readPassphrase"]) {
  265. NSString *e2ePassphrase = [CCUtility getEndToEndPassphrase:appDelegate.account];
  266. NSLog(@"[LOG] Passphrase: %@", e2ePassphrase);
  267. NSString *message = [NSString stringWithFormat:@"\n%@\n\n\n%@", NSLocalizedString(@"_e2e_settings_the_passphrase_is_", nil), e2ePassphrase];
  268. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  269. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { }];
  270. UIAlertAction *copyPassphrase = [UIAlertAction actionWithTitle:NSLocalizedString(@"_copy_passphrase_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  271. UIPasteboard.generalPasteboard.string = e2ePassphrase;
  272. }];
  273. [alertController addAction:okAction];
  274. [alertController addAction:copyPassphrase];
  275. [self presentViewController:alertController animated:YES completion:nil];
  276. } else if ([passcodeType isEqualToString:@"removeLocallyEncryption"]) {
  277. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_e2e_settings_remove_", nil) message:NSLocalizedString(@"_e2e_settings_remove_message_", nil) preferredStyle:UIAlertControllerStyleAlert];
  278. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  279. [CCUtility clearAllKeysEndToEnd:appDelegate.account];
  280. [self initializeForm:nil];
  281. }];
  282. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
  283. [alertController addAction:okAction];
  284. [alertController addAction:cancelAction];
  285. [self presentViewController:alertController animated:YES completion:nil];
  286. }
  287. }
  288. - (void)deleteCertificate:(XLFormRowDescriptor *)sender
  289. {
  290. [self deselectFormRow:sender];
  291. NKRequestOptions *options = [[NKRequestOptions alloc] initWithEndpoint:nil customHeader:nil customUserAgent:nil contentType:nil e2eToken: nil timeout:60 queue:dispatch_get_main_queue()];
  292. [[NextcloudKit shared] deleteE2EECertificateWithOptions:options completionHandler:^(NSString *account, NKError *error) {
  293. if (error == NKError.success && [account isEqualToString:appDelegate.account]) {
  294. NKError *error = [[NKError alloc] initWithErrorCode:NCGlobal.shared.errorInternalError errorDescription:@"Success"];
  295. [[NCContentPresenter shared] messageNotification:@"E2E delete certificate" error:error delay:[[NCGlobal shared] dismissAfterSecond] type:messageTypeSuccess];
  296. } else {
  297. [[NCContentPresenter shared] messageNotification:@"E2E delete certificate" error:error delay:[[NCGlobal shared] dismissAfterSecond] type:messageTypeError];
  298. }
  299. }];
  300. }
  301. - (void)deletePrivateKey:(XLFormRowDescriptor *)sender
  302. {
  303. [self deselectFormRow:sender];
  304. NKRequestOptions *options = [[NKRequestOptions alloc] initWithEndpoint:nil customHeader:nil customUserAgent:nil contentType:nil e2eToken: nil timeout:60 queue:dispatch_get_main_queue()];
  305. [[NextcloudKit shared] deleteE2EEPrivateKeyWithOptions: options completionHandler:^(NSString *account, NKError *error) {
  306. if (error == NKError.success && [account isEqualToString:appDelegate.account]) {
  307. NKError *error = [[NKError alloc] initWithErrorCode:NCGlobal.shared.errorInternalError errorDescription:@"Success"];
  308. [[NCContentPresenter shared] messageNotification:@"E2E delete privateKey" error:error delay:[[NCGlobal shared] dismissAfterSecond] type:messageTypeSuccess];
  309. } else {
  310. [[NCContentPresenter shared] messageNotification:@"E2E delete privateKey" error:error delay:[[NCGlobal shared] dismissAfterSecond] type:messageTypeError];
  311. }
  312. }];
  313. }
  314. #pragma mark - Delegate
  315. - (void)endToEndInitializeSuccess
  316. {
  317. // Reload All Datasource
  318. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterReloadDataSource object:nil];
  319. [self initializeForm:nil];
  320. }
  321. #pragma mark -
  322. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  323. return NCGlobal.shared.heightCellSettings;
  324. }
  325. @end