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 return errSecWrongSecVersion;
61 }
62
63 if (info->pid == base::GetCurrentProcId()) {
64 // Ignore events generated by the current process, as the assumption is
65 // that they have already been handled. This may miss events that
66 // originated as a result of spawning native dialogs that allow the user
67 // to modify Keychain settings. However, err on the side of missing
68 // events rather than sending too many events.
69 return errSecSuccess;
70 }
71
72 switch (keychain_event) {
73 case kSecKeychainListChangedEvent:
74 CertDatabase::GetInstance()->NotifyObserversClientCertStoreChanged();
75 break;
76 case kSecTrustSettingsChangedEvent:
77 CertDatabase::GetInstance()->NotifyObserversTrustStoreChanged();
78 break;
79
80 default:
81 break;
82 }
83
84 return errSecSuccess;
85 }
86
87 } // namespace
88
StartListeningForKeychainEvents()89 void CertDatabase::StartListeningForKeychainEvents() {
90 static base::NoDestructor<Notifier> notifier;
91 }
92
93 } // namespace net
94