CCCertificate.m 6.7 KB

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