2 * Copyright (c) 2018 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import <XCTest/XCTest.h>
25 #include "trust/trustd/trustd_spi.h"
26 #include "trust/trustd/SecRevocationDb.h"
27 #include <Security/SecCertificatePriv.h>
28 #include <Security/SecTrustPriv.h>
29 #include <Security/SecPolicy.h>
30 #include <Security/SecPolicyPriv.h>
31 #include <Security/SecTrustSettings.h>
32 #include <Security/SecTrustSettingsPriv.h>
33 #include "OSX/utilities/SecCFWrappers.h"
34 #include <dispatch/dispatch.h>
38 #include <Security/SecTrustStore.h>
40 #define kSystemLoginKeychainPath "/Library/Keychains/System.keychain"
41 #include <Security/SecKeychain.h>
44 #import "../TestMacroConversions.h"
45 #import "TrustEvaluationTestCase.h"
47 @implementation TrustEvaluationTestCase
49 static int current_dir = -1;
50 static char *home_var = NULL;
52 /* Build in trustd functionality to the tests */
54 /* Set up TMP directory for trustd's files */
57 NSString* pid = [NSString stringWithFormat: @"tst-%d", [[NSProcessInfo processInfo] processIdentifier]];
58 NSURL* tmpDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:pid];
61 if (current_dir == -1 && home_var == NULL) {
62 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:tmpDirURL
63 withIntermediateDirectories:NO
67 NSURL* libraryURL = [tmpDirURL URLByAppendingPathComponent:@"Library"];
68 NSURL* preferencesURL = [tmpDirURL URLByAppendingPathComponent:@"Preferences"];
70 ok = (ok && (current_dir = open(".", O_RDONLY) >= 0)
71 && (chdir([tmpDirURL fileSystemRepresentation]) >= 0)
72 && (setenv("HOME", [tmpDirURL fileSystemRepresentation], 1) >= 0)
73 && (bool)(home_var = getenv("HOME")));
75 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:libraryURL
76 withIntermediateDirectories:NO
80 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:preferencesURL
81 withIntermediateDirectories:NO
86 /* Use the production Valid DB by default (so we'll have data to test against) */
87 CFPreferencesSetAppValue(CFSTR("ValidUpdateServer"), kValidUpdateProdServer, kSecurityPreferencesDomain);
88 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
92 trustd_init((__bridge CFURLRef) tmpDirURL);
96 - (id)addTrustSettingsForCert:(SecCertificateRef)cert trustSettings:(id)trustSettings
99 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
100 OSStatus status = SecTrustStoreSetTrustSettings(defaultStore, cert, (__bridge CFTypeRef)trustSettings);
101 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", (int)status);
104 /* Since we're putting trust settings in the admin domain,
105 * we need to add the certs to the system keychain. */
106 SecKeychainRef kcRef = NULL;
107 CFArrayRef certRef = NULL;
108 NSDictionary *attrs = nil;
110 SecKeychainOpen(kSystemLoginKeychainPath, &kcRef);
115 /* Since we're interacting with the keychain we need a framework cert */
116 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
117 attrs = @{(__bridge NSString*)kSecValueRef: (__bridge id)frameworkCert,
118 (__bridge NSString*)kSecUseKeychain: (__bridge id)kcRef,
119 (__bridge NSString*)kSecReturnPersistentRef: @YES};
120 OSStatus status = SecItemAdd((CFDictionaryRef)attrs, (void *)&certRef);
121 XCTAssert(errSecSuccess == status, "failed to add cert to keychain: %d", status);
122 id result = ((__bridge NSArray*)certRef)[0];
123 CFReleaseNull(kcRef);
124 CFReleaseNull(certRef);
126 status = SecTrustSettingsSetTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin,
127 (__bridge CFTypeRef)trustSettings);
128 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", status);
131 CFReleaseNull(frameworkCert);
137 - (id)addTrustSettingsForCert:(SecCertificateRef)cert
139 NSDictionary *trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustRoot)};
140 Boolean isSelfSigned = false;
141 XCTAssert(errSecSuccess == SecCertificateIsSelfSigned(cert, &isSelfSigned));
143 trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustAsRoot)};
146 return [self addTrustSettingsForCert:cert trustSettings:trustSettings];
149 - (void)removeTrustSettingsForCert:(SecCertificateRef)cert persistentRef:(id)persistentRef
152 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
153 XCTAssert(errSecSuccess == SecTrustStoreRemoveCertificate(defaultStore, cert), "failed to remove trust settings");
155 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
156 XCTAssert(errSecSuccess == SecTrustSettingsRemoveTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin),
157 "failed to remove trust settings");
158 XCTAssert(errSecSuccess == SecItemDelete((CFDictionaryRef)@{ (__bridge NSString*)kSecValuePersistentRef: persistentRef}),
159 "failed to remove item from keychain");
160 CFReleaseNull(frameworkCert);
164 const CFStringRef kSecurityPreferencesDomain = CFSTR("com.apple.security");
165 const CFStringRef kTestSystemRootKey = CFSTR("TestSystemRoot");
167 - (void)setTestRootAsSystem:(const uint8_t *)sha256hash
169 NSData *rootHash = [NSData dataWithBytes:sha256hash length:32];
170 CFPreferencesSetAppValue(kTestSystemRootKey, (__bridge CFDataRef)rootHash, kSecurityPreferencesDomain);
171 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
174 - (void)removeTestRootAsSystem
176 CFPreferencesSetAppValue(kTestSystemRootKey, NULL, kSecurityPreferencesDomain);
177 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
180 - (id _Nullable) CF_RETURNS_RETAINED SecCertificateCreateFromResource:(NSString *)name
181 subdirectory:(NSString *)dir
183 NSURL *url = [[NSBundle bundleForClass:[self class]] URLForResource:name withExtension:@".cer"
186 url = [[NSBundle bundleForClass:[self class]] URLForResource:name withExtension:@".crt"
189 NSData *certData = [NSData dataWithContentsOfURL:url];
193 SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certData);
194 return (__bridge id)cert;
197 - (id _Nullable) CF_RETURNS_RETAINED SecCertificateCreateFromPEMResource:(NSString *)name
198 subdirectory:(NSString *)dir
200 NSURL *url = [[NSBundle bundleForClass:[self class]] URLForResource:name withExtension:@".pem"
202 NSData *certData = [NSData dataWithContentsOfURL:url];
207 SecCertificateRef cert = SecCertificateCreateWithPEM(kCFAllocatorDefault, (__bridge CFDataRef)certData);
208 return (__bridge id)cert;
211 /* MARK: run test methods from regressionBase */
212 - (void)runOneLeafTest:(SecPolicyRef)policy
213 anchors:(NSArray *)anchors
214 intermediates:(NSArray *)intermediates
215 leafPath:(NSString *)path
216 expectedResult:(bool)expectedResult
217 expectations:(NSObject *)expectations
218 verifyDate:(NSDate *)date
220 NSString* fileName = [path lastPathComponent];
221 NSString *reason = NULL;
222 SecTrustRef trustRef = NULL;
223 NSMutableArray* certArray = NULL;
224 SecCertificateRef certRef = NULL;
225 CFErrorRef error = NULL;
228 if ([expectations isKindOfClass: [NSString class]]) {
229 reason = (NSString *)expectations;
230 } else if ([expectations isKindOfClass: [NSDictionary class]]) {
231 NSDictionary *dict = (NSDictionary *)expectations;
232 NSObject *value = [dict valueForKey:@"valid"];
234 if ([value isKindOfClass: [NSNumber class]]) {
235 expectedResult = [(NSNumber *)value boolValue];
237 NSLog(@"Unexpected valid value %@ in dict for key %@", value, fileName);
240 value = [dict valueForKey:@"reason"];
242 if ([value isKindOfClass: [NSString class]]) {
243 reason = (NSString *)value;
245 NSLog(@"Unexpected reason value %@ in dict for key %@", value, fileName);
248 } else if ([expectations isKindOfClass: [NSNumber class]]) {
249 expectedResult = [(NSNumber *)expectations boolValue];
251 NSLog(@"Unexpected class %@ value %@ for key %@", [expectations class], expectations, fileName);
255 certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
258 fail("TODO test: %@ unable to create certificate, %@", fileName, reason);
260 fail("PARSE %@ unable to create certificate", fileName);
265 certArray = [NSMutableArray arrayWithArray:intermediates];
266 [certArray insertObject:(__bridge id)certRef atIndex:0]; //The certificate to be verified must be the first in the array.
269 err = SecTrustCreateWithCertificates((__bridge CFTypeRef _Nonnull)(certArray), policy, &trustRef);
271 ok_status(err, "SecTrustCreateWithCertificates");
275 SecTrustSetAnchorCertificates(trustRef, (CFArrayRef)anchors);
277 SecTrustSetVerifyDate(trustRef, (__bridge CFDateRef)date);
279 BOOL isValid = SecTrustEvaluateWithError(trustRef, &error);
281 XCTAssertFalse(isValid == expectedResult, "TODO test: %@%@", fileName, error);
283 ok(isValid == expectedResult, "%s %@%@", expectedResult ? "REGRESSION" : "SECURITY", fileName, error);
287 CFReleaseSafe(trustRef);
288 CFReleaseSafe(certRef);
289 CFReleaseSafe(error);
292 - (void)runCertificateTestFor:(SecPolicyRef)policy
293 anchors:(NSArray *)anchors
294 intermediates:(NSArray *)intermediates
295 leafPaths:(NSMutableArray *)leafPaths
296 expectations:(NSDictionary *)expect
297 verifyDate:(NSDate *)date
299 /* Sort the tests by name. */
300 [leafPaths sortUsingSelector:@selector(compare:)];
302 for (NSString* path in leafPaths) {
303 NSString* fileName = [path lastPathComponent];
304 [self runOneLeafTest:policy anchors:anchors intermediates:intermediates leafPath:path expectedResult:![fileName hasPrefix:@"Invalid"] expectations:[expect objectForKey:fileName] verifyDate:date];
309 - (void)runCertificateTestForDirectory:(SecPolicyRef)policy subDirectory:(NSString *)resourceSubDirectory verifyDate:(NSDate*)date
311 NSMutableArray* allRoots = [NSMutableArray array];
312 NSMutableArray* allCAs = [NSMutableArray array];
313 NSMutableArray* certTests = [NSMutableArray array];
314 NSDictionary* expect = NULL;
316 NSURL* filesDirectory = [[[NSBundle bundleForClass:[self class]] resourceURL] URLByAppendingPathComponent:resourceSubDirectory];
317 for (NSURL* fileURL in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:filesDirectory includingPropertiesForKeys:[NSArray array] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:nil]) {
318 NSString* path = [fileURL path];
319 if ([path hasSuffix:@"Cert.crt"]) {
320 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
321 [allCAs addObject:(__bridge id)certRef];
322 CFReleaseNull(certRef);
323 } else if ([path hasSuffix:@"RootCertificate.crt"]) {
324 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
325 [allRoots addObject:(__bridge id)certRef];
326 CFReleaseNull(certRef);
327 } else if ([path hasSuffix:@".crt"]) {
328 [certTests addObject:path];
329 } else if ([path hasSuffix:@".plist"]) {
331 fail("Multiple .plist files found in %@", filesDirectory);
333 expect = [NSDictionary dictionaryWithContentsOfFile:path];
338 [self runCertificateTestFor:policy anchors:allRoots intermediates:allCAs leafPaths:certTests expectations:expect verifyDate:date];
343 /* MARK: Framework type conversion functions */
345 typedef SecCertificateRef (*cert_create_f)(CFAllocatorRef allocator,
346 const UInt8 *der_bytes, CFIndex der_length);
347 CF_RETURNS_RETAINED _Nullable
348 SecCertificateRef SecFrameworkCertificateCreate(const uint8_t * _Nonnull der_bytes, CFIndex der_length) {
349 static cert_create_f FrameworkCertCreateFunctionPtr = NULL;
350 static dispatch_once_t onceToken;
352 dispatch_once(&onceToken, ^{
353 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
355 FrameworkCertCreateFunctionPtr = dlsym(framework, "SecCertificateCreateWithBytes");
359 if (FrameworkCertCreateFunctionPtr) {
360 return FrameworkCertCreateFunctionPtr(NULL, der_bytes, der_length);
362 NSLog(@"WARNING: not using Security framework certificate");
363 return SecCertificateCreateWithBytes(NULL, der_bytes, der_length);
367 SecCertificateRef SecFrameworkCertificateCreateFromTestCert(SecCertificateRef cert) {
368 return SecFrameworkCertificateCreate(SecCertificateGetBytePtr(cert), SecCertificateGetLength(cert));
371 typedef SecPolicyRef (*ssl_policy_create_f)(Boolean server, CFStringRef hostname);
372 SecPolicyRef SecFrameworkPolicyCreateSSL(Boolean server, CFStringRef __nullable hostname) {
373 static ssl_policy_create_f FrameworkPolicyCreateFunctionPtr = NULL;
374 static dispatch_once_t onceToken;
376 dispatch_once(&onceToken, ^{
377 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
379 FrameworkPolicyCreateFunctionPtr = dlsym(framework, "SecPolicyCreateSSL");
383 if (FrameworkPolicyCreateFunctionPtr) {
384 return FrameworkPolicyCreateFunctionPtr(server, hostname);
386 NSLog(@"WARNING: not using Security framework policy");
387 return SecPolicyCreateSSL(server, hostname);
391 typedef SecPolicyRef (*basic_policy_create_f)(void);
392 SecPolicyRef SecFrameworkPolicyCreateBasicX509(void) {
393 static basic_policy_create_f FrameworkPolicyCreateFunctionPtr = NULL;
394 static dispatch_once_t onceToken;
396 dispatch_once(&onceToken, ^{
397 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
399 FrameworkPolicyCreateFunctionPtr = dlsym(framework, "SecPolicyCreateBasicX509");
403 if (FrameworkPolicyCreateFunctionPtr) {
404 return FrameworkPolicyCreateFunctionPtr();
406 NSLog(@"WARNING: not using Security framework policy");
407 return SecPolicyCreateBasicX509();
411 typedef SecPolicyRef (*smime_policy_create_f)(CFIndex smimeUsage, CFStringRef email);
412 SecPolicyRef SecFrameworkPolicyCreateSMIME(CFIndex smimeUsage, CFStringRef email) {
413 static smime_policy_create_f FrameworkPolicyCreateFunctionPtr = NULL;
414 static dispatch_once_t onceToken;
416 dispatch_once(&onceToken, ^{
417 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
419 FrameworkPolicyCreateFunctionPtr = dlsym(framework, "SecPolicyCreateSMIME");
423 if (FrameworkPolicyCreateFunctionPtr) {
424 return FrameworkPolicyCreateFunctionPtr(smimeUsage, email);
426 NSLog(@"WARNING: not using Security framework policy");
427 return SecPolicyCreateSMIME(smimeUsage, email);