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 "OSX/trustd/trustd_spi.h"
26 #include <Security/SecCertificatePriv.h>
27 #include <Security/SecTrustPriv.h>
28 #include <Security/SecPolicy.h>
29 #include <Security/SecTrustSettings.h>
30 #include <Security/SecTrustSettingsPriv.h>
31 #include "OSX/utilities/SecCFWrappers.h"
32 #include <dispatch/dispatch.h>
36 #include <Security/SecTrustStore.h>
38 #define kSystemLoginKeychainPath "/Library/Keychains/System.keychain"
39 #include <Security/SecKeychain.h>
42 #import "../TestMacroConversions.h"
43 #import "TrustEvaluationTestCase.h"
45 @implementation TrustEvaluationTestCase
47 static int current_dir = -1;
48 static char *home_var = NULL;
50 /* Build in trustd functionality to the tests */
52 /* Set up TMP directory for trustd's files */
55 NSString* pid = [NSString stringWithFormat: @"tst-%d", [[NSProcessInfo processInfo] processIdentifier]];
56 NSURL* tmpDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:pid];
59 if (current_dir == -1 && home_var == NULL) {
60 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:tmpDirURL
61 withIntermediateDirectories:NO
65 NSURL* libraryURL = [tmpDirURL URLByAppendingPathComponent:@"Library"];
66 NSURL* preferencesURL = [tmpDirURL URLByAppendingPathComponent:@"Preferences"];
68 ok = (ok && (current_dir = open(".", O_RDONLY) >= 0)
69 && (chdir([tmpDirURL fileSystemRepresentation]) >= 0)
70 && (setenv("HOME", [tmpDirURL fileSystemRepresentation], 1) >= 0)
71 && (bool)(home_var = getenv("HOME")));
73 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:libraryURL
74 withIntermediateDirectories:NO
78 ok = ok && [[NSFileManager defaultManager] createDirectoryAtURL:preferencesURL
79 withIntermediateDirectories:NO
86 trustd_init((__bridge CFURLRef) tmpDirURL);
90 - (id)addTrustSettingsForCert:(SecCertificateRef)cert trustSettings:(id)trustSettings
93 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
94 OSStatus status = SecTrustStoreSetTrustSettings(defaultStore, cert, (__bridge CFTypeRef)trustSettings);
95 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", (int)status);
98 /* Since we're putting trust settings in the admin domain,
99 * we need to add the certs to the system keychain. */
100 SecKeychainRef kcRef = NULL;
101 CFArrayRef certRef = NULL;
102 NSDictionary *attrs = nil;
104 SecKeychainOpen(kSystemLoginKeychainPath, &kcRef);
109 /* Since we're interacting with the keychain we need a framework cert */
110 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
111 attrs = @{(__bridge NSString*)kSecValueRef: (__bridge id)frameworkCert,
112 (__bridge NSString*)kSecUseKeychain: (__bridge id)kcRef,
113 (__bridge NSString*)kSecReturnPersistentRef: @YES};
114 OSStatus status = SecItemAdd((CFDictionaryRef)attrs, (void *)&certRef);
115 XCTAssert(errSecSuccess == status, "failed to add cert to keychain: %d", status);
116 id result = ((__bridge NSArray*)certRef)[0];
117 CFReleaseNull(kcRef);
118 CFReleaseNull(certRef);
120 status = SecTrustSettingsSetTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin,
121 (__bridge CFTypeRef)trustSettings);
122 XCTAssert(errSecSuccess == status, "failed to set trust settings: %d", status);
125 CFReleaseNull(frameworkCert);
131 - (id)addTrustSettingsForCert:(SecCertificateRef)cert
133 NSDictionary *trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustRoot)};
134 Boolean isSelfSigned = false;
135 XCTAssert(errSecSuccess == SecCertificateIsSelfSigned(cert, &isSelfSigned));
137 trustSettings = @{ (__bridge NSString*)kSecTrustSettingsResult: @(kSecTrustSettingsResultTrustAsRoot)};
140 return [self addTrustSettingsForCert:cert trustSettings:trustSettings];
143 - (void)removeTrustSettingsForCert:(SecCertificateRef)cert persistentRef:(id)persistentRef
146 SecTrustStoreRef defaultStore = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
147 XCTAssert(errSecSuccess == SecTrustStoreRemoveCertificate(defaultStore, cert), "failed to remove trust settings");
149 SecCertificateRef frameworkCert = SecFrameworkCertificateCreateFromTestCert(cert);
150 XCTAssert(errSecSuccess == SecTrustSettingsRemoveTrustSettings(frameworkCert, kSecTrustSettingsDomainAdmin),
151 "failed to remove trust settings");
152 XCTAssert(errSecSuccess == SecItemDelete((CFDictionaryRef)@{ (__bridge NSString*)kSecValuePersistentRef: persistentRef}),
153 "failed to remove item from keychain");
154 CFReleaseNull(frameworkCert);
158 const CFStringRef kSecurityPreferencesDomain = CFSTR("com.apple.security");
159 const CFStringRef kTestSystemRootKey = CFSTR("TestSystemRoot");
161 - (void)setTestRootAsSystem:(const uint8_t *)sha256hash
163 NSData *rootHash = [NSData dataWithBytes:sha256hash length:32];
164 CFPreferencesSetAppValue(kTestSystemRootKey, (__bridge CFDataRef)rootHash, kSecurityPreferencesDomain);
165 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
168 - (void)removeTestRootAsSystem
170 CFPreferencesSetAppValue(kTestSystemRootKey, NULL, kSecurityPreferencesDomain);
171 CFPreferencesAppSynchronize(kSecurityPreferencesDomain);
174 /* MARK: run test methods from regressionBase */
175 - (void)runOneLeafTest:(SecPolicyRef)policy
176 anchors:(NSArray *)anchors
177 intermediates:(NSArray *)intermediates
178 leafPath:(NSString *)path
179 expectedResult:(bool)expectedResult
180 expectations:(NSObject *)expectations
181 verifyDate:(NSDate *)date
183 NSString* fileName = [path lastPathComponent];
184 NSString *reason = NULL;
185 SecTrustRef trustRef = NULL;
186 NSMutableArray* certArray = NULL;
187 SecCertificateRef certRef = NULL;
188 CFErrorRef error = NULL;
191 if ([expectations isKindOfClass: [NSString class]]) {
192 reason = (NSString *)expectations;
193 } else if ([expectations isKindOfClass: [NSDictionary class]]) {
194 NSDictionary *dict = (NSDictionary *)expectations;
195 NSObject *value = [dict valueForKey:@"valid"];
197 if ([value isKindOfClass: [NSNumber class]]) {
198 expectedResult = [(NSNumber *)value boolValue];
200 NSLog(@"Unexpected valid value %@ in dict for key %@", value, fileName);
203 value = [dict valueForKey:@"reason"];
205 if ([value isKindOfClass: [NSString class]]) {
206 reason = (NSString *)value;
208 NSLog(@"Unexpected reason value %@ in dict for key %@", value, fileName);
211 } else if ([expectations isKindOfClass: [NSNumber class]]) {
212 expectedResult = [(NSNumber *)expectations boolValue];
214 NSLog(@"Unexpected class %@ value %@ for key %@", [expectations class], expectations, fileName);
218 certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
221 fail("TODO test: %@ unable to create certificate, %@", fileName, reason);
223 fail("PARSE %@ unable to create certificate", fileName);
228 certArray = [NSMutableArray arrayWithArray:intermediates];
229 [certArray insertObject:(__bridge id)certRef atIndex:0]; //The certificate to be verified must be the first in the array.
232 err = SecTrustCreateWithCertificates((__bridge CFTypeRef _Nonnull)(certArray), policy, &trustRef);
234 ok_status(err, "SecTrustCreateWithCertificates");
238 SecTrustSetAnchorCertificates(trustRef, (CFArrayRef)anchors);
240 SecTrustSetVerifyDate(trustRef, (__bridge CFDateRef)date);
242 BOOL isValid = SecTrustEvaluateWithError(trustRef, &error);
244 XCTAssertFalse(isValid == expectedResult, "TODO test: %@%@", fileName, error);
246 ok(isValid == expectedResult, "%s %@%@", expectedResult ? "REGRESSION" : "SECURITY", fileName, error);
250 CFReleaseSafe(trustRef);
251 CFReleaseSafe(certRef);
252 CFReleaseSafe(error);
255 - (void)runCertificateTestFor:(SecPolicyRef)policy
256 anchors:(NSArray *)anchors
257 intermediates:(NSArray *)intermediates
258 leafPaths:(NSMutableArray *)leafPaths
259 expectations:(NSDictionary *)expect
260 verifyDate:(NSDate *)date
262 /* Sort the tests by name. */
263 [leafPaths sortUsingSelector:@selector(compare:)];
265 for (NSString* path in leafPaths) {
266 NSString* fileName = [path lastPathComponent];
267 [self runOneLeafTest:policy anchors:anchors intermediates:intermediates leafPath:path expectedResult:![fileName hasPrefix:@"Invalid"] expectations:[expect objectForKey:fileName] verifyDate:date];
272 - (void)runCertificateTestForDirectory:(SecPolicyRef)policy subDirectory:(NSString *)resourceSubDirectory verifyDate:(NSDate*)date
274 NSMutableArray* allRoots = [NSMutableArray array];
275 NSMutableArray* allCAs = [NSMutableArray array];
276 NSMutableArray* certTests = [NSMutableArray array];
277 NSDictionary* expect = NULL;
279 NSURL* filesDirectory = [[[NSBundle bundleForClass:[self class]] resourceURL] URLByAppendingPathComponent:resourceSubDirectory];
280 for (NSURL* fileURL in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:filesDirectory includingPropertiesForKeys:[NSArray array] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:nil]) {
281 NSString* path = [fileURL path];
282 if ([path hasSuffix:@"Cert.crt"]) {
283 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
284 [allCAs addObject:(__bridge id)certRef];
285 CFReleaseNull(certRef);
286 } else if ([path hasSuffix:@"RootCertificate.crt"]) {
287 SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (CFDataRef)[NSData dataWithContentsOfFile:path]);
288 [allRoots addObject:(__bridge id)certRef];
289 CFReleaseNull(certRef);
290 } else if ([path hasSuffix:@".crt"]) {
291 [certTests addObject:path];
292 } else if ([path hasSuffix:@".plist"]) {
294 fail("Multiple .plist files found in %@", filesDirectory);
296 expect = [NSDictionary dictionaryWithContentsOfFile:path];
301 [self runCertificateTestFor:policy anchors:allRoots intermediates:allCAs leafPaths:certTests expectations:expect verifyDate:date];
306 typedef SecCertificateRef (*create_f)(CFAllocatorRef allocator,
307 const UInt8 *der_bytes, CFIndex der_length);
308 CF_RETURNS_RETAINED _Nullable
309 SecCertificateRef SecFrameworkCertificateCreate(const uint8_t * _Nonnull der_bytes, CFIndex der_length) {
310 static create_f FrameworkCertCreateFunctionPtr = NULL;
311 static dispatch_once_t onceToken;
313 dispatch_once(&onceToken, ^{
314 void *framework = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY);
316 FrameworkCertCreateFunctionPtr = dlsym(framework, "SecCertificateCreateWithBytes");
320 if (FrameworkCertCreateFunctionPtr) {
321 return FrameworkCertCreateFunctionPtr(NULL, der_bytes, der_length);
323 NSLog(@"WARNING: not using Security framework certificate");
324 return SecCertificateCreateWithBytes(NULL, der_bytes, der_length);
328 SecCertificateRef SecFrameworkCertificateCreateFromTestCert(SecCertificateRef cert) {
329 return SecFrameworkCertificateCreate(SecCertificateGetBytePtr(cert), SecCertificateGetLength(cert));