CCCertificate.m 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. //
  2. // CCCertificate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 10/08/16.
  6. // Copyright (c) 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 "CCUtility.h"
  24. #import "CCCertificate.h"
  25. #import "NCBridgeSwift.h"
  26. #import "AppDelegate.h"
  27. #import <openssl/x509.h>
  28. #import <openssl/bio.h>
  29. #import <openssl/err.h>
  30. #import <openssl/pem.h>
  31. @implementation CCCertificate
  32. //Singleton
  33. + (id)sharedManager {
  34. static CCCertificate *CCCertificate = nil;
  35. static dispatch_once_t onceToken;
  36. dispatch_once(&onceToken, ^{
  37. CCCertificate = [[self alloc] init];
  38. });
  39. return CCCertificate;
  40. }
  41. static SecCertificateRef SecTrustGetLeafCertificate(SecTrustRef trust)
  42. // Returns the leaf certificate from a SecTrust object (that is always the
  43. // certificate at index 0).
  44. {
  45. SecCertificateRef result;
  46. assert(trust != NULL);
  47. if (SecTrustGetCertificateCount(trust) > 0) {
  48. result = SecTrustGetCertificateAtIndex(trust, 0);
  49. assert(result != NULL);
  50. } else {
  51. result = NULL;
  52. }
  53. return result;
  54. }
  55. - (BOOL)checkTrustedChallenge:(NSURLAuthenticationChallenge *)challenge
  56. {
  57. BOOL trusted = NO;
  58. SecTrustRef trust;
  59. NSURLProtectionSpace *protectionSpace;
  60. protectionSpace = [challenge protectionSpace];
  61. trust = [protectionSpace serverTrust];
  62. if(trust != nil) {
  63. [self saveCertificate:trust withName:@"tmp.der"];
  64. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  65. NSArray *listCertificateLocation = [[NCManageDatabase sharedInstance] getCertificatesLocation:[CCUtility getDirectoryCerificates]];
  66. for (int i = 0 ; i < [listCertificateLocation count] ; i++) {
  67. NSString *currentLocalCertLocation = [listCertificateLocation objectAtIndex:i];
  68. NSFileManager *fileManager = [ NSFileManager defaultManager];
  69. if([fileManager contentsEqualAtPath:[NSString stringWithFormat:@"%@/%@",localCertificatesFolder,@"tmp.der"] andPath:[NSString stringWithFormat:@"%@",currentLocalCertLocation]]) {
  70. NSLog(@"[LOG] Is the same certificate!!!");
  71. trusted = YES;
  72. }
  73. }
  74. } else
  75. trusted = NO;
  76. return trusted;
  77. }
  78. - (void)saveCertificate:(SecTrustRef)trust withName:(NSString *)certName
  79. {
  80. SecCertificateRef currentServerCert = SecTrustGetLeafCertificate(trust);
  81. CFDataRef data = SecCertificateCopyData(currentServerCert);
  82. X509 *x509cert = NULL;
  83. if (data) {
  84. BIO *mem = BIO_new_mem_buf((void *)CFDataGetBytePtr(data), (int)CFDataGetLength(data));
  85. x509cert = d2i_X509_bio(mem, NULL);
  86. BIO_free(mem);
  87. CFRelease(data);
  88. if (!x509cert) {
  89. NSLog(@"[LOG] OpenSSL couldn't parse X509 Certificate");
  90. } else {
  91. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  92. certName = [NSString stringWithFormat:@"%@/%@",localCertificatesFolder,certName];
  93. if ([[NSFileManager defaultManager] fileExistsAtPath:certName]) {
  94. NSError *error;
  95. [[NSFileManager defaultManager] removeItemAtPath:certName error:&error];
  96. }
  97. FILE *file;
  98. file = fopen([certName UTF8String], "w");
  99. if (file) {
  100. PEM_write_X509(file, x509cert);
  101. }
  102. fclose(file);
  103. }
  104. } else {
  105. NSLog(@"[LOG] Failed to retrieve DER data from Certificate Ref");
  106. }
  107. //Free
  108. X509_free(x509cert);
  109. }
  110. - (void)presentViewControllerCertificateWithAccount:(NSString *)account viewController:(UIViewController *)viewController delegate:(id)delegate
  111. {
  112. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  113. _delegate = delegate;
  114. if (![viewController isKindOfClass:[UIViewController class]])
  115. return;
  116. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  117. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  118. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  119. [[CCCertificate sharedManager] acceptCertificate];
  120. if (account != nil) [CCUtility setCertificateError:account error:NO];
  121. [appDelegate startTimerErrorNetworking];
  122. if([self.delegate respondsToSelector:@selector(trustedCerticateAccepted)])
  123. [self.delegate trustedCerticateAccepted];
  124. }]];
  125. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  126. [appDelegate startTimerErrorNetworking];
  127. if([self.delegate respondsToSelector:@selector(trustedCerticateDenied)])
  128. [self.delegate trustedCerticateDenied];
  129. }]];
  130. [viewController presentViewController:alertController animated:YES completion:^{
  131. // Stop timer error network
  132. [appDelegate.timerErrorNetworking invalidate];
  133. }];
  134. });
  135. }
  136. - (BOOL)acceptCertificate
  137. {
  138. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  139. NSError *error;
  140. NSFileManager *fm = [[NSFileManager alloc] init];
  141. NSTimeInterval dateCertificate = [[NSDate date] timeIntervalSince1970];
  142. NSString *currentCertLocation = [NSString stringWithFormat:@"%@/%f.der",localCertificatesFolder, dateCertificate];
  143. NSLog(@"[LOG] currentCertLocation: %@", currentCertLocation);
  144. if(![fm moveItemAtPath:[NSString stringWithFormat:@"%@/%@",localCertificatesFolder, @"tmp.der"] toPath:currentCertLocation error:&error]) {
  145. NSLog(@"[LOG] Error: %@", [error localizedDescription]);
  146. return NO;
  147. } else {
  148. [[NCManageDatabase sharedInstance] addCertificates:[NSString stringWithFormat:@"%f.der", dateCertificate]];
  149. }
  150. return YES;
  151. }
  152. @end