1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/cert/cert_database.h"
6
7 #include <Security/Security.h>
8
9 #include "base/apple/osstatus_logging.h"
10 #include "base/check.h"
11 #include "base/functional/bind.h"
12 #include "base/location.h"
13 #include "base/notreached.h"
14 #include "base/process/process_handle.h"
15 #include "net/base/network_notification_thread_mac.h"
16
17 namespace net {
18
19 namespace {
20
21 // Helper that observes events from the Keychain and forwards them to the
22 // CertDatabase.
23 class Notifier {
24 public:
Notifier()25 Notifier() {
26 GetNetworkNotificationThreadMac()->PostTask(
27 FROM_HERE, base::BindOnce(&Notifier::Init, base::Unretained(this)));
28 }
29
30 ~Notifier() = delete;
31
32 // Much of the Keychain API was marked deprecated as of the macOS 13 SDK.
33 // Removal of its use is tracked in https://crbug.com/1348251 but deprecation
34 // warnings are disabled in the meanwhile.
35 #pragma clang diagnostic push
36 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
37
38 private:
Init()39 void Init() {
40 SecKeychainEventMask event_mask =
41 kSecKeychainListChangedMask | kSecTrustSettingsChangedEventMask;
42 SecKeychainAddCallback(&Notifier::KeychainCallback, event_mask, nullptr);
43 }
44
45 #pragma clang diagnostic pop
46
47 // SecKeychainCallback function that receives notifications from securityd
48 // and forwards them to the |cert_db_|.
49 static OSStatus KeychainCallback(SecKeychainEvent keychain_event,
50 SecKeychainCallbackInfo* info,
51 void* context);
52 };
53
54 // static
KeychainCallback(SecKeychainEvent keychain_event,SecKeychainCallbackInfo * info,void * context)55 OSStatus Notifier::KeychainCallback(SecKeychainEvent keychain_event,
56 SecKeychainCallbackInfo* info,
57 void* context) {
58 if (info->version > SEC_KEYCHAIN_SETTINGS_VERS1) {
59 NOTREACHED();
60 }
61
62 if (info->pid == base::GetCurrentProcId()) {
63 // Ignore events generated by the current process, as the assumption is
64 // that they have already been handled. This may miss events that
65 // originated as a result of spawning native dialogs that allow the user
66 // to modify Keychain settings. However, err on the side of missing
67 // events rather than sending too many events.
68 return errSecSuccess;
69 }
70
71 switch (keychain_event) {
72 case kSecKeychainListChangedEvent:
73 CertDatabase::GetInstance()->NotifyObserversClientCertStoreChanged();
74 break;
75 case kSecTrustSettingsChangedEvent:
76 CertDatabase::GetInstance()->NotifyObserversTrustStoreChanged();
77 break;
78
79 default:
80 break;
81 }
82
83 return errSecSuccess;
84 }
85
86 } // namespace
87
StartListeningForKeychainEvents()88 void CertDatabase::StartListeningForKeychainEvents() {
89 static base::NoDestructor<Notifier> notifier;
90 }
91
92 } // namespace net
93