2 * Copyright (c) 2016-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@
29 #include <AssertMacros.h>
30 #import <Foundation/Foundation.h>
35 #import <MobileAsset/MAAsset.h>
36 #import <MobileAsset/MAAssetQuery.h>
40 #import <MobileAsset/MobileAsset.h>
44 #import <Security/SecInternalReleasePriv.h>
46 #import <securityd/OTATrustUtilities.h>
47 #import <securityd/SecPinningDb.h>
48 #import <securityd/SecTrustLoggingServer.h>
50 #include "utilities/debugging.h"
51 #include "utilities/sqlutils.h"
52 #include "utilities/iOSforOSX.h"
53 #include <utilities/SecCFError.h>
54 #include <utilities/SecCFRelease.h>
55 #include <utilities/SecCFWrappers.h>
56 #include <utilities/SecDb.h>
57 #include <utilities/SecFileLocations.h>
58 #include "utilities/sec_action.h"
60 #define kSecPinningBasePath "/Library/Keychains/"
61 #define kSecPinningDbFileName "pinningrules.sqlite3"
63 const uint64_t PinningDbSchemaVersion = 2;
64 const NSString *PinningDbPolicyNameKey = @"policyName"; /* key for a string value */
65 const NSString *PinningDbDomainsKey = @"domains"; /* key for an array of dictionaries */
66 const NSString *PinningDbPoliciesKey = @"rules"; /* key for an array of dictionaries */
67 const NSString *PinningDbDomainSuffixKey = @"suffix"; /* key for a string */
68 const NSString *PinningDbLabelRegexKey = @"labelRegex"; /* key for a regex string */
70 const CFStringRef kSecPinningDbKeyHostname = CFSTR("PinningHostname");
71 const CFStringRef kSecPinningDbKeyPolicyName = CFSTR("PinningPolicyName");
72 const CFStringRef kSecPinningDbKeyRules = CFSTR("PinningRules");
74 @interface SecPinningDb : NSObject
75 @property (assign) SecDbRef db;
76 @property dispatch_queue_t queue;
77 @property NSURL *dbPath;
78 - (instancetype) init;
79 - ( NSDictionary * _Nullable ) queryForDomain:(NSString *)domain;
80 - ( NSDictionary * _Nullable ) queryForPolicyName:(NSString *)policyName;
83 static inline bool isNSNumber(id nsType) {
84 return nsType && [nsType isKindOfClass:[NSNumber class]];
87 static inline bool isNSArray(id nsType) {
88 return nsType && [nsType isKindOfClass:[NSArray class]];
91 static inline bool isNSDictionary(id nsType) {
92 return nsType && [nsType isKindOfClass:[NSDictionary class]];
95 @implementation SecPinningDb
96 #define getSchemaVersionSQL CFSTR("PRAGMA user_version")
97 #define selectVersionSQL CFSTR("SELECT ival FROM admin WHERE key='version'")
98 #define insertAdminSQL CFSTR("INSERT OR REPLACE INTO admin (key,ival,value) VALUES (?,?,?)")
99 #define selectDomainSQL CFSTR("SELECT DISTINCT labelRegex,policyName,policies FROM rules WHERE domainSuffix=?")
100 #define selectPolicyNameSQL CFSTR("SELECT DISTINCT policies FROM rules WHERE policyName=?")
101 #define insertRuleSQL CFSTR("INSERT OR REPLACE INTO rules (policyName,domainSuffix,labelRegex,policies) VALUES (?,?,?,?) ")
102 #define removeAllRulesSQL CFSTR("DELETE FROM rules;")
104 - (NSNumber *)getSchemaVersion:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
105 __block bool ok = true;
106 __block NSNumber *version = nil;
107 ok &= SecDbWithSQL(dbconn, getSchemaVersionSQL, error, ^bool(sqlite3_stmt *selectVersion) {
108 ok &= SecDbStep(dbconn, selectVersion, error, ^(bool *stop) {
109 int ival = sqlite3_column_int(selectVersion, 0);
110 version = [NSNumber numberWithInt:ival];
117 - (BOOL)setSchemaVersion:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
119 NSString *setVersion = [NSString stringWithFormat:@"PRAGMA user_version = %llu", PinningDbSchemaVersion];
120 ok &= SecDbExec(dbconn,
121 (__bridge CFStringRef)setVersion,
124 secerror("SecPinningDb: failed to create admin table: %@", error ? *error : nil);
129 - (NSNumber *)getContentVersion:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
130 __block bool ok = true;
131 __block NSNumber *version = nil;
132 ok &= SecDbWithSQL(dbconn, selectVersionSQL, error, ^bool(sqlite3_stmt *selectVersion) {
133 ok &= SecDbStep(dbconn, selectVersion, error, ^(bool *stop) {
134 uint64_t ival = sqlite3_column_int64(selectVersion, 0);
135 version = [NSNumber numberWithUnsignedLongLong:ival];
142 - (BOOL)setContentVersion:(NSNumber *)version dbConnection:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
143 __block BOOL ok = true;
144 ok &= SecDbWithSQL(dbconn, insertAdminSQL, error, ^bool(sqlite3_stmt *insertAdmin) {
145 const char *versionKey = "version";
146 ok &= SecDbBindText(insertAdmin, 1, versionKey, strlen(versionKey), SQLITE_TRANSIENT, error);
147 ok &= SecDbBindInt64(insertAdmin, 2, [version unsignedLongLongValue], error);
148 ok &= SecDbStep(dbconn, insertAdmin, error, NULL);
152 secerror("SecPinningDb: failed to set version %@ from pinning list: %@", version, error ? *error : nil);
157 - (BOOL) shouldUpdateContent:(NSNumber *)new_version {
158 __block CFErrorRef error = NULL;
159 __block BOOL ok = YES;
160 __block BOOL newer = NO;
161 ok &= SecDbPerformRead(_db, &error, ^(SecDbConnectionRef dbconn) {
162 NSNumber *db_version = [self getContentVersion:dbconn error:&error];
163 if (!db_version || [new_version compare:db_version] == NSOrderedDescending) {
165 secnotice("pinningDb", "Pinning database should update from version %@ to version %@", db_version, new_version);
170 secerror("SecPinningDb: error reading content version from database %@", error);
172 CFReleaseNull(error);
176 - (BOOL) insertRuleWithName:(NSString *)policyName
177 domainSuffix:(NSString *)domainSuffix
178 labelRegex:(NSString *)labelRegex
179 policies:(NSArray *)policies
180 dbConnection:(SecDbConnectionRef)dbconn
181 error:(CFErrorRef *)error{
182 /* @@@ This insertion mechanism assumes that the input is trusted -- namely, that the new rules
183 * are allowed to replace existing rules. For third-party inputs, this assumption isn't true. */
185 secdebug("pinningDb", "inserting new rule: %@ for %@.%@", policyName, labelRegex, domainSuffix);
187 __block bool ok = true;
188 ok &= SecDbWithSQL(dbconn, insertRuleSQL, error, ^bool(sqlite3_stmt *insertRule) {
189 ok &= SecDbBindText(insertRule, 1, [policyName UTF8String], [policyName length], SQLITE_TRANSIENT, error);
190 ok &= SecDbBindText(insertRule, 2, [domainSuffix UTF8String], [domainSuffix length], SQLITE_TRANSIENT, error);
191 ok &= SecDbBindText(insertRule, 3, [labelRegex UTF8String], [labelRegex length], SQLITE_TRANSIENT, error);
192 NSData *xmlPolicies = [NSPropertyListSerialization dataWithPropertyList:policies
193 format:NSPropertyListXMLFormat_v1_0
197 secerror("SecPinningDb: failed to serialize policies");
200 ok &= SecDbBindBlob(insertRule, 4, [xmlPolicies bytes], [xmlPolicies length], SQLITE_TRANSIENT, error);
201 ok &= SecDbStep(dbconn, insertRule, error, NULL);
205 secerror("SecPinningDb: failed to insert rule %@ for %@.%@ with error %@", policyName, labelRegex, domainSuffix, error ? *error : nil);
210 - (BOOL) populateDbFromBundle:(NSArray *)pinningList dbConnection:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
211 __block BOOL ok = true;
212 [pinningList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
213 if (idx ==0) { return; } // Skip the first value which is the version
214 if (!isNSDictionary(obj)) {
215 secerror("SecPinningDb: rule entry in pinning plist is wrong class");
219 NSDictionary *rule = obj;
220 __block NSString *policyName = [rule objectForKey:PinningDbPolicyNameKey];
221 NSArray *domains = [rule objectForKey:PinningDbDomainsKey];
222 __block NSArray *policies = [rule objectForKey:PinningDbPoliciesKey];
224 if (!policyName || !domains || !policies) {
225 secerror("SecPinningDb: failed to get required fields from rule entry %lu", (unsigned long)idx);
230 [domains enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
231 if (!isNSDictionary(obj)) {
232 secerror("SecPinningDb: domain entry %lu for %@ in pinning rule is wrong class", (unsigned long)idx, policyName);
236 NSDictionary *domain = obj;
237 NSString *suffix = [domain objectForKey:PinningDbDomainSuffixKey];
238 NSString *labelRegex = [domain objectForKey:PinningDbLabelRegexKey];
240 if (!suffix || !labelRegex) {
241 secerror("SecPinningDb: failed to get required fields for entry %lu for %@", (unsigned long)idx, policyName);
245 ok &= [self insertRuleWithName:policyName domainSuffix:suffix labelRegex:labelRegex policies:policies
246 dbConnection:dbconn error:error];
250 secerror("SecPinningDb: failed to populate DB from pinning list: %@", error ? *error : nil);
255 - (BOOL) removeAllRulesFromDb:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
256 __block BOOL ok = true;
257 ok &= SecDbWithSQL(dbconn, removeAllRulesSQL, error, ^bool(sqlite3_stmt *deleteRules) {
258 ok &= SecDbStep(dbconn, deleteRules, error, NULL);
262 secerror("SecPinningDb: failed to delete old values: %@", error ? *error :nil);
268 - (BOOL) createOrAlterAdminTable:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
270 ok &= SecDbExec(dbconn,
271 CFSTR("CREATE TABLE IF NOT EXISTS admin("
272 "key TEXT PRIMARY KEY NOT NULL,"
273 "ival INTEGER NOT NULL,"
278 secerror("SecPinningDb: failed to create admin table: %@", error ? *error : nil);
283 - (BOOL) createOrAlterRulesTable:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error {
285 ok &= SecDbExec(dbconn,
286 CFSTR("CREATE TABLE IF NOT EXISTS rules("
287 "policyName TEXT NOT NULL,"
288 "domainSuffix TEXT NOT NULL,"
289 "labelRegex TEXT NOT NULL,"
290 "policies BLOB NOT NULL,"
291 "UNIQUE(policyName, domainSuffix, labelRegex)"
294 ok &= SecDbExec(dbconn, CFSTR("CREATE INDEX IF NOT EXISTS idomain ON rules(domainSuffix);"), error);
295 ok &= SecDbExec(dbconn, CFSTR("CREATE INDEX IF NOT EXISTS ipolicy ON rules(policyName);"), error);
297 secerror("SecPinningDb: failed to create rules table: %@", error ? *error : nil);
302 #if !TARGET_OS_BRIDGE
303 - (BOOL) installDbFromURL:(NSURL *)localURL {
305 secerror("SecPinningDb: missing url for downloaded asset");
308 NSURL *fileLoc = [NSURL URLWithString:@"CertificatePinning.plist"
309 relativeToURL:localURL];
310 __block NSArray *pinningList = [NSArray arrayWithContentsOfURL:fileLoc];
312 secerror("SecPinningDb: unable to create pinning list from asset file: %@", fileLoc);
316 NSNumber *plist_version = [pinningList objectAtIndex:0];
317 if (![self shouldUpdateContent:plist_version]) {
318 /* We got a new plist but we already have that version installed. */
323 __block CFErrorRef error = NULL;
324 __block BOOL ok = YES;
325 dispatch_sync(self->_queue, ^{
326 ok &= SecDbPerformWrite(self->_db, &error, ^(SecDbConnectionRef dbconn) {
327 ok &= [self updateDb:dbconn error:&error pinningList:pinningList updateSchema:NO updateContent:YES];
332 secerror("SecPinningDb: error installing updated pinning list version %@: %@", [pinningList objectAtIndex:0], error);
333 #if ENABLE_TRUSTD_ANALYTICS
334 [[TrustdHealthAnalytics logger] logHardError:(__bridge NSError *)error
335 withEventName:TrustdHealthAnalyticsEventDatabaseEvent
336 withAttributes:@{TrustdHealthAnalyticsAttributeAffectedDatabase : @(TAPinningDb),
337 TrustdHealthAnalyticsAttributeDatabaseOperation : @(TAOperationWrite) }];
338 #endif // ENABLE_TRUSTD_ANALYTICS
339 CFReleaseNull(error);
344 #endif /* !TARGET_OS_BRIDGE */
346 - (NSArray *) copySystemPinningList {
347 NSArray *pinningList = nil;
348 NSURL *pinningListURL = nil;
349 /* Get the pinning list shipped with the OS */
350 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
352 pinningListURL = CFBridgingRelease(SecOTAPKICopyPinningList(otapkiref));
353 CFReleaseNull(otapkiref);
354 if (!pinningListURL) {
355 secerror("SecPinningDb: failed to get pinning plist URL");
357 NSError *error = nil;
358 pinningList = [NSArray arrayWithContentsOfURL:pinningListURL error:&error];
360 secerror("SecPinningDb: failed to read pinning plist from bundle: %@", error);
367 - (BOOL) updateDb:(SecDbConnectionRef)dbconn error:(CFErrorRef *)error pinningList:(NSArray *)pinningList
368 updateSchema:(BOOL)updateSchema updateContent:(BOOL)updateContent
370 if (!SecOTAPKIIsSystemTrustd()) { return false; }
371 secdebug("pinningDb", "updating or creating database");
373 __block bool ok = true;
374 ok &= SecDbTransaction(dbconn, kSecDbExclusiveTransactionType, error, ^(bool *commit) {
376 /* update the tables */
377 ok &= [self createOrAlterAdminTable:dbconn error:error];
378 ok &= [self createOrAlterRulesTable:dbconn error:error];
379 ok &= [self setSchemaVersion:dbconn error:error];
383 /* remove the old data */
384 /* @@@ This behavior assumes that we have all the rules we want to populate
385 * elsewhere on disk and that the DB doesn't contain the sole copy of that data. */
386 ok &= [self removeAllRulesFromDb:dbconn error:error];
388 /* read the new data */
389 NSNumber *version = [pinningList objectAtIndex:0];
391 /* populate the tables */
392 ok &= [self populateDbFromBundle:pinningList dbConnection:dbconn error:error];
393 ok &= [self setContentVersion:version dbConnection:dbconn error:error];
402 - (SecDbRef) createAtPath {
403 bool readWrite = SecOTAPKIIsSystemTrustd();
405 mode_t mode = 0644; // Root trustd can rw. All other trustds need to read.
407 mode_t mode = 0600; // Only one trustd.
410 CFStringRef path = CFStringCreateWithCString(NULL, [_dbPath fileSystemRepresentation], kCFStringEncodingUTF8);
411 SecDbRef result = SecDbCreateWithOptions(path, mode, readWrite, readWrite, false,
412 ^bool (SecDbRef db, SecDbConnectionRef dbconn, bool didCreate, bool *callMeAgainForNextConnection, CFErrorRef *error) {
413 if (!SecOTAPKIIsSystemTrustd()) {
414 /* Non-owner process can't update the db, but it should get a db connection.
415 * @@@ Revisit if new schema version is needed by reader processes. */
419 __block BOOL ok = true;
420 dispatch_sync(self->_queue, ^{
421 bool updateSchema = false;
422 bool updateContent = false;
424 /* Get the pinning plist */
425 NSArray *pinningList = [self copySystemPinningList];
427 secerror("SecPinningDb: failed to find pinning plist in bundle");
432 /* Check latest data and schema versions against existing table. */
433 if (!isNSNumber([pinningList objectAtIndex:0])) {
434 secerror("SecPinningDb: pinning plist in wrong format");
435 return; // Don't change status. We can continue to use old DB.
437 NSNumber *plist_version = [pinningList objectAtIndex:0];
438 NSNumber *db_version = [self getContentVersion:dbconn error:error];
439 secnotice("pinningDb", "Opening db with version %@", db_version);
440 if (!db_version || [plist_version compare:db_version] == NSOrderedDescending) {
441 secnotice("pinningDb", "Updating pinning database content from version %@ to version %@",
442 db_version ? db_version : 0, plist_version);
443 updateContent = true;
445 NSNumber *schema_version = [self getSchemaVersion:dbconn error:error];
446 NSNumber *current_version = [NSNumber numberWithUnsignedLongLong:PinningDbSchemaVersion];
447 if (!schema_version || ![schema_version isEqualToNumber:current_version]) {
448 secnotice("pinningDb", "Updating pinning database schema from version %@ to version %@",
449 schema_version, current_version);
453 if (updateContent || updateSchema) {
454 ok &= [self updateDb:dbconn error:error pinningList:pinningList updateSchema:updateSchema updateContent:updateContent];
455 /* Since we updated the DB to match the list that shipped with the system,
456 * reset the OTAPKI Asset version to the system asset version */
457 (void)SecOTAPKIResetCurrentAssetVersion(NULL);
460 secerror("SecPinningDb: %s failed: %@", didCreate ? "Create" : "Open", error ? *error : NULL);
461 #if ENABLE_TRUSTD_ANALYTICS
462 [[TrustdHealthAnalytics logger] logHardError:(error ? (__bridge NSError *)*error : nil)
463 withEventName:TrustdHealthAnalyticsEventDatabaseEvent
464 withAttributes:@{TrustdHealthAnalyticsAttributeAffectedDatabase : @(TAPinningDb),
465 TrustdHealthAnalyticsAttributeDatabaseOperation : didCreate ? @(TAOperationCreate) : @(TAOperationOpen)}];
466 #endif // ENABLE_TRUSTD_ANALYTICS
476 static void verify_create_path(const char *path)
478 int ret = mkpath_np(path, 0755);
479 if (!(ret == 0 || ret == EEXIST)) {
480 secerror("could not create path: %s (%s)", path, strerror(ret));
484 - (NSURL *)pinningDbPath {
485 /* Make sure the /Library/Keychains directory is there */
487 NSURL *directory = CFBridgingRelease(SecCopyURLForFileInKeychainDirectory(nil));
489 NSURL *directory = [NSURL fileURLWithFileSystemRepresentation:"/Library/Keychains/" isDirectory:YES relativeToURL:nil];
491 verify_create_path([directory fileSystemRepresentation]);
493 /* Get the full path of the pinning DB */
494 return [directory URLByAppendingPathComponent:@"pinningrules.sqlite3"];
497 - (void) initializedDb {
498 dispatch_sync(_queue, ^{
500 self->_dbPath = [self pinningDbPath];
501 self->_db = [self createAtPath];
506 - (instancetype) init {
507 if (self = [super init]) {
508 _queue = dispatch_queue_create("Pinning DB Queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
509 [self initializedDb];
518 - (BOOL) isPinningDisabled:(NSString * _Nullable)policy {
519 static dispatch_once_t once;
520 static sec_action_t action;
522 BOOL pinningDisabled = NO;
523 if (SecIsInternalRelease()) {
524 NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.apple.security"];
525 pinningDisabled = [defaults boolForKey:@"AppleServerAuthenticationNoPinning"];
526 if (!pinningDisabled && policy) {
527 NSMutableString *policySpecificKey = [NSMutableString stringWithString:@"AppleServerAuthenticationNoPinning"];
528 [policySpecificKey appendString:policy];
529 pinningDisabled = [defaults boolForKey:policySpecificKey];
530 secinfo("pinningQA", "%@ disable pinning = %d", policy, pinningDisabled);
535 dispatch_once(&once, ^{
536 /* Only log system-wide pinning status once every five minutes */
537 action = sec_action_create("pinning logging charles", 5*60.0);
538 sec_action_set_handler(action, ^{
539 if (!SecIsInternalRelease()) {
540 secnotice("pinningQA", "could not disable pinning: not an internal release");
542 NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.apple.security"];
543 secnotice("pinningQA", "generic pinning disable = %d", [defaults boolForKey:@"AppleServerAuthenticationNoPinning"]);
547 sec_action_perform(action);
549 return pinningDisabled;
552 - ( NSDictionary * _Nullable ) queryForDomain:(NSString *)domain {
553 if (!_queue) { (void)[self init]; }
554 if (!_db) { [self initializedDb]; }
556 /* Check for general no-pinning setting */
557 if ([self isPinningDisabled:nil]) {
561 /* parse the domain into suffix and 1st label */
562 NSRange firstDot = [domain rangeOfString:@"."];
563 if (firstDot.location == NSNotFound) { return nil; } // Probably not a legitimate domain name
564 __block NSString *firstLabel = [domain substringToIndex:firstDot.location];
565 __block NSString *suffix = [domain substringFromIndex:(firstDot.location + 1)];
568 __block bool ok = true;
569 __block CFErrorRef error = NULL;
570 __block NSMutableArray *resultRules = [NSMutableArray array];
571 __block NSString *resultName = nil;
572 ok &= SecDbPerformRead(_db, &error, ^(SecDbConnectionRef dbconn) {
573 ok &= SecDbWithSQL(dbconn, selectDomainSQL, &error, ^bool(sqlite3_stmt *selectDomain) {
574 ok &= SecDbBindText(selectDomain, 1, [suffix UTF8String], [suffix length], SQLITE_TRANSIENT, &error);
575 ok &= SecDbStep(dbconn, selectDomain, &error, ^(bool *stop) {
576 /* Match the labelRegex */
577 const uint8_t *regex = sqlite3_column_text(selectDomain, 0);
578 if (!regex) { return; }
579 NSString *regexStr = [NSString stringWithUTF8String:(const char *)regex];
580 if (!regexStr) { return; }
581 NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regexStr
582 options:NSRegularExpressionCaseInsensitive
584 if (!regularExpression) { return; }
585 NSUInteger numMatches = [regularExpression numberOfMatchesInString:firstLabel
587 range:NSMakeRange(0, [firstLabel length])];
588 if (numMatches == 0) {
591 secdebug("SecPinningDb", "found matching rule for %@.%@", firstLabel, suffix);
593 /* Check the policyName for no-pinning settings */
594 const uint8_t *policyName = sqlite3_column_text(selectDomain, 1);
595 NSString *policyNameStr = [NSString stringWithUTF8String:(const char *)policyName];
596 if ([self isPinningDisabled:policyNameStr]) {
600 /* Deserialize the policies and return.
601 * @@@ Assumes there is only one rule with matching suffix/label pairs. */
602 NSData *xmlPolicies = [NSData dataWithBytes:sqlite3_column_blob(selectDomain, 2) length:sqlite3_column_bytes(selectDomain, 2)];
603 if (!xmlPolicies) { return; }
604 id policies = [NSPropertyListSerialization propertyListWithData:xmlPolicies options:0 format:nil error:nil];
605 if (!isNSArray(policies)) {
608 [resultRules addObjectsFromArray:(NSArray *)policies];
609 resultName = policyNameStr;
616 secerror("SecPinningDb: error querying DB for hostname: %@", error);
617 #if ENABLE_TRUSTD_ANALYTICS
618 [[TrustdHealthAnalytics logger] logHardError:(__bridge NSError *)error
619 withEventName:TrustdHealthAnalyticsEventDatabaseEvent
620 withAttributes:@{TrustdHealthAnalyticsAttributeAffectedDatabase : @(TAPinningDb),
621 TrustdHealthAnalyticsAttributeDatabaseOperation : @(TAOperationRead)}];
622 #endif // ENABLE_TRUSTD_ANALYTICS
623 CFReleaseNull(error);
626 if ([resultRules count] > 0) {
627 NSDictionary *results = @{(__bridge NSString*)kSecPinningDbKeyRules:resultRules,
628 (__bridge NSString*)kSecPinningDbKeyPolicyName:resultName};
634 - (NSDictionary * _Nullable) queryForPolicyName:(NSString *)policyName {
635 if (!_queue) { (void)[self init]; }
636 if (!_db) { [self initializedDb]; }
638 /* Skip the "sslServer" policyName, which is not a pinning policy */
639 if ([policyName isEqualToString:@"sslServer"]) {
643 /* Check for general no-pinning setting */
644 if ([self isPinningDisabled:nil] || [self isPinningDisabled:policyName]) {
648 secinfo("SecPinningDb", "Fetching rules for policy named %@", policyName);
651 __block bool ok = true;
652 __block CFErrorRef error = NULL;
653 __block NSMutableArray *resultRules = [NSMutableArray array];
654 ok &= SecDbPerformRead(_db, &error, ^(SecDbConnectionRef dbconn) {
655 ok &= SecDbWithSQL(dbconn, selectPolicyNameSQL, &error, ^bool(sqlite3_stmt *selectPolicyName) {
656 ok &= SecDbBindText(selectPolicyName, 1, [policyName UTF8String], [policyName length], SQLITE_TRANSIENT, &error);
657 ok &= SecDbStep(dbconn, selectPolicyName, &error, ^(bool *stop) {
658 secdebug("SecPinningDb", "found matching rule for %@ policy", policyName);
660 /* Deserialize the policies and return */
661 NSData *xmlPolicies = [NSData dataWithBytes:sqlite3_column_blob(selectPolicyName, 0) length:sqlite3_column_bytes(selectPolicyName, 0)];
662 if (!xmlPolicies) { return; }
663 id policies = [NSPropertyListSerialization propertyListWithData:xmlPolicies options:0 format:nil error:nil];
664 if (!isNSArray(policies)) {
667 [resultRules addObjectsFromArray:(NSArray *)policies];
674 secerror("SecPinningDb: error querying DB for policyName: %@", error);
675 #if ENABLE_TRUSTD_ANALYTICS
676 [[TrustdHealthAnalytics logger] logHardError:(__bridge NSError *)error
677 withEventName:TrustdHealthAnalyticsEventDatabaseEvent
678 withAttributes:@{TrustdHealthAnalyticsAttributeAffectedDatabase : @(TAPinningDb),
679 TrustdHealthAnalyticsAttributeDatabaseOperation : @(TAOperationRead)}];
680 #endif // ENABLE_TRUSTD_ANALYTICS
681 CFReleaseNull(error);
684 if ([resultRules count] > 0) {
685 NSDictionary *results = @{(__bridge NSString*)kSecPinningDbKeyRules:resultRules,
686 (__bridge NSString*)kSecPinningDbKeyPolicyName:policyName};
695 static SecPinningDb *pinningDb = nil;
696 void SecPinningDbInitialize(void) {
697 /* Create the pinning object once per launch */
698 static dispatch_once_t onceToken;
699 dispatch_once(&onceToken, ^{
701 pinningDb = [[SecPinningDb alloc] init];
702 __block CFErrorRef error = NULL;
703 BOOL ok = SecDbPerformRead([pinningDb db], &error, ^(SecDbConnectionRef dbconn) {
704 NSNumber *contentVersion = [pinningDb getContentVersion:dbconn error:&error];
705 NSNumber *schemaVersion = [pinningDb getSchemaVersion:dbconn error:&error];
706 secinfo("pinningDb", "Database Schema: %@ Content: %@", schemaVersion, contentVersion);
709 secerror("SecPinningDb: unable to initialize db: %@", error);
710 #if ENABLE_TRUSTD_ANALYTICS
711 [[TrustdHealthAnalytics logger] logHardError:(__bridge NSError *)error
712 withEventName:TrustdHealthAnalyticsEventDatabaseEvent
713 withAttributes:@{TrustdHealthAnalyticsAttributeAffectedDatabase : @(TAPinningDb),
714 TrustdHealthAnalyticsAttributeDatabaseOperation : @(TAOperationRead)}];
715 #endif // ENABLE_TRUSTD_ANALYTICS
717 CFReleaseNull(error);
722 CFDictionaryRef _Nullable SecPinningDbCopyMatching(CFDictionaryRef query) {
724 SecPinningDbInitialize();
726 NSDictionary *nsQuery = (__bridge NSDictionary*)query;
727 NSString *hostname = [nsQuery objectForKey:(__bridge NSString*)kSecPinningDbKeyHostname];
729 NSDictionary *results = [pinningDb queryForDomain:hostname];
730 if (results) { return CFBridgingRetain(results); }
731 NSString *policyName = [nsQuery objectForKey:(__bridge NSString*)kSecPinningDbKeyPolicyName];
732 results = [pinningDb queryForPolicyName:policyName];
733 if (!results) { return nil; }
734 return CFBridgingRetain(results);
738 #if !TARGET_OS_BRIDGE
739 bool SecPinningDbUpdateFromURL(CFURLRef url) {
740 SecPinningDbInitialize();
742 return [pinningDb installDbFromURL:(__bridge NSURL*)url];
746 CFNumberRef SecPinningDbCopyContentVersion(void) {
748 __block CFErrorRef error = NULL;
749 __block NSNumber *contentVersion = nil;
750 BOOL ok = SecDbPerformRead([pinningDb db], &error, ^(SecDbConnectionRef dbconn) {
751 contentVersion = [pinningDb getContentVersion:dbconn error:&error];
754 secerror("SecPinningDb: unable to get content version: %@", error);
756 CFReleaseNull(error);
757 if (!contentVersion) {
758 contentVersion = [NSNumber numberWithInteger:0];
760 return CFBridgingRetain(contentVersion);