CCCertificate.m 11 KB

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