Debian Codegraph @

crt/aws-c-io/source/s2n/s2n_apple_keychain.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include "s2n_apple_keychain.h"
7
8 #include <aws/common/encoding.h>
9 #include <aws/common/error.h>
10 #include <aws/common/logging.h>
11 #include <aws/io/logging.h>
12 #include <aws/io/pem.h>
13
14 /* Check for USE_S2N needed to handle cross-compilation for Apple non-macOS platforms that can't use s2n-tls. */
15 #if defined(__APPLE__) && defined(USE_S2N)
16
17 # include <s2n.h>
18
19 # include <Security/Security.h>
20
21 static bool s_is_cert_trusted(const SecCertificateRef cert) {
22 SecPolicyRef policy = SecPolicyCreateBasicX509();
23 if (!policy) {
24 AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Failed to create a basic X509 SecPolicy");
25 return false;
26 }
27
28 bool is_trusted = false;
29
30 SecTrustRef trust = NULL;
31 OSStatus status = SecTrustCreateWithCertificates(cert, policy, &trust);
32 if (status == errSecSuccess) {
33 is_trusted = SecTrustEvaluateWithError(trust, NULL);
34 } else {
35 AWS_LOGF_TRACE(AWS_LS_IO_TLS, "Failed to create a trust object, status code %d", (int)status);
36 }
37
38 CFRelease(policy);
39 if (trust) {
40 CFRelease(trust);
41 }
42
43 return is_trusted;
44 }
45
46 static bool s_cert_has_basic_constraints_ca(SecCertificateRef cert) {
47 CFErrorRef error = NULL;
48 CFArrayRef keys = CFArrayCreate(NULL, (const void *[]){kSecOIDBasicConstraints}, 1, &kCFTypeArrayCallBacks);
49
50 CFDictionaryRef values = SecCertificateCopyValues(cert, keys, &error);
51 CFRelease(keys);
52 if (!values) {
53 if (error) {
54 CFRelease(error);
55 }
56 return false;
57 }
58
59 bool is_ca = false;
60 CFDictionaryRef bc_dict = CFDictionaryGetValue(values, kSecOIDBasicConstraints);
61 if (!bc_dict) {
62 goto done;
63 }
64
65 CFArrayRef bc_section = CFDictionaryGetValue(bc_dict, kSecPropertyKeyValue);
66 if (!bc_section) {
67 goto done;
68 }
69
70 CFIndex count = CFArrayGetCount(bc_section);
71 for (CFIndex i = 0; i < count; i++) {
72 CFDictionaryRef entry = CFArrayGetValueAtIndex(bc_section, i);
73 CFStringRef label = CFDictionaryGetValue(entry, kSecPropertyKeyLabel);
74 CFStringRef value = CFDictionaryGetValue(entry, kSecPropertyKeyValue);
75 if (label && value && CFStringCompare(label, CFSTR("Certificate Authority"), 0) == kCFCompareEqualTo &&
76 CFStringCompare(value, CFSTR("Yes"), 0) == kCFCompareEqualTo) {
77 is_ca = true;
78 break;
79 }
80 }
81
82 done:
83 CFRelease(values);
84 return is_ca;
85 }
86
87 /* This function loads trusted root CA certificates from the macOS searchable keychains into the s2n config.
88 * NOTE: Certificates from SystemRootCertificates.keychain are NOT processed here since s2n-tls will get them from the
89 * bundle system roots instead. */
90 void aws_tls_s2n_load_macos_keychain_root_cas(struct s2n_config *config, struct aws_allocator *alloc) {
91 CFMutableDictionaryRef query =
92 CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
93 CFDictionarySetValue(query, kSecClass, kSecClassCertificate);
94 CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll);
95 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
96
97 CFArrayRef results = NULL;
98 OSStatus status = SecItemCopyMatching(query, (CFTypeRef *)&results);
99 CFRelease(query);
100
101 if (status != errSecSuccess || !results) {
102 return;
103 }
104
105 /* Check all certificates in the keychains, and if they are trusted root CAs, add them to s2n trust store. */
106 CFIndex count = CFArrayGetCount(results);
107 for (CFIndex i = 0; i < count; i++) {
108 SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(results, i);
109
110 CFDataRef subject_data = SecCertificateCopyNormalizedSubjectSequence(cert);
111 CFDataRef issuer_data = SecCertificateCopyNormalizedIssuerSequence(cert);
112
113 if (!subject_data || !issuer_data) {
114 if (subject_data) {
115 CFRelease(subject_data);
116 }
117 if (issuer_data) {
118 CFRelease(issuer_data);
119 }
120 continue;
121 }
122
123 bool is_self_signed = CFEqual(subject_data, issuer_data);
124 bool is_ca = s_cert_has_basic_constraints_ca(cert);
125
126 CFRelease(subject_data);
127 CFRelease(issuer_data);
128
129 /* We check both conditions: a root CA is typically self-signed (subject == issuer), but some cross-signed CAs
130 * have a different issuer yet are still valid CAs per Basic Constraints. Either condition is sufficient to
131 * consider the certificate as a CA worth loading. */
132 if (!is_self_signed && !is_ca) {
133 continue;
134 }
135
136 /* Even if a certificate is a CA, it may have been explicitly distrusted by the user or system. Only proceed if
137 * macOS trust evaluation confirms the certificate is trusted. */
138 if (!s_is_cert_trusted(cert)) {
139 continue;
140 }
141
142 CFDataRef cert_data = SecCertificateCopyData(cert);
143 if (!cert_data) {
144 continue;
145 }
146
147 struct aws_byte_cursor der_cursor =
148 aws_byte_cursor_from_array(CFDataGetBytePtr(cert_data), (size_t)CFDataGetLength(cert_data));
149
150 CFStringRef summary = SecCertificateCopySubjectSummary(cert);
151 const char *cert_summary = "(unknown)";
152 char *name_buf = NULL;
153 if (summary) {
154 CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(summary), kCFStringEncodingUTF8) + 1;
155 name_buf = aws_mem_calloc(alloc, 1, (size_t)len);
156 if (name_buf && CFStringGetCString(summary, name_buf, len, kCFStringEncodingUTF8)) {
157 cert_summary = name_buf;
158 }
159 }
160
161 struct aws_string *pem_str = aws_der_cert_to_pem(alloc, der_cursor);
162 if (!pem_str) {
163 AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "Failed to convert DER to PEM for certificate '%s'", cert_summary);
164 } else if (s2n_config_add_pem_to_trust_store(config, (const char *)pem_str->bytes)) {
165 AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "Failed to add certificate '%s' to trust store", cert_summary);
166 } else {
167 AWS_LOGF_TRACE(AWS_LS_IO_TLS, "Successfully added certificate '%s' to s2n trust store", cert_summary);
168 }
169
170 aws_string_destroy(pem_str);
171 aws_mem_release(alloc, name_buf);
172 if (summary) {
173 CFRelease(summary);
174 }
175
176 CFRelease(cert_data);
177 }
178
179 CFRelease(results);
180 }
181
182 #endif /* defined(__APPLE__) && defined(USE_S2N) */