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];
188 SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certData);
189 return (__bridge id)cert;
192 - (id _Nullable) CF_RETURNS_RETAINED SecCertificateCreateFromPEMResource:(NSString *)name
193 subdirectory:(NSString *)dir
195 NSURL *url = [[NSBundle bundleForClass:[self class]] URLForResource:name withExtension:@".pem"
197 NSData *certData = [NSData dataWithContentsOfURL:url];
202 SecCertificateRef cert = SecCertificateCreateWithPEM(kCFAllocatorDefault, (__bridge CFDataRef)certData);
203 return (__bridge id)cert;
206 /* MARK: run test methods from regressionBase */
207 - (void)runOneLeafTest:(SecPolicyRef)policy
208 anchors:(NSArray *)anchors
209 intermediates:(NSArray *)intermediates
210 leafPath:(NSString *)path
211 expectedResult:(bool)expectedResult
212 expectations:(NSObject *)expectations
213 verifyDate:(NSDate *)date
215 NSString* fileName = [path lastPathComponent];
216 NSString *reason = NULL;
217 SecTrustRef trustRef = NULL;
218 NSMutableArray* certArray = NULL;
219 SecCertificateRef certRef = NULL;
220 CFErrorRef error = NULL;
223 if ([expectations isKindOfClass: [NSString class]]) {
224 reason = (NSString *)expectations;
225 } else if ([expectations isKindOfClass: [NSDictionary class]]) {
226 NSDictionary *dict = (NSDictionary *)expectations;
227 NSObject *value = [dict valueForKey:@"valid"];
229 if ([value isKindOfClass: [NSNumber class]]) {
230 expectedResult = [(NSNumber *)value boolValue];
232 NSLog(@"Unexpected valid value %@ in dict for key %@", value, fileName);
235 value = [dict valueForKey:@"reason"];
237 if ([value isKindOfClass: [NSString class]]) {
238 reason = (NSString *)value;
240 NSLog(@"Unexpected reason value %@ in dict for key %@", value, fileName);
243 } else if ([expectations isKindOfClass: [NSNumber class]]) {
244 expectedResult = [(NSNumber *)expectations boolValue];
246 NSLog(@"Unexpected class %@ value %@ for key %@", [expectations class], expectations, fileName);
250 certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
253 fail("TODO test: %@ unable to create certificate, %@", fileName, reason);
255 fail("PARSE %@ unable to create certificate", fileName);
260 certArray = [NSMutableArray arrayWithArray:intermediates];
261 [certArray insertObject:(__bridge id)certRef atIndex:0]; //The certificate to be verified must be the first in the array.
264 err = SecTrustCreateWithCertificates((__bridge CFTypeRef _Nonnull)(certArray), policy, &trustRef);
266 ok_status(err, "SecTrustCreateWithCertificates");
270 SecTrustSetAnchorCertificates(trustRef, (CFArrayRef)anchors);
272 SecTrustSetVerifyDate(trustRef, (__bridge CFDateRef)date);
274 BOOL isValid = SecTrustEvaluateWithError(trustRef, &error);
276 XCTAssertFalse(isValid == expectedResult, "TODO test: %@%@", fileName, error);
278 ok(isValid == expectedResult, "%s %@%@", expectedResult ? "REGRESSION" : "SECURITY", fileName, error);
282 CFReleaseSafe(trustRef);
283 CFReleaseSafe(certRef);
284 CFReleaseSafe(error);
287 - (void)runCertificateTestFor:(SecPolicyRef)policy
288 anchors:(NSArray *)anchors
289 intermediates:(NSArray *)intermediates
290 leafPaths:(NSMutableArray *)leafPaths
291 expectations:(NSDictionary *)expect
292 verifyDate:(NSDate *)date
294 /* Sort the tests by name. */
295 [leafPaths sortUsingSelector:@selector(compare:)];
297 for (NSString* path in leafPaths) {
298 NSString* fileName = [path lastPathComponent];
299 [self runOneLeafTest:policy anchors:anchors intermediates:intermediates leafPath:path expectedResult:![fileName hasPrefix:@"Invalid"] expectations:[expect objectForKey:fileName] verifyDate:date];
304 - (void)runCertificateTestForDirectory:(SecPolicyRef)policy subDirectory:(NSString *)resourceSubDirectory verifyDate:(NSDate*)date
306 NSMutableArray* allRoots = [NSMutableArray array];
307 NSMutableArray* allCAs = [NSMutableArray array];
308 NSMutableArray* certTests = [NSMutableArray array];
309 NSDictionary* expect = NULL;
311 NSURL* filesDirectory = [[[NSBundle bundleForClass:[self class]] resourceURL] URLByAppendingPathComponent:resourceSubDirectory];
312 for (NSURL* fileURL in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:filesDirectory includingPropertiesForKeys:[NSArray array] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:nil]) {
313 NSString* path = [fileURL path];
314 if ([path hasSuffix:@"Cert.crt"]) {
315 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
316 [allCAs addObject:(__bridge id)certRef];
317 CFReleaseNull(certRef);
318 } else if ([path hasSuffix:@"RootCertificate.crt"]) {
319 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
320 [allRoots addObject:(__bridge id)certRef];
321 CFReleaseNull(certRef);
322 } else if ([path hasSuffix:@".crt"]) {
323 [certTests addObject:path];
324 } else if ([path hasSuffix:@".plist"]) {
326 fail("Multiple .plist files found in %@", filesDirectory);
328 expect = [NSDictionary dictionaryWithContentsOfFile:path];
333 [self runCertificateTestFor:policy anchors:allRoots intermediates:allCAs leafPaths:certTests expectations:expect verifyDate:date];
338 typedef SecCertificateRef (*create_f)(CFAllocatorRef allocator,
339 const UInt8 *der_bytes, CFIndex der_length);
340 CF_RETURNS_RETAINED _Nullable
341 SecCertificateRef SecFrameworkCertificateCreate(const uint8_t * _Nonnull der_bytes, CFIndex der_length) {
342 static create_f FrameworkCertCreateFunctionPtr = NULL;
343 static dispatch_once_t onceToken;
345 dispatch_once(&onceToken, ^{
346 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
348 FrameworkCertCreateFunctionPtr = dlsym(framework, "SecCertificateCreateWithBytes");
352 if (FrameworkCertCreateFunctionPtr) {
353 return FrameworkCertCreateFunctionPtr(NULL, der_bytes, der_length);
355 NSLog(@"WARNING: not using Security framework certificate");
356 return SecCertificateCreateWithBytes(NULL, der_bytes, der_length);
360 SecCertificateRef SecFrameworkCertificateCreateFromTestCert(SecCertificateRef cert) {
361 return SecFrameworkCertificateCreate(SecCertificateGetBytePtr(cert), SecCertificateGetLength(cert));