9#include <botan/certstor_macos.h>
11#include <botan/ber_dec.h>
12#include <botan/data_src.h>
13#include <botan/exceptn.h>
14#include <botan/pkix_types.h>
19#define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
20#include <CoreFoundation/CoreFoundation.h>
21#include <CoreServices/CoreServices.h>
34 explicit scoped_CFType(
T value) : m_value(value) {}
36 scoped_CFType(
const scoped_CFType<T>& rhs) =
delete;
38 scoped_CFType(scoped_CFType<T>&& rhs) : m_value(std::move(rhs.m_value)) { rhs.m_value =
nullptr; }
46 operator bool()
const {
return m_value !=
nullptr; }
48 void assign(
T value) {
49 BOTAN_ASSERT(m_value ==
nullptr,
"scoped_CFType was not set yet");
53 T& get() {
return m_value; }
55 const T& get()
const {
return m_value; }
66X509_DN normalize(
const X509_DN& dn) {
69 for(
const auto& rdn : dn.dn_info()) {
71 const auto oid = rdn.first;
72 auto str = rdn.second;
75 std::string normalized;
76 normalized.reserve(str.value().size());
77 for(
const char c : str.value()) {
80 normalized.push_back(::toupper(c));
81 }
else if(!normalized.empty() && normalized.back() !=
' ') {
83 normalized.push_back(c);
87 if(normalized.back() ==
' ') {
89 normalized.erase(normalized.end() - 1);
92 str = ASN1_String(normalized, str.tagging());
95 result.add_attribute(oid, str);
101std::vector<uint8_t> normalizeAndSerialize(
const X509_DN& dn) {
102 return normalize(dn).DER_encode();
105std::string
to_string(
const CFStringRef cfstring) {
106 const char* ccstr = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);
108 if(ccstr !=
nullptr) {
109 return std::string(ccstr);
112 auto utf16_pairs = CFStringGetLength(cfstring);
113 auto max_utf8_bytes = CFStringGetMaximumSizeForEncoding(utf16_pairs, kCFStringEncodingUTF8);
115 std::vector<char> cstr(max_utf8_bytes,
'\0');
116 auto result = CFStringGetCString(cfstring, cstr.data(), cstr.size(), kCFStringEncodingUTF8);
118 return (result) ? std::string(cstr.data()) : std::string();
121std::string
to_string(
const OSStatus status) {
122 scoped_CFType<CFStringRef> eCFString(SecCopyErrorMessageString(status,
nullptr));
126void check_success(
const OSStatus status,
const std::string context) {
127 if(errSecSuccess == status) {
131 throw Internal_Error(std::string(
"failed to " + context +
": " +
to_string(status)));
135void check_notnull(
const T& value,
const std::string context) {
140 throw Internal_Error(std::string(
"failed to ") + context);
150class Certificate_Store_MacOS_Impl {
152 static constexpr const char* system_roots =
"/System/Library/Keychains/SystemRootCertificates.keychain";
153 static constexpr const char* system_keychain =
"/Library/Keychains/System.keychain";
165 Query(Query&& other) =
default;
166 Query& operator=(Query&& other) =
default;
168 Query(
const Query& other) =
delete;
169 Query& operator=(
const Query& other) =
delete;
172 void addParameter(CFStringRef key, CFTypeRef value) {
173 m_keys.emplace_back(key);
174 m_values.emplace_back(value);
177 void addParameter(CFStringRef key, std::vector<uint8_t> value) {
178 const auto& data = m_data_store.emplace_back(std::move(value));
180 const auto& data_ref = m_data_refs.emplace_back(
181 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, data.data(), data.size(), kCFAllocatorNull));
182 check_notnull(data_ref,
"create CFDataRef of search object failed");
184 addParameter(key, data_ref.get());
192 scoped_CFType<CFDictionaryRef> prepare(
const CFArrayRef& keychains,
const SecPolicyRef& policy) {
193 addParameter(kSecClass, kSecClassCertificate);
194 addParameter(kSecReturnRef, kCFBooleanTrue);
195 addParameter(kSecMatchLimit, kSecMatchLimitAll);
196 addParameter(kSecMatchTrustedOnly, kCFBooleanTrue);
197 addParameter(kSecMatchSearchList, keychains);
198 addParameter(kSecMatchPolicy, policy);
202 auto query = scoped_CFType<CFDictionaryRef>(CFDictionaryCreate(kCFAllocatorDefault,
203 (
const void**)m_keys.data(),
204 (
const void**)m_values.data(),
206 &kCFTypeDictionaryKeyCallBacks,
207 &kCFTypeDictionaryValueCallBacks));
208 check_notnull(query,
"create search query");
214 using Data = std::vector<std::vector<uint8_t>>;
215 using DataRefs = std::vector<scoped_CFType<CFDataRef>>;
216 using Keys = std::vector<CFStringRef>;
217 using Values = std::vector<CFTypeRef>;
220 DataRefs m_data_refs;
226 Certificate_Store_MacOS_Impl() :
227 m_policy(SecPolicyCreateBasicX509()),
228 m_system_roots(
nullptr),
229 m_system_chain(
nullptr),
230 m_keychains(
nullptr) {
236 check_success(SecKeychainOpen(system_roots, &m_system_roots.get()),
"open system root certificates");
237 check_success(SecKeychainOpen(system_keychain, &m_system_chain.get()),
"open system keychain");
239 check_notnull(m_system_roots,
"open system root certificate chain");
240 check_notnull(m_system_chain,
"open system certificate chain");
244 std::array<const void*, 2> keychains{{m_system_roots.get(), m_system_chain.get()}};
247 CFArrayCreate(kCFAllocatorDefault, keychains.data(), keychains.size(), &kCFTypeArrayCallBacks));
248 check_notnull(m_keychains,
"initialize keychain array");
251 std::optional<X509_Certificate> findOne(Query query)
const {
252 query.addParameter(kSecMatchLimit, kSecMatchLimitOne);
254 scoped_CFType<CFTypeRef> result(
nullptr);
255 search(std::move(query), &result.get());
258 return readCertificate(result.get());
263 std::vector<X509_Certificate> findAll(Query query)
const {
264 query.addParameter(kSecMatchLimit, kSecMatchLimitAll);
266 scoped_CFType<CFArrayRef> result(
nullptr);
267 search(std::move(query), (CFTypeRef*)&result.get());
269 std::vector<X509_Certificate> output;
272 const auto count = CFArrayGetCount(result.get());
273 BOTAN_ASSERT(count > 0,
"certificate result list contains data");
275 for(
unsigned int i = 0; i < count; ++i) {
276 auto cert = CFArrayGetValueAtIndex(result.get(), i);
277 output.emplace_back(readCertificate(cert));
285 void search(Query query, CFTypeRef* result)
const {
286 scoped_CFType<CFDictionaryRef> fullQuery(query.prepare(keychains(), policy()));
288 auto status = SecItemCopyMatching(fullQuery.get(), result);
290 if(errSecItemNotFound == status) {
294 check_success(status,
"look up certificate");
295 check_notnull(result,
"look up certificate (invalid result value)");
301 X509_Certificate readCertificate(CFTypeRef
object)
const {
302 if(!
object || CFGetTypeID(
object) != SecCertificateGetTypeID()) {
303 throw Internal_Error(
"cannot convert CFTypeRef to SecCertificateRef");
306 auto cert =
static_cast<SecCertificateRef
>(
const_cast<void*
>(object));
308 scoped_CFType<CFDataRef> derData(SecCertificateCopyData(cert));
309 check_notnull(derData,
"read extracted certificate");
311 const auto data = CFDataGetBytePtr(derData.get());
312 const auto length = CFDataGetLength(derData.get());
314 DataSource_Memory ds(data, length);
315 return X509_Certificate(ds);
318 CFArrayRef keychains()
const {
return m_keychains.get(); }
320 SecPolicyRef policy()
const {
return m_policy.get(); }
323 scoped_CFType<SecPolicyRef> m_policy;
324 scoped_CFType<SecKeychainRef> m_system_roots;
325 scoped_CFType<SecKeychainRef> m_system_chain;
326 scoped_CFType<CFArrayRef> m_keychains;
345 const auto certificates = m_impl->findAll({});
347 std::vector<X509_DN> output;
348 std::transform(certificates.cbegin(),
350 std::back_inserter(output),
351 [](
const std::optional<X509_Certificate> cert) { return cert->subject_dn(); });
357 const std::vector<uint8_t>& key_id)
const {
358 Certificate_Store_MacOS_Impl::Query query;
359 query.addParameter(kSecAttrSubject, normalizeAndSerialize(subject_dn));
361 if(!key_id.empty()) {
362 query.addParameter(kSecAttrSubjectKeyID, key_id);
365 return m_impl->findOne(std::move(query));
369 const std::vector<uint8_t>& key_id)
const {
370 Certificate_Store_MacOS_Impl::Query query;
371 query.addParameter(kSecAttrSubject, normalizeAndSerialize(subject_dn));
373 if(!key_id.empty()) {
374 query.addParameter(kSecAttrSubjectKeyID, key_id);
377 return m_impl->findAll(std::move(query));
381 const std::vector<uint8_t>& key_hash)
const {
382 if(key_hash.size() != 20) {
383 throw Invalid_Argument(
"Certificate_Store_MacOS::find_cert_by_pubkey_sha1 invalid hash");
386 Certificate_Store_MacOS_Impl::Query query;
387 query.addParameter(kSecAttrPublicKeyHash, key_hash);
389 return m_impl->findOne(std::move(query));
393 const std::vector<uint8_t>& subject_hash)
const {
395 throw Not_Implemented(
"Certificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256");
#define BOTAN_ASSERT_EQUAL(expr1, expr2, assertion_made)
#define BOTAN_ASSERT(expr, assertion_made)
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
Certificate_Store_MacOS()
std::optional< X509_CRL > find_crl_for(const X509_Certificate &subject) const override
#define BOTAN_DIAGNOSTIC_POP
#define BOTAN_DIAGNOSTIC_PUSH
#define BOTAN_DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS
std::string to_string(ErrorType type)
Convert an ErrorType to string.