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