CCCertificate.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //
  2. // CCCertificate.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 10/08/16.
  6. // Copyright (c) 2014 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 "CCCoreData.h"
  25. #import "CCCertificate.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. [CCUtility getDirectoryCerificates];
  62. if(trust != nil) {
  63. [self saveCertificate:trust withName:@"tmp.der"];
  64. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  65. NSMutableArray *listCertificateLocation = [CCCoreData getAllCertificatesLocation];
  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)presentViewControllerCertificateWithTitle:(NSString *)title viewController:(UIViewController *)viewController delegate:(id)delegate
  111. {
  112. if (![viewController isKindOfClass:[UIViewController class]])
  113. return;
  114. //viewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
  115. _delegate = delegate;
  116. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  117. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title 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([self.delegate respondsToSelector:@selector(trustedCerticateAccepted)])
  121. [self.delegate trustedCerticateAccepted];
  122. }]];
  123. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  124. if([self.delegate respondsToSelector:@selector(trustedCerticateDenied)])
  125. [self.delegate trustedCerticateDenied];
  126. }]];
  127. [viewController presentViewController:alertController animated:YES completion:nil];
  128. });
  129. }
  130. - (void)viewCertificate:(SecTrustRef)trust
  131. {
  132. SecCertificateRef currentServerCert = SecTrustGetLeafCertificate(trust);
  133. CFDataRef data = SecCertificateCopyData(currentServerCert);
  134. X509 *x509cert = NULL;
  135. if (data) {
  136. BIO *mem = BIO_new_mem_buf((void *)CFDataGetBytePtr(data), (int)CFDataGetLength(data));
  137. x509cert = d2i_X509_bio(mem, NULL);
  138. BIO_free(mem);
  139. CFRelease(data);
  140. if (!x509cert) {
  141. NSLog(@"[LOG] OpenSSL couldn't parse X509 Certificate");
  142. } else {
  143. NSString *issuer = CertificateGetIssuerName(x509cert);
  144. NSDate *expiryDate = CertificateGetExpiryDate(x509cert);
  145. NSLog(@"[LOG] %@ %@", issuer, expiryDate);
  146. }
  147. } else {
  148. NSLog(@"[LOG] Failed to retrieve DER data from Certificate Ref");
  149. }
  150. //Free
  151. X509_free(x509cert);
  152. }
  153. - (BOOL)acceptCertificate
  154. {
  155. NSString *localCertificatesFolder = [CCUtility getDirectoryCerificates];
  156. NSError *error;
  157. NSFileManager *fm = [[NSFileManager alloc] init];
  158. NSTimeInterval dateCertificate = [[NSDate date] timeIntervalSince1970];
  159. NSString *currentCertLocation = [NSString stringWithFormat:@"%@%f.der",localCertificatesFolder, dateCertificate];
  160. NSLog(@"[LOG] currentCertLocation: %@", currentCertLocation);
  161. if(![fm moveItemAtPath:[NSString stringWithFormat:@"%@%@",localCertificatesFolder, @"tmp.der"] toPath:currentCertLocation error:&error]) {
  162. NSLog(@"[LOG] Error: %@", [error localizedDescription]);
  163. return NO;
  164. } else {
  165. [CCCoreData addCertificate:[NSString stringWithFormat:@"%f.der", dateCertificate]];
  166. }
  167. return YES;
  168. }
  169. static NSString * CertificateGetIssuerName(X509 *certificateX509)
  170. {
  171. NSString *issuer = nil;
  172. if (certificateX509 != NULL) {
  173. X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
  174. if (issuerX509Name != NULL) {
  175. int nid = OBJ_txt2nid("O"); // organization
  176. int index = X509_NAME_get_index_by_NID(issuerX509Name, nid, -1);
  177. X509_NAME_ENTRY *issuerNameEntry = X509_NAME_get_entry(issuerX509Name, index);
  178. if (issuerNameEntry) {
  179. ASN1_STRING *issuerNameASN1 = X509_NAME_ENTRY_get_data(issuerNameEntry);
  180. if (issuerNameASN1 != NULL) {
  181. unsigned char *issuerName = ASN1_STRING_data(issuerNameASN1);
  182. issuer = [NSString stringWithUTF8String:(char *)issuerName];
  183. }
  184. }
  185. }
  186. }
  187. return issuer;
  188. }
  189. static NSDate *CertificateGetExpiryDate(X509 *certificateX509)
  190. {
  191. NSDate *expiryDate = nil;
  192. if (certificateX509 != NULL) {
  193. ASN1_TIME *certificateExpiryASN1 = X509_get_notAfter(certificateX509);
  194. if (certificateExpiryASN1 != NULL) {
  195. ASN1_GENERALIZEDTIME *certificateExpiryASN1Generalized = ASN1_TIME_to_generalizedtime(certificateExpiryASN1, NULL);
  196. if (certificateExpiryASN1Generalized != NULL) {
  197. unsigned char *certificateExpiryData = ASN1_STRING_data(certificateExpiryASN1Generalized);
  198. // ASN1 generalized times look like this: "20131114230046Z"
  199. // format: YYYYMMDDHHMMSS
  200. // indices: 01234567890123
  201. // 1111
  202. // There are other formats (e.g. specifying partial seconds or
  203. // time zones) but this is good enough for our purposes since
  204. // we only use the date and not the time.
  205. //
  206. // (Source: http://www.obj-sys.com/asn1tutorial/node14.html)
  207. NSString *expiryTimeStr = [NSString stringWithUTF8String:(char *)certificateExpiryData];
  208. NSDateComponents *expiryDateComponents = [[NSDateComponents alloc] init];
  209. expiryDateComponents.year = [[expiryTimeStr substringWithRange:NSMakeRange(0, 4)] intValue];
  210. expiryDateComponents.month = [[expiryTimeStr substringWithRange:NSMakeRange(4, 2)] intValue];
  211. expiryDateComponents.day = [[expiryTimeStr substringWithRange:NSMakeRange(6, 2)] intValue];
  212. expiryDateComponents.hour = [[expiryTimeStr substringWithRange:NSMakeRange(8, 2)] intValue];
  213. expiryDateComponents.minute = [[expiryTimeStr substringWithRange:NSMakeRange(10, 2)] intValue];
  214. expiryDateComponents.second = [[expiryTimeStr substringWithRange:NSMakeRange(12, 2)] intValue];
  215. NSCalendar *calendar = [NSCalendar currentCalendar];
  216. expiryDate = [calendar dateFromComponents:expiryDateComponents];
  217. }
  218. }
  219. }
  220. return expiryDate;
  221. }
  222. @end