Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 168 lines (141 sloc) 5.843 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
//
// ConnectionViewController.m
// Connection
//
// Created by Rob Napier on 8/1/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ConnectionViewController.h"

CFAbsoluteTime SecCertificateNotValidBefore(SecCertificateRef certificate);
CFAbsoluteTime SecCertificateNotValidAfter(SecCertificateRef certificate);

@implementation ConnectionViewController
@synthesize connection=connection_;

- (void)didReceiveMemoryWarning
{
  [super didReceiveMemoryWarning];
  // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
  [super viewDidLoad];
  // IP Address for encrypted.google.com
// NSURL *url = [NSURL URLWithString:@"https://72.14.204.113"];
  NSURL *url = [NSURL URLWithString:@"https://encrypted.google.com"];

  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  self.connection = [NSURLConnection connectionWithRequest:request
                                                  delegate:self];
}

static OSStatus RNSecTrustEvaluateAsX509(SecTrustRef trust,
                                         SecTrustResultType *result
                                         )
{
  OSStatus status = errSecSuccess;

  SecPolicyRef policy = SecPolicyCreateBasicX509();
  SecTrustRef newTrust;
  CFIndex numberOfCerts = SecTrustGetCertificateCount(trust);
  CFMutableArrayRef certs;
  certs = CFArrayCreateMutable(NULL,
                               numberOfCerts,
                               &kCFTypeArrayCallBacks);
  for (NSUInteger index = 0; index < numberOfCerts; ++index) {
    SecCertificateRef cert;
    cert = SecTrustGetCertificateAtIndex(trust, index);
    CFArrayAppendValue(certs, cert);
  }

  status = SecTrustCreateWithCertificates(certs,
                                          policy,
                                          &newTrust);
  if (status == errSecSuccess) {
    status = SecTrustEvaluate(newTrust, result);
  }

  CFRelease(policy);
  CFRelease(newTrust);
  CFRelease(certs);
  
  return status;
}

- (void)connection:(NSURLConnection *)connection
  willSendRequestForAuthenticationChallenge:
  (NSURLAuthenticationChallenge *)challenge
{
  NSURLProtectionSpace *protSpace = challenge.protectionSpace;
  SecTrustRef trust = protSpace.serverTrust;
  SecTrustResultType result = kSecTrustResultFatalTrustFailure;
    
  OSStatus status = SecTrustEvaluate(trust, &result);
  if (status == errSecSuccess &&
      result == kSecTrustResultRecoverableTrustFailure) {
    SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust,
                                                           0);
    CFStringRef subject = SecCertificateCopySubjectSummary(cert);

    CFAbsoluteTime start = SecCertificateNotValidBefore(cert);
    CFAbsoluteTime end = SecCertificateNotValidAfter(cert);

    NSLog(@"Begin Date: %@", [NSDate dateWithTimeIntervalSinceReferenceDate:start]);
    NSLog(@"End Date: %@", [NSDate dateWithTimeIntervalSinceReferenceDate:end]);
    
    NSLog(@"Trying to access %@. Got %@.", protSpace.host,
          (__bridge id)subject);
    CFRange range = CFStringFind(subject, CFSTR(".google.com"),
                                 kCFCompareAnchored|
                                 kCFCompareBackwards);
    if (range.location != kCFNotFound) {
      status = RNSecTrustEvaluateAsX509(trust, &result);
    }
    CFRelease(subject);
  }
  

  if (status == errSecSuccess) {
    switch (result) {
      case kSecTrustResultInvalid:
      case kSecTrustResultDeny:
      case kSecTrustResultFatalTrustFailure:
      case kSecTrustResultOtherError:
// We've tried everything:
      case kSecTrustResultRecoverableTrustFailure:
        NSLog(@"Failing due to result: %lu", result);
        [challenge.sender cancelAuthenticationChallenge:challenge];
        break;
        
      case kSecTrustResultProceed:
      case kSecTrustResultConfirm:
      case kSecTrustResultUnspecified: {
        NSLog(@"Successing with result: %lu", result);
        NSURLCredential *cred;
        cred = [NSURLCredential credentialForTrust:trust];
        [challenge.sender useCredential:cred
             forAuthenticationChallenge:challenge];
        }
        break;
        
      default:
        NSAssert(NO, @"Unexpected result from trust evaluation:%d",
                 result);
        break;
    }
  }
  else {
    // Something was broken
    NSLog(@"Complete failure with code: %lu", status);
    [challenge.sender cancelAuthenticationChallenge:challenge];
  }
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error {
  NSLog(@"didFailWithError:%@", error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  NSLog(@"didFinishLoading");
  self.connection = nil;
}

//- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

//- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
//
//- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
//- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
//
//- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
//
//- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request;
//- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten
// totalBytesWritten:(NSInteger)totalBytesWritten
//totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;
//
//- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;
//
//- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

@end
Something went wrong with that request. Please try again.