Botan 3.9.0
Crypto and TLS for C&
certstor_macos.cpp
Go to the documentation of this file.
1/*
2* Certificate Store
3* (C) 1999-2019 Jack Lloyd
4* (C) 2019-2020 René Meusel
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/certstor_macos.h>
10
11#include <botan/assert.h>
12#include <botan/ber_dec.h>
13#include <botan/data_src.h>
14#include <botan/exceptn.h>
15#include <botan/pkix_types.h>
16
17#include <algorithm>
18#include <array>
19
20#define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
21#include <CoreFoundation/CoreFoundation.h>
22#include <CoreServices/CoreServices.h>
23
24namespace Botan {
25
26namespace {
27
28/**
29 * Abstract RAII wrapper for CFTypeRef-style object handles
30 * All of those xxxRef types are eventually typedefs to void*
31 */
32template <typename T>
33class scoped_CFType {
34 public:
35 explicit scoped_CFType(T value) : m_value(value) {}
36
37 scoped_CFType(const scoped_CFType<T>& rhs) = delete;
38
39 scoped_CFType(scoped_CFType<T>&& rhs) : m_value(std::move(rhs.m_value)) { rhs.m_value = nullptr; }
40
41 ~scoped_CFType() {
42 if(m_value) {
43 CFRelease(m_value);
44 }
45 }
46
47 operator bool() const { return m_value != nullptr; }
48
49 void assign(T value) {
50 BOTAN_ASSERT(m_value == nullptr, "scoped_CFType was not set yet");
51 m_value = value;
52 }
53
54 T& get() { return m_value; }
55
56 const T& get() const { return m_value; }
57
58 private:
59 T m_value;
60};
61
62/**
63 * Apple's DN parser "normalizes" ASN1 'PrintableString' into upper-case values
64 * and strips leading, trailing as well as multiple white spaces.
65 * See: opensource.apple.com/source/Security/Security-55471/sec/Security/SecCertificate.c.auto.html
66 */
67X509_DN normalize(const X509_DN& dn) {
68 X509_DN result{};
69
70 for(const auto& [oid, str] : dn.dn_info()) {
71 if(str.tagging() == ASN1_Type::PrintableString) {
72 std::string normalized;
73 normalized.reserve(str.value().size());
74
75 for(const char c : str.value()) {
76 if(c != ' ') {
77 // store all 'normal' characters as upper case
78 normalized.push_back(std::toupper(c));
79 } else if(!normalized.empty() && normalized.back() != ' ') {
80 // remove leading and squash multiple white spaces
81 normalized.push_back(c);
82 }
83 }
84
85 if(!normalized.empty() && normalized.back() == ' ') {
86 // remove potential remaining single trailing white space char
87 normalized.pop_back();
88 }
89
90 result.add_attribute(oid, ASN1_String(normalized, str.tagging()));
91 } else {
92 result.add_attribute(oid, str);
93 }
94 }
95 return result;
96}
97
98std::vector<uint8_t> normalizeAndSerialize(const X509_DN& dn) {
99 return normalize(dn).DER_encode();
100}
101
102std::string to_string(const CFStringRef cfstring) {
103 const char* ccstr = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);
104
105 if(ccstr != nullptr) {
106 return std::string(ccstr);
107 }
108
109 auto utf16_pairs = CFStringGetLength(cfstring);
110 auto max_utf8_bytes = CFStringGetMaximumSizeForEncoding(utf16_pairs, kCFStringEncodingUTF8);
111
112 std::vector<char> cstr(max_utf8_bytes, '\0');
113 auto result = CFStringGetCString(cfstring, cstr.data(), cstr.size(), kCFStringEncodingUTF8);
114
115 return (result) ? std::string(cstr.data()) : std::string();
116}
117
118std::string to_string(const OSStatus status) {
119 scoped_CFType<CFStringRef> eCFString(SecCopyErrorMessageString(status, nullptr));
120 return to_string(eCFString.get());
121}
122
123void check_success(const OSStatus status, const std::string context) {
124 if(errSecSuccess == status) {
125 return;
126 }
127
128 throw Internal_Error(std::string("failed to " + context + ": " + to_string(status)));
129}
130
131template <typename T>
132void check_notnull(const T& value, const std::string context) {
133 if(value) {
134 return;
135 }
136
137 throw Internal_Error(std::string("failed to ") + context);
138}
139
140} // namespace
141
142/**
143 * Internal class implementation (i.e. Pimpl) to keep the required platform-
144 * dependent members of Certificate_Store_MacOS contained in this compilation
145 * unit.
146 */
147class Certificate_Store_MacOS_Impl {
148 private:
149 static constexpr const char* system_roots = "/System/Library/Keychains/SystemRootCertificates.keychain";
150 static constexpr const char* system_keychain = "/Library/Keychains/System.keychain";
151
152 public:
153 /**
154 * Wraps a list of search query parameters that are later passed into
155 * Apple's certifificate store API. The class provides some convenience
156 * functionality and handles the query paramenter's data lifetime.
157 */
158 class Query {
159 public:
160 Query() = default;
161 ~Query() = default;
162 Query(Query&& other) = default;
163 Query& operator=(Query&& other) = default;
164
165 Query(const Query& other) = delete;
166 Query& operator=(const Query& other) = delete;
167
168 public:
169 void addParameter(CFStringRef key, CFTypeRef value) {
170 m_keys.emplace_back(key);
171 m_values.emplace_back(value);
172 }
173
174 void addParameter(CFStringRef key, std::vector<uint8_t> value) {
175 const auto& data = m_data_store.emplace_back(std::move(value));
176
177 const auto& data_ref = m_data_refs.emplace_back(
178 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, data.data(), data.size(), kCFAllocatorNull));
179 check_notnull(data_ref, "create CFDataRef of search object failed");
180
181 addParameter(key, data_ref.get());
182 }
183
184 /**
185 * Amends the user-provided search query with generic filter rules
186 * for the associated system keychains and transforms it into a
187 * representation that can be passed to the Apple keychain API.
188 */
189 scoped_CFType<CFDictionaryRef> prepare(const CFArrayRef& keychains, const SecPolicyRef& policy) {
190 addParameter(kSecClass, kSecClassCertificate);
191 addParameter(kSecReturnRef, kCFBooleanTrue);
192 addParameter(kSecMatchLimit, kSecMatchLimitAll);
193 addParameter(kSecMatchTrustedOnly, kCFBooleanTrue);
194 addParameter(kSecMatchSearchList, keychains);
195 addParameter(kSecMatchPolicy, policy);
196
197 BOTAN_ASSERT_EQUAL(m_keys.size(), m_values.size(), "valid key-value pairs");
198
199 auto query = scoped_CFType<CFDictionaryRef>(CFDictionaryCreate(kCFAllocatorDefault,
200 (const void**)m_keys.data(),
201 (const void**)m_values.data(),
202 m_keys.size(),
203 &kCFTypeDictionaryKeyCallBacks,
204 &kCFTypeDictionaryValueCallBacks));
205 check_notnull(query, "create search query");
206
207 return query;
208 }
209
210 private:
211 using Data = std::vector<std::vector<uint8_t>>;
212 using DataRefs = std::vector<scoped_CFType<CFDataRef>>;
213 using Keys = std::vector<CFStringRef>;
214 using Values = std::vector<CFTypeRef>;
215
216 Data m_data_store; //! makes sure that data parameters are kept alive
217 DataRefs m_data_refs; //! keeps track of CFDataRef objects refering into \p m_data_store
218 Keys m_keys; //! ordered list of search parameter keys
219 Values m_values; //! ordered list of search parameter values
220 };
221
222 public:
223 Certificate_Store_MacOS_Impl() :
224 m_policy(SecPolicyCreateBasicX509()),
225 m_system_roots(nullptr),
226 m_system_chain(nullptr),
227 m_keychains(nullptr) {
230 // macOS 12.0 deprecates 'Custom keychain management', though the API still works.
231 // Ideas for a replacement can be found in the discussion of GH #3122:
232 // https://github.com/randombit/botan/pull/3122
233 check_success(SecKeychainOpen(system_roots, &m_system_roots.get()), "open system root certificates");
234 check_success(SecKeychainOpen(system_keychain, &m_system_chain.get()), "open system keychain");
236 check_notnull(m_system_roots, "open system root certificate chain");
237 check_notnull(m_system_chain, "open system certificate chain");
238
239 // m_keychains is merely a convenience list view into all open keychain
240 // objects. This list is required in prepareQuery().
241 std::array<const void*, 2> keychains{{m_system_roots.get(), m_system_chain.get()}};
242
243 m_keychains.assign(
244 CFArrayCreate(kCFAllocatorDefault, keychains.data(), keychains.size(), &kCFTypeArrayCallBacks));
245 check_notnull(m_keychains, "initialize keychain array");
246 }
247
248 std::optional<X509_Certificate> findOne(Query query) const {
249 query.addParameter(kSecMatchLimit, kSecMatchLimitOne);
250
251 scoped_CFType<CFTypeRef> result(nullptr);
252 search(std::move(query), &result.get());
253
254 if(result)
255 return readCertificate(result.get());
256 else
257 return std::nullopt;
258 }
259
260 std::vector<X509_Certificate> findAll(Query query) const {
261 query.addParameter(kSecMatchLimit, kSecMatchLimitAll);
262
263 scoped_CFType<CFArrayRef> result(nullptr);
264 search(std::move(query), (CFTypeRef*)&result.get());
265
266 std::vector<X509_Certificate> output;
267
268 if(result) {
269 const auto count = CFArrayGetCount(result.get());
270 BOTAN_ASSERT(count > 0, "certificate result list contains data");
271
272 for(unsigned int i = 0; i < count; ++i) {
273 auto cert = CFArrayGetValueAtIndex(result.get(), i);
274 output.emplace_back(readCertificate(cert));
275 }
276 }
277
278 return output;
279 }
280
281 protected:
282 void search(Query query, CFTypeRef* result) const {
283 scoped_CFType<CFDictionaryRef> fullQuery(query.prepare(keychains(), policy()));
284
285 auto status = SecItemCopyMatching(fullQuery.get(), result);
286
287 if(errSecItemNotFound == status) {
288 return; // no matches
289 }
290
291 check_success(status, "look up certificate");
292 check_notnull(result, "look up certificate (invalid result value)");
293 }
294
295 /**
296 * Convert a CFTypeRef object into a X509_Certificate
297 */
298 X509_Certificate readCertificate(CFTypeRef object) const {
299 if(!object || CFGetTypeID(object) != SecCertificateGetTypeID()) {
300 throw Internal_Error("cannot convert CFTypeRef to SecCertificateRef");
301 }
302
303 auto cert = static_cast<SecCertificateRef>(const_cast<void*>(object));
304
305 scoped_CFType<CFDataRef> derData(SecCertificateCopyData(cert));
306 check_notnull(derData, "read extracted certificate");
307
308 const auto data = CFDataGetBytePtr(derData.get());
309 const auto length = CFDataGetLength(derData.get());
310
311 DataSource_Memory ds(data, length);
312 return X509_Certificate(ds);
313 }
314
315 CFArrayRef keychains() const { return m_keychains.get(); }
316
317 SecPolicyRef policy() const { return m_policy.get(); }
318
319 private:
320 scoped_CFType<SecPolicyRef> m_policy;
321 scoped_CFType<SecKeychainRef> m_system_roots;
322 scoped_CFType<SecKeychainRef> m_system_chain;
323 scoped_CFType<CFArrayRef> m_keychains;
324};
325
326//
327// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
328//
329// Implementation of Certificate_Store interface ...
330//
331// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
332//
333
334Certificate_Store_MacOS::Certificate_Store_MacOS() : m_impl(std::make_shared<Certificate_Store_MacOS_Impl>()) {}
335
336std::vector<X509_DN> Certificate_Store_MacOS::all_subjects() const {
337 // Note: This fetches and parses all certificates in the trust store.
338 // Apple's API provides SecCertificateCopyNormalizedSubjectSequence
339 // which facilitates reading the certificate DN without parsing the
340 // entire certificate via X509_Certificate. However, this
341 // function applies the same DN "normalization" as stated above.
342 const auto certificates = m_impl->findAll({});
343
344 std::vector<X509_DN> output;
345 std::transform(certificates.cbegin(),
346 certificates.cend(),
347 std::back_inserter(output),
348 [](const std::optional<X509_Certificate> cert) { return cert->subject_dn(); });
349
350 return output;
351}
352
353std::optional<X509_Certificate> Certificate_Store_MacOS::find_cert(const X509_DN& subject_dn,
354 const std::vector<uint8_t>& key_id) const {
355 Certificate_Store_MacOS_Impl::Query query;
356 query.addParameter(kSecAttrSubject, normalizeAndSerialize(subject_dn));
357
358 if(!key_id.empty()) {
359 query.addParameter(kSecAttrSubjectKeyID, key_id);
360 }
361
362 return m_impl->findOne(std::move(query));
363}
364
365std::vector<X509_Certificate> Certificate_Store_MacOS::find_all_certs(const X509_DN& subject_dn,
366 const std::vector<uint8_t>& key_id) const {
367 Certificate_Store_MacOS_Impl::Query query;
368 query.addParameter(kSecAttrSubject, normalizeAndSerialize(subject_dn));
369
370 if(!key_id.empty()) {
371 query.addParameter(kSecAttrSubjectKeyID, key_id);
372 }
373
374 return m_impl->findAll(std::move(query));
375}
376
378 const std::vector<uint8_t>& key_hash) const {
379 if(key_hash.size() != 20) {
380 throw Invalid_Argument("Certificate_Store_MacOS::find_cert_by_pubkey_sha1 invalid hash");
381 }
382
383 Certificate_Store_MacOS_Impl::Query query;
384 query.addParameter(kSecAttrPublicKeyHash, key_hash);
385
386 return m_impl->findOne(std::move(query));
387}
388
390 const std::vector<uint8_t>& subject_hash) const {
391 BOTAN_UNUSED(subject_hash);
392 throw Not_Implemented("Certificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256");
393}
394
395std::optional<X509_CRL> Certificate_Store_MacOS::find_crl_for(const X509_Certificate& subject) const {
396 BOTAN_UNUSED(subject);
397 return {};
398}
399
400} // namespace Botan
#define BOTAN_DIAGNOSTIC_POP
Definition api.h:122
#define BOTAN_DIAGNOSTIC_PUSH
Definition api.h:119
#define BOTAN_DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS
Definition api.h:120
#define BOTAN_UNUSED
Definition assert.h:144
#define BOTAN_ASSERT_EQUAL(expr1, expr2, assertion_made)
Definition assert.h:88
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
std::optional< X509_Certificate > find_cert_by_pubkey_sha1(const std::vector< uint8_t > &key_hash) const override
std::optional< X509_Certificate > find_cert(const X509_DN &subject_dn, const std::vector< uint8_t > &key_id) const override
std::vector< X509_Certificate > find_all_certs(const X509_DN &subject_dn, const std::vector< uint8_t > &key_id) const override
std::vector< X509_DN > all_subjects() const override
std::optional< X509_Certificate > find_cert_by_raw_subject_dn_sha256(const std::vector< uint8_t > &subject_hash) const override
std::optional< X509_CRL > find_crl_for(const X509_Certificate &subject) const override
std::string to_string(ErrorType type)
Convert an ErrorType to string.
Definition exceptn.cpp:13