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/SecTrustSettings.h>
31 #include <Security/SecTrustSettingsPriv.h>
32 #include "OSX/utilities/SecCFWrappers.h"
33 #include <dispatch/dispatch.h>
37 #include <Security/SecTrustStore.h>
39 #define kSystemLoginKeychainPath "/Library/Keychains/System.keychain"
40 #include <Security/SecKeychain.h>
43 #import "../TestMacroConversions.h"
44 #import "TrustEvaluationTestCase.h"
46 @implementation TrustEvaluationTestCase
48 static int current_dir = -1;
49 static char *home_var = NULL;
51 /* Build in trustd functionality to the tests */
53 /* Set up TMP directory for trustd's files */
56 NSString* pid = [NSString stringWithFormat: @"tst-%d", [[NSProcessInfo processInfo] processIdentifier]];
57 NSURL* tmpDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:pid];
60 if (current_dir == -1 && home_var == NULL) {
61 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:tmpDirURL
62 withIntermediateDirectories:NO
66 NSURL* libraryURL = [tmpDirURL URLByAppendingPathComponent:@"Library"];
67 NSURL* preferencesURL = [tmpDirURL URLByAppendingPathComponent:@"Preferences"];
69 ok = (ok && (current_dir = open(".", O_RDONLY) >= 0)
70 && (chdir([tmpDirURL fileSystemRepresentation]) >= 0)
71 && (setenv("HOME", [tmpDirURL fileSystemRepresentation], 1) >= 0)
72 && (bool)(home_var = getenv("HOME")));
74 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:libraryURL
75 withIntermediateDirectories:NO
79 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:preferencesURL
80 withIntermediateDirectories:NO
85 /* Use the production Valid DB by default (so we'll have data to test against) */
86 CFPreferencesSetAppValue(CFSTR("ValidUpdateServer"), kValidUpdateProdServer, kSecurityPreferencesDomain);
87 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
91 trustd_init((__bridge CFURLRef) tmpDirURL);
95 - (id)addTrustSettingsForCert:(SecCertificateRef)cert trustSettings:(id)trustSettings
98 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
99 OSStatus status = SecTrustStoreSetTrustSettings(defaultStore, cert, (__bridge CFTypeRef)trustSettings);
100 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", (int)status);
103 /* Since we're putting trust settings in the admin domain,
104 * we need to add the certs to the system keychain. */
105 SecKeychainRef kcRef = NULL;
106 CFArrayRef certRef = NULL;
107 NSDictionary *attrs = nil;
109 SecKeychainOpen(kSystemLoginKeychainPath, &kcRef);
114 /* Since we're interacting with the keychain we need a framework cert */
115 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
116 attrs = @{(__bridge NSString*)kSecValueRef: (__bridge id)frameworkCert,
117 (__bridge NSString*)kSecUseKeychain: (__bridge id)kcRef,
118 (__bridge NSString*)kSecReturnPersistentRef: @YES};
119 OSStatus status = SecItemAdd((CFDictionaryRef)attrs, (void *)&certRef);
120 XCTAssert(errSecSuccess == status, "failed to add cert to keychain: %d", status);
121 id result = ((__bridge NSArray*)certRef)[0];
122 CFReleaseNull(kcRef);
123 CFReleaseNull(certRef);
125 status = SecTrustSettingsSetTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin,
126 (__bridge CFTypeRef)trustSettings);
127 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", status);
130 CFReleaseNull(frameworkCert);
136 - (id)addTrustSettingsForCert:(SecCertificateRef)cert
138 NSDictionary *trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustRoot)};
139 Boolean isSelfSigned = false;
140 XCTAssert(errSecSuccess == SecCertificateIsSelfSigned(cert, &isSelfSigned));
142 trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustAsRoot)};
145 return [self addTrustSettingsForCert:cert trustSettings:trustSettings];
148 - (void)removeTrustSettingsForCert:(SecCertificateRef)cert persistentRef:(id)persistentRef
151 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
152 XCTAssert(errSecSuccess == SecTrustStoreRemoveCertificate(defaultStore, cert), "failed to remove trust settings");
154 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
155 XCTAssert(errSecSuccess == SecTrustSettingsRemoveTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin),
156 "failed to remove trust settings");
157 XCTAssert(errSecSuccess == SecItemDelete((CFDictionaryRef)@{ (__bridge NSString*)kSecValuePersistentRef: persistentRef}),
158 "failed to remove item from keychain");
159 CFReleaseNull(frameworkCert);
163 const CFStringRef kSecurityPreferencesDomain = CFSTR("com.apple.security");
164 const CFStringRef kTestSystemRootKey = CFSTR("TestSystemRoot");
166 - (void)setTestRootAsSystem:(const uint8_t *)sha256hash
168 NSData *rootHash = [NSData dataWithBytes:sha256hash length:32];
169 CFPreferencesSetAppValue(kTestSystemRootKey, (__bridge CFDataRef)rootHash, kSecurityPreferencesDomain);
170 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
173 - (void)removeTestRootAsSystem
175 CFPreferencesSetAppValue(kTestSystemRootKey, NULL, kSecurityPreferencesDomain);
176 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
179 - (id _Nullable) CF_RETURNS_RETAINED SecCertificateCreateFromResource:(NSString *)name
180 subdirectory:(NSString *)dir
182 NSURL *url = [[NSBundle bundleForClass:[self class]] URLForResource:name withExtension:@".cer"
184 NSData *certData = [NSData dataWithContentsOfURL:url];
185 SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certData);
186 return (__bridge id)cert;
189 /* MARK: run test methods from regressionBase */
190 - (void)runOneLeafTest:(SecPolicyRef)policy
191 anchors:(NSArray *)anchors
192 intermediates:(NSArray *)intermediates
193 leafPath:(NSString *)path
194 expectedResult:(bool)expectedResult
195 expectations:(NSObject *)expectations
196 verifyDate:(NSDate *)date
198 NSString* fileName = [path lastPathComponent];
199 NSString *reason = NULL;
200 SecTrustRef trustRef = NULL;
201 NSMutableArray* certArray = NULL;
202 SecCertificateRef certRef = NULL;
203 CFErrorRef error = NULL;
206 if ([expectations isKindOfClass: [NSString class]]) {
207 reason = (NSString *)expectations;
208 } else if ([expectations isKindOfClass: [NSDictionary class]]) {
209 NSDictionary *dict = (NSDictionary *)expectations;
210 NSObject *value = [dict valueForKey:@"valid"];
212 if ([value isKindOfClass: [NSNumber class]]) {
213 expectedResult = [(NSNumber *)value boolValue];
215 NSLog(@"Unexpected valid value %@ in dict for key %@", value, fileName);
218 value = [dict valueForKey:@"reason"];
220 if ([value isKindOfClass: [NSString class]]) {
221 reason = (NSString *)value;
223 NSLog(@"Unexpected reason value %@ in dict for key %@", value, fileName);
226 } else if ([expectations isKindOfClass: [NSNumber class]]) {
227 expectedResult = [(NSNumber *)expectations boolValue];
229 NSLog(@"Unexpected class %@ value %@ for key %@", [expectations class], expectations, fileName);
233 certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
236 fail("TODO test: %@ unable to create certificate, %@", fileName, reason);
238 fail("PARSE %@ unable to create certificate", fileName);
243 certArray = [NSMutableArray arrayWithArray:intermediates];
244 [certArray insertObject:(__bridge id)certRef atIndex:0]; //The certificate to be verified must be the first in the array.
247 err = SecTrustCreateWithCertificates((__bridge CFTypeRef _Nonnull)(certArray), policy, &trustRef);
249 ok_status(err, "SecTrustCreateWithCertificates");
253 SecTrustSetAnchorCertificates(trustRef, (CFArrayRef)anchors);
255 SecTrustSetVerifyDate(trustRef, (__bridge CFDateRef)date);
257 BOOL isValid = SecTrustEvaluateWithError(trustRef, &error);
259 XCTAssertFalse(isValid == expectedResult, "TODO test: %@%@", fileName, error);
261 ok(isValid == expectedResult, "%s %@%@", expectedResult ? "REGRESSION" : "SECURITY", fileName, error);
265 CFReleaseSafe(trustRef);
266 CFReleaseSafe(certRef);
267 CFReleaseSafe(error);
270 - (void)runCertificateTestFor:(SecPolicyRef)policy
271 anchors:(NSArray *)anchors
272 intermediates:(NSArray *)intermediates
273 leafPaths:(NSMutableArray *)leafPaths
274 expectations:(NSDictionary *)expect
275 verifyDate:(NSDate *)date
277 /* Sort the tests by name. */
278 [leafPaths sortUsingSelector:@selector(compare:)];
280 for (NSString* path in leafPaths) {
281 NSString* fileName = [path lastPathComponent];
282 [self runOneLeafTest:policy anchors:anchors intermediates:intermediates leafPath:path expectedResult:![fileName hasPrefix:@"Invalid"] expectations:[expect objectForKey:fileName] verifyDate:date];
287 - (void)runCertificateTestForDirectory:(SecPolicyRef)policy subDirectory:(NSString *)resourceSubDirectory verifyDate:(NSDate*)date
289 NSMutableArray* allRoots = [NSMutableArray array];
290 NSMutableArray* allCAs = [NSMutableArray array];
291 NSMutableArray* certTests = [NSMutableArray array];
292 NSDictionary* expect = NULL;
294 NSURL* filesDirectory = [[[NSBundle bundleForClass:[self class]] resourceURL] URLByAppendingPathComponent:resourceSubDirectory];
295 for (NSURL* fileURL in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:filesDirectory includingPropertiesForKeys:[NSArray array] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:nil]) {
296 NSString* path = [fileURL path];
297 if ([path hasSuffix:@"Cert.crt"]) {
298 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
299 [allCAs addObject:(__bridge id)certRef];
300 CFReleaseNull(certRef);
301 } else if ([path hasSuffix:@"RootCertificate.crt"]) {
302 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
303 [allRoots addObject:(__bridge id)certRef];
304 CFReleaseNull(certRef);
305 } else if ([path hasSuffix:@".crt"]) {
306 [certTests addObject:path];
307 } else if ([path hasSuffix:@".plist"]) {
309 fail("Multiple .plist files found in %@", filesDirectory);
311 expect = [NSDictionary dictionaryWithContentsOfFile:path];
316 [self runCertificateTestFor:policy anchors:allRoots intermediates:allCAs leafPaths:certTests expectations:expect verifyDate:date];
321 typedef SecCertificateRef (*create_f)(CFAllocatorRef allocator,
322 const UInt8 *der_bytes, CFIndex der_length);
323 CF_RETURNS_RETAINED _Nullable
324 SecCertificateRef SecFrameworkCertificateCreate(const uint8_t * _Nonnull der_bytes, CFIndex der_length) {
325 static create_f FrameworkCertCreateFunctionPtr = NULL;
326 static dispatch_once_t onceToken;
328 dispatch_once(&onceToken, ^{
329 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
331 FrameworkCertCreateFunctionPtr = dlsym(framework, "SecCertificateCreateWithBytes");
335 if (FrameworkCertCreateFunctionPtr) {
336 return FrameworkCertCreateFunctionPtr(NULL, der_bytes, der_length);
338 NSLog(@"WARNING: not using Security framework certificate");
339 return SecCertificateCreateWithBytes(NULL, der_bytes, der_length);
343 SecCertificateRef SecFrameworkCertificateCreateFromTestCert(SecCertificateRef cert) {
344 return SecFrameworkCertificateCreate(SecCertificateGetBytePtr(cert), SecCertificateGetLength(cert));