CCCertificate.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //
  2. // CCCertificate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 10/08/16.
  6. // Copyright (c) 2017 TWS. 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. - (void)viewCertificate:(SecTrustRef)trust
  129. {
  130. SecCertificateRef currentServerCert = SecTrustGetLeafCertificate(trust);
  131. CFDataRef data = SecCertificateCopyData(currentServerCert);
  132. X509 *x509cert = NULL;
  133. if (data) {
  134. BIO *mem = BIO_new_mem_buf((void *)CFDataGetBytePtr(data), (int)CFDataGetLength(data));
  135. x509cert = d2i_X509_bio(mem, NULL);
  136. BIO_free(mem);
  137. CFRelease(data);
  138. if (!x509cert) {
  139. NSLog(@"[LOG] OpenSSL couldn't parse X509 Certificate");
  140. } else {
  141. NSString *issuer = CertificateGetIssuerName(x509cert);
  142. NSDate *expiryDate = CertificateGetExpiryDate(x509cert);
  143. NSLog(@"[LOG] %@ %@", issuer, expiryDate);
  144. }
  145. } else {
  146. NSLog(@"[LOG] Failed to retrieve DER data from Certificate Ref");
  147. }
  148. //Free
  149. X509_free(x509cert);
  150. }
  151. - (BOOL)acceptCertificate
  152. {
  153. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  154. NSError *error;
  155. NSFileManager *fm = [[NSFileManager alloc] init];
  156. NSTimeInterval dateCertificate = [[NSDate date] timeIntervalSince1970];
  157. NSString *currentCertLocation = [NSString stringWithFormat:@"%@%f.der",localCertificatesFolder, dateCertificate];
  158. NSLog(@"[LOG] currentCertLocation: %@", currentCertLocation);
  159. if(![fm moveItemAtPath:[NSString stringWithFormat:@"%@%@",localCertificatesFolder, @"tmp.der"] toPath:currentCertLocation error:&error]) {
  160. NSLog(@"[LOG] Error: %@", [error localizedDescription]);
  161. return NO;
  162. } else {
  163. [[NCManageDatabase sharedInstance] addCertificates:[NSString stringWithFormat:@"%f.der", dateCertificate]];
  164. }
  165. return YES;
  166. }
  167. static NSString * CertificateGetIssuerName(X509 *certificateX509)
  168. {
  169. NSString *issuer = nil;
  170. if (certificateX509 != NULL) {
  171. X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
  172. if (issuerX509Name != NULL) {
  173. int nid = OBJ_txt2nid("O"); // organization
  174. int index = X509_NAME_get_index_by_NID(issuerX509Name, nid, -1);
  175. X509_NAME_ENTRY *issuerNameEntry = X509_NAME_get_entry(issuerX509Name, index);
  176. if (issuerNameEntry) {
  177. ASN1_STRING *issuerNameASN1 = X509_NAME_ENTRY_get_data(issuerNameEntry);
  178. if (issuerNameASN1 != NULL) {
  179. const unsigned char *issuerName = ASN1_STRING_get0_data(issuerNameASN1);
  180. issuer = [NSString stringWithUTF8String:(char *)issuerName];
  181. }
  182. }
  183. }
  184. }
  185. return issuer;
  186. }
  187. static NSDate *CertificateGetExpiryDate(X509 *certificateX509)
  188. {
  189. NSDate *expiryDate = nil;
  190. if (certificateX509 != NULL) {
  191. ASN1_TIME *certificateExpiryASN1 = X509_getm_notAfter(certificateX509);
  192. if (certificateExpiryASN1 != NULL) {
  193. ASN1_GENERALIZEDTIME *certificateExpiryASN1Generalized = ASN1_TIME_to_generalizedtime(certificateExpiryASN1, NULL);
  194. if (certificateExpiryASN1Generalized != NULL) {
  195. const unsigned char *certificateExpiryData = ASN1_STRING_get0_data(certificateExpiryASN1Generalized);
  196. // ASN1 generalized times look like this: "20131114230046Z"
  197. // format: YYYYMMDDHHMMSS
  198. // indices: 01234567890123
  199. // 1111
  200. // There are other formats (e.g. specifying partial seconds or
  201. // time zones) but this is good enough for our purposes since
  202. // we only use the date and not the time.
  203. //
  204. // (Source: http://www.obj-sys.com/asn1tutorial/node14.html)
  205. NSString *expiryTimeStr = [NSString stringWithUTF8String:(char *)certificateExpiryData];
  206. NSDateComponents *expiryDateComponents = [[NSDateComponents alloc] init];
  207. expiryDateComponents.year = [[expiryTimeStr substringWithRange:NSMakeRange(0, 4)] intValue];
  208. expiryDateComponents.month = [[expiryTimeStr substringWithRange:NSMakeRange(4, 2)] intValue];
  209. expiryDateComponents.day = [[expiryTimeStr substringWithRange:NSMakeRange(6, 2)] intValue];
  210. expiryDateComponents.hour = [[expiryTimeStr substringWithRange:NSMakeRange(8, 2)] intValue];
  211. expiryDateComponents.minute = [[expiryTimeStr substringWithRange:NSMakeRange(10, 2)] intValue];
  212. expiryDateComponents.second = [[expiryTimeStr substringWithRange:NSMakeRange(12, 2)] intValue];
  213. NSCalendar *calendar = [NSCalendar currentCalendar];
  214. expiryDate = [calendar dateFromComponents:expiryDateComponents];
  215. }
  216. }
  217. }
  218. return expiryDate;
  219. }
  220. @end