Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #include <arpa/inet.h>
26 : #include <chashmap.h>
27 : #include <errno.h>
28 : #include <fcntl.h>
29 : #include <internal/cascii.h>
30 : #include <internal/chashinsert.h>
31 : #include <internal/csock.h>
32 : #include <internal/ctls.h>
33 : #include <internal/test_helpers/ctls.h>
34 : #include <limits.h>
35 : #include <netinet/in.h>
36 : #include <openssl/bio.h>
37 : #include <openssl/err.h>
38 : #include <openssl/evp.h>
39 : #include <openssl/pem.h>
40 : #include <openssl/rsa.h>
41 : #include <openssl/ssl.h>
42 : #include <openssl/x509v3.h>
43 : #include <stdatomic.h>
44 : #include <stdint.h>
45 : #include <stdio.h>
46 : #include <stdlib.h>
47 : #include <string.h>
48 : #include <sys/socket.h>
49 : #include <sys/stat.h>
50 : #include <unistd.h>
51 : #if defined(__linux__)
52 : #include <sys/auxv.h>
53 : #endif
54 :
55 : // Process-wide self-signed root key
56 : //
57 : // The RSA key every self-signed certificate of this module is signed with,
58 : // made once per process on first need. It belongs to the process, not to a
59 : // context, so a once flag and its own mutex guard it; finalized stops a new
60 : // key after the exit handler freed it.
61 : static struct {
62 : EVP_PKEY *key;
63 : ccol__mutex mutex;
64 : ccol__once_flag once;
65 : bool finalized;
66 : } ctls_root_key_bundle = {.once = CCOL__ONCE_INIT};
67 :
68 : // Initializes the root key mutex; runs once through the bundle's once flag
69 : // before the first use of the key.
70 38 : static void ctls_root_key_globals_init(void) {
71 38 : if (ccol__mutex_init(ctls_root_key_bundle.mutex) != 0)
72 0 : ccol__fatal_err("ctls root key: failed to initialize mutex");
73 38 : }
74 :
75 : // The certificates and CRLs of the platform's default CA file, parsed once per
76 : // process at the first ctls_ctx_trust_system() and shared by every context
77 : // that trusts the system store. The list never changes once stored; each
78 : // store holds its own references, so freeing it at exit leaves live contexts
79 : // intact. The mutex makes concurrent first users parse once and orders every
80 : // read against the free at exit.
81 : static struct {
82 : STACK_OF(X509_INFO) * infos;
83 : ccol__mutex mutex;
84 : ccol__once_flag once;
85 : bool finalized;
86 : } ctls_system_ca_bundle = {.once = CCOL__ONCE_INIT};
87 :
88 : // Initializes the system CA mutex; runs once before the first use of the
89 : // list.
90 41 : static void ctls_system_ca_globals_init(void) {
91 41 : if (ccol__mutex_init(ctls_system_ca_bundle.mutex) != 0)
92 0 : ccol__fatal_err("ctls system CA bundle: failed to initialize mutex");
93 41 : }
94 :
95 : // Frees the root key and the parsed default CA file at exit, so valgrind finds
96 : // nothing of ours left. It's registered after OpenSSL's own cleanup, so it
97 : // runs first; a destructor would run too late. It sets finalized in both
98 : // bundles: Afterwards no root key is made, and a system-trust context parses
99 : // the file for itself. A caller holding a key reference keeps it.
100 38 : static void ctls_process_state_at_exit(void) {
101 38 : ccol__call_once(ctls_root_key_bundle.once, ctls_root_key_globals_init);
102 38 : ccol__mutex_lock(ctls_root_key_bundle.mutex);
103 38 : EVP_PKEY_free(ctls_root_key_bundle.key);
104 38 : ctls_root_key_bundle.key = NULL;
105 38 : ctls_root_key_bundle.finalized = true;
106 38 : ccol__mutex_unlock(ctls_root_key_bundle.mutex);
107 :
108 38 : ccol__call_once(ctls_system_ca_bundle.once, ctls_system_ca_globals_init);
109 38 : ccol__mutex_lock(ctls_system_ca_bundle.mutex);
110 38 : sk_X509_INFO_pop_free(ctls_system_ca_bundle.infos, X509_INFO_free);
111 38 : ctls_system_ca_bundle.infos = NULL;
112 38 : ctls_system_ca_bundle.finalized = true;
113 38 : ccol__mutex_unlock(ctls_system_ca_bundle.mutex);
114 38 : }
115 :
116 : // Makes the exit handler register only once.
117 : static ccol__once_flag ctls_process_state_exit_once = CCOL__ONCE_INIT;
118 :
119 : // Registers ctls_process_state_at_exit with atexit(); runs once.
120 41 : static void ctls_process_state_exit_register(void) {
121 41 : (void)atexit(ctls_process_state_at_exit);
122 41 : }
123 :
124 : // Registers the exit handler once. Call it only after an OpenSSL call has run,
125 : // so OpenSSL's cleanup was registered first and runs after ours.
126 5502 : static void ctls_process_state_exit_arm(void) {
127 5502 : ccol__call_once(ctls_process_state_exit_once,
128 : ctls_process_state_exit_register);
129 5502 : }
130 :
131 : #ifdef RUNNING_UNIT_TESTS
132 : // Tells whether the root key is still held, so the test suite can check that
133 : // the exit handler frees it.
134 1 : bool ctls__root_key_held_for_tests(void) {
135 1 : return __atomic_load_n(&ctls_root_key_bundle.key, __ATOMIC_SEQ_CST) != NULL;
136 : }
137 : #endif
138 :
139 : // Gives a reference to the process root key (free it with EVP_PKEY_free()),
140 : // making a 2048-bit RSA key under the bundle mutex on first use, for the
141 : // self-signed certificate code. It uses EVP_PKEY_CTX key generation, which
142 : // neither OpenSSL 3 nor LibreSSL deprecates. It gives NULL when generation
143 : // fails (the next call tries again) or after the exit handler ran, and arms
144 : // the exit handler when it makes the key.
145 650 : static EVP_PKEY *ctls_get_root_key(void) {
146 650 : ccol__call_once(ctls_root_key_bundle.once, ctls_root_key_globals_init);
147 650 : ccol__mutex_lock(ctls_root_key_bundle.mutex);
148 650 : if (!ctls_root_key_bundle.key && !ctls_root_key_bundle.finalized) {
149 3 : EVP_PKEY *key = NULL;
150 3 : EVP_PKEY_CTX *kctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
151 6 : if (!kctx || EVP_PKEY_keygen_init(kctx) <= 0 ||
152 6 : EVP_PKEY_CTX_set_rsa_keygen_bits(kctx, 2048) <= 0 ||
153 3 : EVP_PKEY_keygen(kctx, &key) <= 0) {
154 0 : EVP_PKEY_free(key);
155 0 : key = NULL;
156 : }
157 3 : EVP_PKEY_CTX_free(kctx);
158 3 : ctls_root_key_bundle.key = key;
159 3 : if (key) ctls_process_state_exit_arm();
160 : }
161 650 : EVP_PKEY *key = ctls_root_key_bundle.key;
162 650 : if (key && EVP_PKEY_up_ref(key) != 1) key = NULL;
163 650 : ccol__mutex_unlock(ctls_root_key_bundle.mutex);
164 650 : return key;
165 : }
166 :
167 : // Connection ex_data index
168 : //
169 : // The SSL ex_data index that maps an SSL object to its ctls_conn, for the SNI
170 : // and ALPN callbacks. idx starts at -1, the "not registered" sentinel and also
171 : // SSL_get_ex_new_index()'s failure value: 0 would read as registered and
172 : // share index 0 with SSL_set_app_data(), so other code holding the SSL could
173 : // read and overwrite our pointer.
174 : static struct {
175 : int idx;
176 : ccol__mutex mutex;
177 : ccol__once_flag once;
178 : } ctls_conn_ex_idx_bundle = {.idx = -1};
179 :
180 : #ifdef RUNNING_UNIT_TESTS
181 : // Counts the index lookups that took the mutex, for a white-box test.
182 : static long g_ctls_ex_idx_locked_calls_for_tests = 0;
183 : // Gives the locked lookup count, so a test can check that a registered index
184 : // is read without the lock.
185 2 : long ctls__ex_idx_locked_calls_for_tests(void) {
186 2 : return __atomic_load_n(&g_ctls_ex_idx_locked_calls_for_tests,
187 : __ATOMIC_RELAXED);
188 : }
189 : #endif
190 :
191 : // Initializes the ex_data index mutex; runs once.
192 37 : static void ctls_ex_idx_globals_init(void) {
193 37 : if (ccol__mutex_init(ctls_conn_ex_idx_bundle.mutex) != 0)
194 0 : ccol__fatal_err("ctls conn ex_data index: failed to initialize mutex");
195 37 : }
196 :
197 : // Gives the connection ex_data index, registering it on first use. Every
198 : // connection create and every SNI and ALPN callback asks for it, so a
199 : // registered index is read with one acquire load and no lock; only a call that
200 : // finds -1 takes the mutex, registers and publishes with a release store. It
201 : // gives -1 when registration fails, and the next call tries again.
202 1103 : static int ctls_conn_ex_idx(void) {
203 1103 : int idx = __atomic_load_n(&ctls_conn_ex_idx_bundle.idx, __ATOMIC_ACQUIRE);
204 1103 : if (__builtin_expect(idx >= 0, 1)) return idx;
205 : #ifdef RUNNING_UNIT_TESTS
206 37 : __atomic_fetch_add(&g_ctls_ex_idx_locked_calls_for_tests, 1,
207 : __ATOMIC_RELAXED);
208 : #endif
209 37 : ccol__call_once(ctls_conn_ex_idx_bundle.once, ctls_ex_idx_globals_init);
210 37 : ccol__mutex_lock(ctls_conn_ex_idx_bundle.mutex);
211 37 : idx = __atomic_load_n(&ctls_conn_ex_idx_bundle.idx, __ATOMIC_RELAXED);
212 37 : if (idx < 0) {
213 37 : idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
214 37 : __atomic_store_n(&ctls_conn_ex_idx_bundle.idx, idx, __ATOMIC_RELEASE);
215 : }
216 37 : ccol__mutex_unlock(ctls_conn_ex_idx_bundle.mutex);
217 37 : return idx;
218 : }
219 :
220 : // Socket BIO that never raises SIGPIPE
221 : //
222 : // The BIO_METHOD every connection reads and writes through. It acts like
223 : // OpenSSL's socket BIO but writes with send(2) and MSG_NOSIGNAL, so a write to
224 : // a gone peer (the close_notify of ctls_conn_destroy() included) fails with
225 : // EPIPE instead of killing the process, without touching the application's
226 : // signal disposition. Each BIO holds a count on the method (live_bios); the
227 : // exit destructor frees an unused method, or marks it retired so the last BIO
228 : // frees it, because a later destructor can still close a connection. The
229 : // mutex is never destroyed, since a release can come after the destructor.
230 : static struct {
231 : BIO_METHOD *meth;
232 : size_t live_bios;
233 : bool retired;
234 : ccol__mutex mutex;
235 : ccol__once_flag once;
236 : } ctls_sock_bio_bundle = {.once = CCOL__ONCE_INIT};
237 :
238 : // Initializes the socket BIO mutex; runs once.
239 49 : static void ctls_sock_bio_globals_init(void) {
240 49 : if (ccol__mutex_init(ctls_sock_bio_bundle.mutex) != 0)
241 0 : ccol__fatal_err("ctls socket BIO: failed to initialize mutex");
242 49 : }
243 :
244 : // The BIO flag that records end of file, read back through BIO_CTRL_EOF.
245 : // OpenSSL names it; on LibreSSL we use a bit no LibreSSL flag takes.
246 : #ifdef BIO_FLAGS_IN_EOF
247 : #define CTLS_SOCK_BIO_EOF BIO_FLAGS_IN_EOF
248 : #else
249 : #define CTLS_SOCK_BIO_EOF 0x800
250 : #endif
251 :
252 : // Follows the TLS record framing of the bytes the socket BIO hands up.
253 : // ctls_conn_read() uses it to tell whether a peer closed without close_notify
254 : // on a record boundary, and on LibreSSL (no SSL_has_pending())
255 : // ctls_conn_has_pending_input() uses it to tell whether the TLS layer holds a
256 : // partial record. With read-ahead off, the TLS layer holds part of a record
257 : // exactly while hdr_got isn't 0. A first header byte outside 20 to 24 means
258 : // the framing isn't one we follow, and the tracker gives up (lost), which
259 : // reports pending input from then on; that's always safe.
260 : typedef struct {
261 : uint32_t body_left;
262 : uint8_t hdr_got;
263 : uint8_t len_hi;
264 : bool lost;
265 : } ctls_rec_track;
266 :
267 : // Advances the record tracker rt over n bytes at p that the BIO just read:
268 : // counts header bytes, takes the body length from bytes 3 and 4, and skips
269 : // body bytes. It sets lost on a bad content type.
270 8296 : static void ctls_rec_track_feed(ctls_rec_track *rt, const char *p, int n) {
271 33127 : while (n > 0 && !rt->lost) {
272 24833 : if (rt->hdr_got < 5) {
273 20687 : uint8_t c = (uint8_t)*p++;
274 20687 : n--;
275 20687 : if (rt->hdr_got == 0 && (c < 20 || c > 24)) {
276 2 : rt->lost = true;
277 2 : return;
278 : }
279 20685 : if (rt->hdr_got == 3) rt->len_hi = c;
280 20685 : if (rt->hdr_got == 4) rt->body_left = (uint32_t)rt->len_hi << 8 | c;
281 20685 : if (++rt->hdr_got == 5 && rt->body_left == 0) rt->hdr_got = 0;
282 : } else {
283 4146 : uint32_t take = (uint32_t)n < rt->body_left ? (uint32_t)n : rt->body_left;
284 4146 : p += take;
285 4146 : n -= (int)take;
286 4146 : rt->body_left -= take;
287 4146 : if (rt->body_left == 0) rt->hdr_got = 0;
288 : }
289 : }
290 : }
291 :
292 : #ifdef RUNNING_UNIT_TESTS
293 : // Feeds count chunks of the given lens to a fresh tracker and gives whether it
294 : // would report pending input, so a test can drive record boundaries
295 : // directly.
296 0 : bool ctls__rec_track_pending_after_for_tests(const char *const *chunks,
297 : const int *lens, int count) {
298 0 : ctls_rec_track rt = {0};
299 0 : for (int i = 0; i < count; i++) ctls_rec_track_feed(&rt, chunks[i], lens[i]);
300 0 : return rt.hdr_got != 0 || rt.lost;
301 : }
302 : #endif
303 :
304 : // Gives the descriptor of BIO b, kept in its data pointer so a write needs no
305 : // control call.
306 12532 : static inline int ctls_sock_bio_fd(BIO *b) {
307 25058 : return (int)(intptr_t)BIO_get_data(b);
308 : }
309 :
310 : // The BIO write: Sends inl bytes with MSG_NOSIGNAL and sets the retry flag
311 : // when the socket would block. Gives the bytes sent or -1.
312 3142 : static int ctls_sock_bio_write(BIO *b, const char *in, int inl) {
313 3142 : errno = 0;
314 3142 : ssize_t n = send(ctls_sock_bio_fd(b), in, (size_t)inl, CCOL_MSG_NOSIGNAL);
315 3141 : int ret = n < 0 ? -1 : (int)n;
316 3141 : BIO_clear_retry_flags(b);
317 3142 : if (ret <= 0 && BIO_sock_should_retry(ret)) BIO_set_retry_write(b);
318 3142 : return ret;
319 : }
320 :
321 : // The BIO read: Receives up to outl bytes, sets the retry flag when the
322 : // socket would block or the EOF flag at end of stream, and feeds what it read
323 : // to the connection's record tracker, which the connection hands over through
324 : // the BIO's callback argument (this BIO has no callback). Gives the bytes
325 : // read, 0 at EOF or -1.
326 9390 : static int ctls_sock_bio_read(BIO *b, char *out, int outl) {
327 9390 : if (!out) return 0;
328 9390 : errno = 0;
329 9390 : ssize_t n = recv(ctls_sock_bio_fd(b), out, (size_t)outl, 0);
330 9387 : int ret = n < 0 ? -1 : (int)n;
331 9387 : BIO_clear_retry_flags(b);
332 9387 : if (ret <= 0) {
333 1086 : if (BIO_sock_should_retry(ret))
334 1012 : BIO_set_retry_read(b);
335 75 : else if (ret == 0)
336 27 : BIO_set_flags(b, CTLS_SOCK_BIO_EOF);
337 : }
338 9388 : ctls_rec_track *rt = (ctls_rec_track *)BIO_get_callback_arg(b);
339 9386 : if (ret > 0 && rt) ctls_rec_track_feed(rt, out, ret);
340 : return ret;
341 : }
342 :
343 : // The BIO puts: Writes the string str through ctls_sock_bio_write().
344 0 : static int ctls_sock_bio_puts(BIO *b, const char *str) {
345 0 : return ctls_sock_bio_write(b, str, (int)strlen(str));
346 : }
347 :
348 : // The BIO control call. It handles what OpenSSL's record layer and helpers
349 : // ask of a socket BIO: Setting and getting the fd and the close flag, the EOF
350 : // flag (how an abrupt close is told from a retryable read), and the poll
351 : // descriptors behind SSL_get_rpoll_descriptor(). Everything else gives 0.
352 67834 : static long ctls_sock_bio_ctrl(BIO *b, int cmd, long num, void *ptr) {
353 67834 : switch (cmd) {
354 811 : case BIO_C_SET_FD:
355 811 : if (BIO_get_shutdown(b) && BIO_get_init(b)) close(ctls_sock_bio_fd(b));
356 811 : BIO_clear_flags(b, ~0);
357 811 : BIO_set_data(b, (void *)(intptr_t)*(int *)ptr);
358 811 : BIO_set_shutdown(b, (int)num);
359 811 : BIO_set_init(b, 1);
360 811 : return 1;
361 0 : case BIO_C_GET_FD:
362 0 : if (!BIO_get_init(b)) return -1;
363 0 : if (ptr) *(int *)ptr = ctls_sock_bio_fd(b);
364 0 : return ctls_sock_bio_fd(b);
365 0 : case BIO_CTRL_GET_CLOSE:
366 0 : return BIO_get_shutdown(b);
367 0 : case BIO_CTRL_SET_CLOSE:
368 0 : BIO_set_shutdown(b, (int)num);
369 0 : return 1;
370 : case BIO_CTRL_DUP:
371 : case BIO_CTRL_FLUSH:
372 : return 1;
373 75 : case BIO_CTRL_EOF:
374 75 : return BIO_test_flags(b, CTLS_SOCK_BIO_EOF) != 0;
375 : #ifdef BIO_CTRL_GET_RPOLL_DESCRIPTOR
376 : case BIO_CTRL_GET_RPOLL_DESCRIPTOR:
377 : case BIO_CTRL_GET_WPOLL_DESCRIPTOR: {
378 : if (!BIO_get_init(b)) return 0;
379 : BIO_POLL_DESCRIPTOR *pd = (BIO_POLL_DESCRIPTOR *)ptr;
380 : pd->type = BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD;
381 : pd->value.fd = ctls_sock_bio_fd(b);
382 : return 1;
383 : }
384 : #endif
385 : default:
386 : return 0;
387 : }
388 : }
389 :
390 : // The BIO constructor: Starts with no fd and no flags.
391 811 : static int ctls_sock_bio_create(BIO *b) {
392 811 : BIO_set_init(b, 0);
393 811 : BIO_set_data(b, NULL);
394 811 : BIO_clear_flags(b, ~0);
395 811 : return 1;
396 : }
397 :
398 : // The BIO destructor: Closes the fd only when the BIO owns it (ours never do)
399 : // and clears the state.
400 809 : static int ctls_sock_bio_destroy(BIO *b) {
401 809 : if (!b) return 0;
402 809 : if (BIO_get_shutdown(b) && BIO_get_init(b)) close(ctls_sock_bio_fd(b));
403 809 : BIO_set_init(b, 0);
404 809 : BIO_clear_flags(b, ~0);
405 809 : return 1;
406 : }
407 :
408 : // Builds the BIO_METHOD with a new type index that carries
409 : // BIO_TYPE_DESCRIPTOR, so BIO_find_type() and SSL_get_fd() find it. Gives
410 : // NULL on failure.
411 37 : static BIO_METHOD *ctls_sock_bio_method_build(void) {
412 37 : int type = BIO_get_new_index();
413 37 : if (type == -1) return NULL;
414 37 : BIO_METHOD *m = BIO_meth_new(
415 : type | BIO_TYPE_SOURCE_SINK | BIO_TYPE_DESCRIPTOR, "ccol socket");
416 37 : if (!m) return NULL;
417 74 : if (!BIO_meth_set_write(m, ctls_sock_bio_write) ||
418 74 : !BIO_meth_set_read(m, ctls_sock_bio_read) ||
419 74 : !BIO_meth_set_puts(m, ctls_sock_bio_puts) ||
420 74 : !BIO_meth_set_ctrl(m, ctls_sock_bio_ctrl) ||
421 74 : !BIO_meth_set_create(m, ctls_sock_bio_create) ||
422 37 : !BIO_meth_set_destroy(m, ctls_sock_bio_destroy)) {
423 0 : BIO_meth_free(m);
424 0 : return NULL;
425 : }
426 : return m;
427 : }
428 :
429 : static void ctls_sock_bio_release(void);
430 :
431 : // Builds a socket BIO over fd that never closes fd, for a new connection. It
432 : // first asks ccol_sock_nosigpipe() to stop SIGPIPE on the socket where that's
433 : // per socket, and refuses the socket when it can't. It builds the method when
434 : // there's none (also after the destructor retired one) and charges one count
435 : // on it before unlocking, so the method can't be freed while BIO_new() uses
436 : // it. Gives NULL on failure, and then charges nothing.
437 817 : static BIO *ctls_sock_bio_new(int fd) {
438 817 : if (ccol_sock_nosigpipe(fd) != 0) return NULL;
439 817 : ccol__call_once(ctls_sock_bio_bundle.once, ctls_sock_bio_globals_init);
440 817 : ccol__mutex_lock(ctls_sock_bio_bundle.mutex);
441 817 : if (!ctls_sock_bio_bundle.meth) {
442 37 : ctls_sock_bio_bundle.meth = ctls_sock_bio_method_build();
443 37 : ctls_sock_bio_bundle.retired = false;
444 : }
445 817 : BIO_METHOD *meth = ctls_sock_bio_bundle.meth;
446 817 : if (meth) ctls_sock_bio_bundle.live_bios++;
447 817 : ccol__mutex_unlock(ctls_sock_bio_bundle.mutex);
448 817 : if (!meth) return NULL;
449 817 : BIO *bio = BIO_new(meth);
450 817 : if (!bio) {
451 6 : ctls_sock_bio_release();
452 6 : return NULL;
453 : }
454 811 : BIO_set_fd(bio, fd, BIO_NOCLOSE);
455 811 : return bio;
456 : }
457 :
458 : // Drops the method count of a BIO that SSL_free() already freed, and frees a
459 : // retired method when this was its last BIO.
460 815 : static void ctls_sock_bio_release(void) {
461 815 : ccol__mutex_lock(ctls_sock_bio_bundle.mutex);
462 815 : if (--ctls_sock_bio_bundle.live_bios == 0 && ctls_sock_bio_bundle.retired) {
463 0 : BIO_meth_free(ctls_sock_bio_bundle.meth);
464 0 : ctls_sock_bio_bundle.meth = NULL;
465 0 : ctls_sock_bio_bundle.retired = false;
466 : }
467 815 : ccol__mutex_unlock(ctls_sock_bio_bundle.mutex);
468 815 : }
469 :
470 : // Frees the BIO method at unload or exit when no BIO uses it, or marks it
471 : // retired so the last BIO frees it.
472 44 : __attribute__((destructor)) static void ctls_sock_bio_cleanup(void) {
473 44 : ccol__call_once(ctls_sock_bio_bundle.once, ctls_sock_bio_globals_init);
474 44 : ccol__mutex_lock(ctls_sock_bio_bundle.mutex);
475 44 : if (ctls_sock_bio_bundle.meth) {
476 32 : if (ctls_sock_bio_bundle.live_bios == 0) {
477 30 : BIO_meth_free(ctls_sock_bio_bundle.meth);
478 30 : ctls_sock_bio_bundle.meth = NULL;
479 : } else {
480 2 : ctls_sock_bio_bundle.retired = true;
481 : }
482 : }
483 44 : ccol__mutex_unlock(ctls_sock_bio_bundle.mutex);
484 44 : }
485 :
486 : #ifdef RUNNING_UNIT_TESTS
487 : // Gives the number of live socket BIOs, so a suite can check that every
488 : // connection gives its count back.
489 47 : size_t ctls__live_sock_bio_count_for_tests(void) {
490 47 : ccol__call_once(ctls_sock_bio_bundle.once, ctls_sock_bio_globals_init);
491 47 : ccol__mutex_lock(ctls_sock_bio_bundle.mutex);
492 47 : size_t n = ctls_sock_bio_bundle.live_bios;
493 47 : ccol__mutex_unlock(ctls_sock_bio_bundle.mutex);
494 47 : return n;
495 : }
496 : #endif
497 :
498 : // Internal types
499 : //
500 : // One ALPN registration: The protocol name, its selection callback with its
501 : // udata, and the cleanup for that udata.
502 : typedef struct ctls_alpn_entry {
503 : char *name;
504 : size_t name_len;
505 : ctls_alpn_selected_fn on_selected;
506 : void *udata;
507 : ctls_alpn_cleanup_fn on_cleanup;
508 : } ctls_alpn_entry;
509 :
510 : // One named certificate, dispatched by SNI: Its stored PEM data (or the
511 : // self-signed subject) and its own fully built SSL_CTX, rebuilt whenever the
512 : // trust store or the ALPN protocols of the context change.
513 : typedef struct ctls_named_cert {
514 : char *cert_pem;
515 : size_t cert_len;
516 : char *key_pem;
517 : size_t key_len;
518 : char *pk_password;
519 : bool self_signed;
520 : char *self_signed_name;
521 : // NULL until the first successful rebuild.
522 : SSL_CTX *built_ctx;
523 : } ctls_named_cert;
524 :
525 : // A TLS configuration, shared by its connections. lock guards the refcount
526 : // and every stored field; m_procs is an owned copy of the caller's procs, or
527 : // NULL. The
528 : // stored configuration (default certificate, named certificates, trust
529 : // bundles, verify flags, ALPN protocols) is the source every rebuild makes
530 : // the SSL_CTX objects from; ctx_default, the default SSL_CTX, is NULL
531 : // before the first build.
532 : struct ctls_ctx {
533 : size_t ref;
534 : ccol__mutex lock;
535 : ccol_memmgmt_procs *m_procs;
536 :
537 : // The default certificate, set by a server_name of NULL or "" in
538 : // ctls_ctx_cert_add().
539 : bool has_default_cert;
540 : char *default_cert_pem;
541 : size_t default_cert_len;
542 : char *default_key_pem;
543 : size_t default_key_len;
544 : char *default_pk_password;
545 : bool default_self_signed;
546 : char *default_self_signed_name;
547 :
548 : // Named certificates: A chmap from a lower-case hostname to a
549 : // ctls_named_cert *.
550 : chmap named_certs;
551 : bool sni_callback_installed;
552 :
553 : // The trusted CA bundles as PEM blobs, and the verify settings.
554 : char **trust_pems;
555 : size_t *trust_lens;
556 : size_t trust_count;
557 : size_t trust_cap;
558 : bool verify_default_store;
559 : bool verify_peer;
560 : // True when a server only asks for a client certificate; see
561 : // ctls_ctx_peer_cert_optional().
562 : bool peer_cert_optional;
563 :
564 : // The ALPN registrations, in registration order.
565 : ctls_alpn_entry *alpn;
566 : size_t alpn_count;
567 : size_t alpn_cap;
568 :
569 : SSL_CTX
570 : *ctx_default;
571 : };
572 :
573 : // One TLS connection. ctx is retained for the connection's life.
574 : struct ctls_conn {
575 : SSL *ssl;
576 : ctls_ctx *ctx;
577 : bool is_server;
578 : bool handshake_done;
579 : void *udata;
580 : const char *alpn_selected_name;
581 : size_t alpn_selected_len;
582 : // The connection's own copy of the agreed ALPN name (1 to 255 bytes), which
583 : // alpn_selected_name points at. It's a copy because tls->alpn is mutable: A
584 : // concurrent ctls_ctx_alpn_add() can free or move the stored names.
585 : char alpn_selected_buf[256];
586 : // The direction the last read or write that gave EWOULDBLOCK needs; see
587 : // ctls_conn_wants_write().
588 : bool last_io_wants_write;
589 : // Our references on every SSL_CTX this connection can reach: The default
590 : // context it was created on (pinned in the same ctx->lock section as
591 : // SSL_new()) and the named context an SNI dispatch installed (NULL when there
592 : // was none). OpenSSL holds its own references, but these make keeping them
593 : // alive our guarantee. Both are released under ctx->lock, which orders the
594 : // connection's last use before a rebuild frees the object; ThreadSanitizer
595 : // can't see OpenSSL's atomic refcount, so without the lock it reports a
596 : // race.
597 : SSL_CTX *pinned_ctx_default;
598 : SSL_CTX *pinned_sni_ctx;
599 : // True while the SSL owns a BIO that holds a count on the socket BIO method.
600 : bool holds_sock_bio;
601 : // The record framing the socket BIO follows.
602 : ctls_rec_track rec_track;
603 : // The DER encoding and RFC 2253 subject of the verified peer certificate,
604 : // made on first request from the context's allocator. peer_info_cert
605 : // (referenced) names the certificate they describe, so a renegotiated
606 : // certificate makes them again.
607 : X509 *peer_info_cert;
608 : unsigned char *peer_der;
609 : size_t peer_der_len;
610 : char *peer_subject;
611 : };
612 :
613 : #ifdef RUNNING_UNIT_TESTS
614 : // Counts the SSL_CTX pins held by live connections, so a suite can check that
615 : // a connection pins exactly what it can reach and that the total comes back
616 : // to its start. Several threads take and drop pins at once, so it's atomic;
617 : // tests read it after joining their threads.
618 : static _Atomic long ctls_live_conn_ctx_pins = 0;
619 :
620 : // Adds delta to the pin count when a connection takes or drops pins. A build
621 : // without tests compiles it to nothing.
622 1936 : static inline void ctls_account_ctx_pins(long delta) {
623 1936 : atomic_fetch_add_explicit(&ctls_live_conn_ctx_pins, delta,
624 : memory_order_relaxed);
625 967 : }
626 :
627 : // Gives the pin count, for the reference-balance tests.
628 52 : long ctls__live_conn_ctx_pin_count_for_tests(void) {
629 52 : return atomic_load_explicit(&ctls_live_conn_ctx_pins, memory_order_relaxed);
630 : }
631 : #else
632 : // The same accounting in a build without tests: It does nothing.
633 : static inline void ctls_account_ctx_pins(long delta) { (void)delta; }
634 : #endif
635 :
636 : // Small helpers
637 : //
638 : // Copies string s into a new buffer from mp, to store a caller's names and
639 : // passwords. NULL for a NULL s or a failed allocation.
640 1637 : static char *ctls_strdup(ccol_memmgmt_procs *mp, const char *s) {
641 1637 : if (!s) return NULL;
642 1637 : size_t len = strlen(s) + 1;
643 1637 : char *d = (char *)ccol__mem_alloc(mp, len);
644 1637 : if (!d) return NULL;
645 1631 : memcpy(d, s, len);
646 1631 : return d;
647 : }
648 :
649 : // Copies s in ASCII lower case, the form named certificates are stored and
650 : // looked up in; DNS names ignore case (RFC 4343) whatever the locale. NULL
651 : // for a NULL s or a failed allocation.
652 6539 : static char *ctls_strdup_lower(ccol_memmgmt_procs *mp, const char *s) {
653 6539 : if (!s) return NULL;
654 6539 : size_t len = strlen(s) + 1;
655 6539 : char *d = (char *)ccol__mem_alloc(mp, len);
656 6539 : if (!d) return NULL;
657 68993 : for (size_t i = 0; i < len; ++i)
658 62473 : d[i] = (char)ccol_ascii_tolower((unsigned char)s[i]);
659 : return d;
660 : }
661 :
662 : // The largest file ctls_read_file() reads. PEM files are a few KB (a full CA
663 : // bundle a few hundred), so 16 MB refuses a path that names a log or a disk
664 : // image fast instead of allocating gigabytes. It's an off_t like st_size.
665 : #define CTLS_MAX_PEM_FILE_SIZE ((off_t)16 * 1024 * 1024)
666 :
667 : // Reads the whole file at path into a new buffer from mp, for certificates,
668 : // keys and CA bundles. It gives ccol_success with *out_data and *out_len set,
669 : // ccol_not_enough_memory when the buffer can't be allocated, or
670 : // ccol_http_tls_cert_load_failed for a missing or unreadable file, one that
671 : // isn't a regular file, an empty or oversized one, or a short read; *why (when
672 : // not NULL) gets the reason. The open uses O_NONBLOCK, so a FIFO or a device
673 : // never blocks (the caller may hold a lock), and the type check runs on the
674 : // descriptor, so a swapped path can't pass it. O_NOCTTY and O_CLOEXEC keep a
675 : // terminal and a spawned child out of it.
676 13415 : static ccol_retval ctls_read_file(ccol_memmgmt_procs *mp, const char *path,
677 : char **out_data, size_t *out_len,
678 : char **why) {
679 13415 : *out_data = NULL;
680 13415 : *out_len = 0;
681 13415 : if (why) *why = "file is missing or unreadable";
682 13415 : if (!path) return ccol_http_tls_cert_load_failed;
683 13415 : int fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOCTTY);
684 13415 : if (fd < 0) return ccol_http_tls_cert_load_failed;
685 13410 : struct stat st;
686 13410 : if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
687 3 : if (why) *why = "path does not name a regular file";
688 3 : close(fd);
689 3 : return ccol_http_tls_cert_load_failed;
690 : }
691 13407 : if (st.st_size <= 0) {
692 2 : close(fd);
693 2 : return ccol_http_tls_cert_load_failed;
694 : }
695 13405 : if (st.st_size > CTLS_MAX_PEM_FILE_SIZE) {
696 1 : if (why) *why = "file is larger than the 16 MB limit for a PEM artefact";
697 1 : close(fd);
698 1 : return ccol_http_tls_cert_load_failed;
699 : }
700 13404 : size_t sz = (size_t)st.st_size;
701 13404 : char *buf = (char *)ccol__mem_alloc(mp, sz);
702 13404 : if (!buf) {
703 17 : if (why) *why = "out of memory while reading the file";
704 17 : close(fd);
705 17 : return ccol_not_enough_memory;
706 : }
707 : size_t got = 0;
708 26774 : while (got < sz) {
709 13387 : ssize_t n = read(fd, buf + got, sz - got);
710 13387 : if (n < 0 && errno == EINTR) continue;
711 13387 : if (n <= 0) break;
712 13387 : got += (size_t)n;
713 : }
714 13387 : close(fd);
715 13387 : if (got != sz) {
716 0 : ccol__mem_free(mp, buf);
717 0 : return ccol_http_tls_cert_load_failed;
718 : }
719 13387 : *out_data = buf;
720 13387 : *out_len = sz;
721 13387 : return ccol_success;
722 : }
723 :
724 : // Default CA file of the platform
725 : //
726 : // Gives getenv(name), or NULL in a setuid or setgid process, so a privileged
727 : // program's caller can't pick its trust anchors (as OpenSSL does for
728 : // SSL_CERT_FILE and SSL_CERT_DIR).
729 5508 : static const char *ctls_trusted_getenv(const char *name) {
730 : #if defined(__linux__)
731 5508 : if (getauxval(AT_SECURE) != 0) return NULL;
732 : #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
733 : defined(__NetBSD__) || defined(__DragonFly__)
734 : if (issetugid()) return NULL;
735 : #else
736 : if (getuid() != geteuid() || getgid() != getegid()) return NULL;
737 : #endif
738 5508 : return getenv(name);
739 : }
740 :
741 : #ifdef RUNNING_UNIT_TESTS
742 : // Counts the parses of the default CA file, for a white-box test.
743 : static atomic_long g_ctls_system_ca_parses_for_tests;
744 :
745 : // Gives the parse count, so a test can check the file is parsed once.
746 2 : long ctls__system_ca_parses_for_tests(void) {
747 2 : return atomic_load(&g_ctls_system_ca_parses_for_tests);
748 : }
749 : #endif
750 :
751 : // Parses the PEM buffer (pem, len) into its certificates and CRLs, for trust
752 : // bundles and the default CA file. OpenSSL 3 can lose an allocation without
753 : // ERR_R_MALLOC_FAILURE: It stops part way with an error queued, keeps a
754 : // certificate whose key failed to decode, or gives NULL. A block it can't read
755 : // looks the same, so in any of those cases the buffer is parsed again; the
756 : // same result twice is kept, a different one counts as out of memory. It sets
757 : // *oom and gives NULL when an allocation is known to have failed. *complete
758 : // (may be NULL) tells whether the kept result had no error and every key
759 : // decoded, so a caller knows not to cache a short one. The thread's error
760 : // queue is empty on return.
761 : static STACK_OF(X509_INFO) *
762 8425 : ctls_parse_infos(const char *pem, size_t len, bool *oom, bool *complete) {
763 8425 : STACK_OF(X509_INFO) *infos = NULL;
764 8425 : bool incomplete = false;
765 8425 : int first_count = 0, first_undecoded = 0;
766 9405 : for (int attempt = 0; attempt < 2; ++attempt) {
767 9405 : sk_X509_INFO_pop_free(infos, X509_INFO_free);
768 9405 : infos = NULL;
769 9405 : BIO *bio = BIO_new_mem_buf(pem, (int)len);
770 9405 : if (!bio) {
771 8 : *oom = true;
772 8 : break;
773 : }
774 9397 : infos = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
775 9397 : BIO_free(bio);
776 9397 : incomplete = false;
777 9397 : bool malloc_failure = false;
778 9397 : unsigned long e;
779 12222 : while ((e = ERR_get_error()) != 0) {
780 2825 : incomplete = true;
781 5650 : if (ERR_GET_REASON(e) == ERR_R_MALLOC_FAILURE) malloc_failure = true;
782 : }
783 9397 : int count = infos ? sk_X509_INFO_num(infos) : -1;
784 9397 : int undecoded = 0;
785 55823 : for (int i = 0; i < count; ++i) {
786 46426 : X509 *x = sk_X509_INFO_value(infos, i)->x509;
787 46426 : if (x && !X509_get0_pubkey(x)) undecoded++;
788 : }
789 9397 : ERR_clear_error();
790 9397 : if (!infos || undecoded > 0) incomplete = true;
791 8418 : if (!incomplete) break;
792 980 : if (attempt == 0) {
793 : first_count = count;
794 : first_undecoded = undecoded;
795 0 : } else if (malloc_failure || count != first_count ||
796 : undecoded != first_undecoded) {
797 0 : *oom = true;
798 : }
799 : }
800 8425 : ERR_clear_error();
801 8425 : if (*oom) {
802 8 : sk_X509_INFO_pop_free(infos, X509_INFO_free);
803 8 : return NULL;
804 : }
805 8417 : if (complete) *complete = !incomplete;
806 : return infos;
807 : }
808 :
809 : // Reads the default CA file (SSL_CERT_FILE when the environment may be
810 : // trusted, else the built-in path) through ctls_read_file(), so the
811 : // descriptor is close-on-exec, and parses it for ctls_store_add_system_file().
812 : // It gives NULL when the file is missing, unreadable, not regular or holds no
813 : // certificate, and also when an allocation failed, which it marks in *oom so
814 : // the caller doesn't fall back to the directory. *cacheable tells whether the
815 : // result may be kept for the process. It counts the parse for tests and
816 : // clears the error queue.
817 5506 : static STACK_OF(X509_INFO) * ctls_system_ca_load(bool *oom, bool *cacheable) {
818 5506 : const char *path = ctls_trusted_getenv(X509_get_default_cert_file_env());
819 5506 : if (!path || !*path) path = X509_get_default_cert_file();
820 5506 : char *pem = NULL;
821 5506 : size_t len = 0;
822 5506 : ccol_retval read_rv = ctls_read_file(NULL, path, &pem, &len, NULL);
823 5506 : if (read_rv != ccol_success) {
824 0 : if (read_rv == ccol_not_enough_memory) *oom = true;
825 0 : return NULL;
826 : }
827 5506 : STACK_OF(X509_INFO) *infos = ctls_parse_infos(pem, len, oom, cacheable);
828 5506 : ccol__default_mem_free(pem);
829 5506 : if (*oom) {
830 5 : sk_X509_INFO_pop_free(infos, X509_INFO_free);
831 5 : return NULL;
832 : }
833 : #ifdef RUNNING_UNIT_TESTS
834 5501 : atomic_fetch_add(&g_ctls_system_ca_parses_for_tests, 1);
835 : #endif
836 5501 : bool any_cert = false;
837 43042 : for (int i = 0; infos && i < sk_X509_INFO_num(infos); ++i)
838 37541 : if (sk_X509_INFO_value(infos, i)->x509) any_cert = true;
839 5501 : if (!any_cert) {
840 2 : sk_X509_INFO_pop_free(infos, X509_INFO_free);
841 2 : infos = NULL;
842 : }
843 5501 : ERR_clear_error();
844 5501 : return infos;
845 : }
846 :
847 : // Adds the certificate and the CRL of info to store, each with its own
848 : // reference, while a store is built. An object the store already holds counts
849 : // as added (X509_R_CERT_ALREADY_IN_HASH_TABLE is popped off the queue), so a
850 : // CA in two bundles never fails a rebuild. Any other failure is an allocation
851 : // failure: It gives false and leaves the reason queued.
852 382202 : static bool ctls_store_add_info(X509_STORE *store, X509_INFO *info) {
853 1146590 : for (int pass = 0; pass < 2; ++pass) {
854 764396 : if (pass == 0 ? !info->x509 : !info->crl) continue;
855 383660 : ERR_set_mark();
856 382201 : int added = pass == 0 ? X509_STORE_add_cert(store, info->x509)
857 383660 : : X509_STORE_add_crl(store, info->crl);
858 383660 : if (added == 1) {
859 383652 : ERR_pop_to_mark();
860 383652 : continue;
861 : }
862 8 : unsigned long e = ERR_peek_last_error();
863 8 : if (ERR_GET_LIB(e) != ERR_LIB_X509 ||
864 8 : ERR_GET_REASON(e) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
865 : return false;
866 : }
867 0 : ERR_pop_to_mark();
868 : }
869 : return true;
870 : }
871 :
872 : // Adds every entry of infos to store with ctls_store_add_info(); false when an
873 : // add fails.
874 10397 : static bool ctls_store_add_infos(X509_STORE *store,
875 : STACK_OF(X509_INFO) * infos) {
876 392591 : for (int i = 0; i < sk_X509_INFO_num(infos); ++i)
877 382202 : if (!ctls_store_add_info(store, sk_X509_INFO_value(infos, i))) return false;
878 : return true;
879 : }
880 :
881 : // Adds the default CA file to store, for a context that trusts the system
882 : // store. The file is parsed once per process into ctls_system_ca_bundle
883 : // (under its mutex); a failed or possibly short load isn't kept, so the next
884 : // call reads the file again, and after the exit handler nothing is kept. It
885 : // gives 1 when the certificates went in, 0 when there's no usable file, and
886 : // -1 when an add failed or the load ran out of memory (then *oom is set).
887 8344 : static int ctls_store_add_system_file(X509_STORE *store, bool *oom) {
888 8344 : ccol__call_once(ctls_system_ca_bundle.once, ctls_system_ca_globals_init);
889 8344 : ccol__mutex_lock(ctls_system_ca_bundle.mutex);
890 8344 : STACK_OF(X509_INFO) *infos = ctls_system_ca_bundle.infos;
891 8344 : bool owned = false;
892 8344 : if (!infos) {
893 5506 : bool cacheable = false;
894 5506 : infos = ctls_system_ca_load(oom, &cacheable);
895 5506 : if (!infos && *oom) {
896 5 : ccol__mutex_unlock(ctls_system_ca_bundle.mutex);
897 5 : return -1;
898 : }
899 5499 : if (infos && cacheable && !ctls_system_ca_bundle.finalized) {
900 5499 : ctls_system_ca_bundle.infos = infos;
901 5499 : ctls_process_state_exit_arm();
902 : } else {
903 : owned = true;
904 : }
905 : }
906 13838 : int rv = 0;
907 8339 : if (infos) rv = ctls_store_add_infos(store, infos) ? 1 : -1;
908 8339 : if (owned) sk_X509_INFO_pop_free(infos, X509_INFO_free);
909 8339 : ccol__mutex_unlock(ctls_system_ca_bundle.mutex);
910 8339 : return rv;
911 : }
912 :
913 : #ifdef RUNNING_UNIT_TESTS
914 : // Drops the cached default CA file, so the next system-trust context reads it
915 : // again (after a test changed SSL_CERT_FILE, for example).
916 5666 : void ctls__system_ca_forget_for_tests(void) {
917 5666 : ccol__call_once(ctls_system_ca_bundle.once, ctls_system_ca_globals_init);
918 5666 : ccol__mutex_lock(ctls_system_ca_bundle.mutex);
919 5666 : sk_X509_INFO_pop_free(ctls_system_ca_bundle.infos, X509_INFO_free);
920 5666 : ctls_system_ca_bundle.infos = NULL;
921 5666 : ccol__mutex_unlock(ctls_system_ca_bundle.mutex);
922 5666 : }
923 :
924 : // Gives the certificates in the trust store of ctx's default SSL_CTX, or -1
925 : // before the first build, so a test can check that a bundle went in whole.
926 : // It reads under ctx->lock; OpenSSL 3.3 gives a copy of the store's objects,
927 : // older versions the store's own stack.
928 5449 : int ctls__trusted_cert_count_for_tests(ctls_ctx *ctx) {
929 5449 : if (!ctx) return -1;
930 5449 : int n = -1;
931 5449 : ccol__mutex_lock(ctx->lock);
932 16347 : X509_STORE *store =
933 5449 : ctx->ctx_default ? SSL_CTX_get_cert_store(ctx->ctx_default) : NULL;
934 5449 : if (store) {
935 : #if OPENSSL_VERSION_NUMBER >= 0x30300000L && !defined(LIBRESSL_VERSION_NUMBER)
936 : STACK_OF(X509_OBJECT) *objs = X509_STORE_get1_objects(store);
937 : #else
938 5449 : STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
939 : #endif
940 5449 : if (objs) {
941 : n = 0;
942 27245 : for (int i = 0; i < sk_X509_OBJECT_num(objs); ++i)
943 21796 : if (X509_OBJECT_get_type(sk_X509_OBJECT_value(objs, i)) == X509_LU_X509)
944 21796 : n++;
945 : }
946 : #if OPENSSL_VERSION_NUMBER >= 0x30300000L && !defined(LIBRESSL_VERSION_NUMBER)
947 : sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
948 : #endif
949 : }
950 5449 : ccol__mutex_unlock(ctx->lock);
951 5449 : return n;
952 : }
953 : #endif
954 :
955 : // Installs the platform trust anchors on store for ctls_apply_trust(): The
956 : // default CA file when it exists and holds a certificate, otherwise OpenSSL's
957 : // hashed-directory lookup (SSL_CERT_DIR when the environment may be trusted,
958 : // else the built-in directory), whose files OpenSSL opens during handshakes.
959 : // We read SSL_CERT_DIR ourselves because LibreSSL's default lookup ignores the
960 : // environment. A missing directory isn't an error, as in
961 : // SSL_CTX_set_default_verify_paths(). It gives false and may set *oom when the
962 : // file or the lookup can't be added.
963 8344 : static bool ctls_store_add_system_trust(X509_STORE *store, bool *oom) {
964 8344 : int from_file = ctls_store_add_system_file(store, oom);
965 8344 : if (from_file < 0) return false;
966 8332 : if (from_file > 0) return true;
967 2 : X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
968 2 : if (!lookup) return false;
969 2 : const char *dir = ctls_trusted_getenv(X509_get_default_cert_dir_env());
970 2 : if (!dir || !*dir) dir = X509_get_default_cert_dir();
971 2 : (void)X509_LOOKUP_add_dir(lookup, dir, X509_FILETYPE_PEM);
972 2 : return true;
973 : }
974 :
975 : // The password a PEM key callback hands to OpenSSL.
976 : typedef struct ctls_pw_ctx {
977 : const char *password;
978 : } ctls_pw_ctx;
979 :
980 : // The PEM password callback: Copies the password from u (a ctls_pw_ctx) into
981 : // buf of size bytes, truncated to fit with its NUL, so an encrypted key can be
982 : // read. It gives the password length, or 0 when there's none.
983 8 : static int ctls_pem_passwd_cb(char *buf, int size, int rwflag, void *u) {
984 8 : (void)rwflag;
985 8 : const ctls_pw_ctx *p = (const ctls_pw_ctx *)u;
986 8 : if (!p || !p->password || !size) return 0;
987 7 : size_t plen = strlen(p->password);
988 7 : int len = (size <= (int)plen) ? (size - 1) : (int)plen;
989 7 : if (len < 0) len = 0;
990 7 : memcpy(buf, p->password, (size_t)len);
991 7 : buf[len] = 0;
992 7 : return len;
993 : }
994 :
995 : // Self-signed certificate generation
996 : //
997 : // Builds a certificate whose subject and issuer are O and CN = server_name,
998 : // valid for 180 days, with a serial from a process-wide counter, holding the
999 : // public half of root_key and signed with it (SHA-512). It serves development
1000 : // and tests that run without certificate files. NULL on failure.
1001 325 : static X509 *ctls_create_self_signed_with(const char *server_name,
1002 : EVP_PKEY *root_key) {
1003 325 : X509 *cert = X509_new();
1004 325 : if (!cert) return NULL;
1005 325 : static _Atomic uint32_t counter = 0;
1006 325 : uint32_t serial = ++counter;
1007 325 : if (!ASN1_INTEGER_set(X509_get_serialNumber(cert), (long)serial)) {
1008 0 : X509_free(cert);
1009 0 : return NULL;
1010 : }
1011 650 : if (!X509_gmtime_adj(X509_get_notBefore(cert), 0) ||
1012 325 : !X509_gmtime_adj(X509_get_notAfter(cert), 15552000L)) {
1013 0 : X509_free(cert);
1014 0 : return NULL;
1015 : }
1016 325 : if (!X509_set_pubkey(cert, root_key)) {
1017 0 : X509_free(cert);
1018 0 : return NULL;
1019 : }
1020 325 : X509_NAME *s = X509_get_subject_name(cert);
1021 325 : size_t name_len = strlen(server_name);
1022 325 : if (!X509_NAME_add_entry_by_txt(s, "O", MBSTRING_ASC,
1023 : (const unsigned char *)server_name,
1024 325 : (int)name_len, -1, 0) ||
1025 325 : !X509_NAME_add_entry_by_txt(s, "CN", MBSTRING_ASC,
1026 : (const unsigned char *)server_name,
1027 : (int)name_len, -1, 0)) {
1028 0 : X509_free(cert);
1029 0 : return NULL;
1030 : }
1031 325 : if (!X509_set_issuer_name(cert, s)) {
1032 0 : X509_free(cert);
1033 0 : return NULL;
1034 : }
1035 325 : if (!X509_sign(cert, root_key, EVP_sha512())) {
1036 0 : X509_free(cert);
1037 0 : return NULL;
1038 : }
1039 : return cert;
1040 : }
1041 :
1042 : // Builds a self-signed certificate for server_name with the process root key,
1043 : // taking and dropping a reference on the key. NULL when there's no key or the
1044 : // build fails.
1045 325 : static X509 *ctls_create_self_signed(const char *server_name) {
1046 325 : EVP_PKEY *root_key = ctls_get_root_key();
1047 325 : if (!root_key) return NULL;
1048 325 : X509 *cert = ctls_create_self_signed_with(server_name, root_key);
1049 325 : EVP_PKEY_free(root_key);
1050 325 : return cert;
1051 : }
1052 :
1053 : // SSL_CTX (re)building
1054 : //
1055 : // The session id context of every SSL_CTX of this module. One constant for all
1056 : // of them keeps resumption working across an SNI dispatch: SSL_set_SSL_CTX()
1057 : // swaps the connection's session id context only when it equals the old
1058 : // context's, and here they're always equal. Sessions never cross ctls_ctx
1059 : // objects anyway, since the cache and ticket keys belong to the default
1060 : // SSL_CTX of one build.
1061 : static const unsigned char ctls_session_id_context[] = "ccol-ctls";
1062 :
1063 : // Applies the settings every SSL_CTX of this module carries, and nothing
1064 : // else: Partial writes, moving write buffers, TLS 1.2 as the minimum, no
1065 : // compression and the session id context. Moving buffers let a server retry
1066 : // a write from a copy of the unsent tail (OpenSSL otherwise fails with "bad
1067 : // write retry"). Without the session id context, a server with
1068 : // SSL_VERIFY_PEER fails every resumed handshake instead of doing a full one,
1069 : // which would break every client's second connection. Gives false on
1070 : // failure.
1071 35567 : static bool ctls_apply_base_settings(SSL_CTX *ctx) {
1072 35567 : if (!ctx) return false;
1073 35567 : SSL_CTX_set_mode(
1074 : ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1075 35567 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
1076 35567 : SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
1077 35567 : return SSL_CTX_set_session_id_context(
1078 : ctx, ctls_session_id_context,
1079 35567 : (unsigned int)(sizeof(ctls_session_id_context) - 1)) == 1;
1080 : }
1081 :
1082 : // Installs a certificate chain and its key on ctx while it's built: A
1083 : // self-signed certificate for self_signed_name with the root key, or the PEM
1084 : // cert_pem chain (leaf first; a chain certificate that fails to attach fails
1085 : // the whole call) with the PEM key_pem, decrypted with pk_password. No
1086 : // certificate configured is fine. It finishes with SSL_CTX_check_private_key(),
1087 : // because the install calls don't reliably report a mismatched pair, and a
1088 : // context built with one would fail every handshake without a word. Gives
1089 : // false on failure.
1090 35567 : static bool ctls_apply_cert(SSL_CTX *ctx, const char *cert_pem, size_t cert_len,
1091 : const char *key_pem, size_t key_len,
1092 : const char *pk_password, bool self_signed,
1093 : const char *self_signed_name) {
1094 35567 : if (self_signed) {
1095 325 : X509 *cert = ctls_create_self_signed(self_signed_name);
1096 325 : if (!cert) return false;
1097 325 : EVP_PKEY *root_key = ctls_get_root_key();
1098 650 : bool ok = root_key && SSL_CTX_use_certificate(ctx, cert) == 1 &&
1099 325 : SSL_CTX_use_PrivateKey(ctx, root_key) == 1;
1100 325 : EVP_PKEY_free(root_key);
1101 325 : X509_free(cert);
1102 325 : return ok && SSL_CTX_check_private_key(ctx) == 1;
1103 : }
1104 35242 : if (!cert_pem || !key_pem) return true;
1105 :
1106 16004 : ctls_pw_ctx pw = {.password = pk_password};
1107 16004 : bool key_ok = false;
1108 16004 : BIO *kbio = BIO_new_mem_buf(key_pem, (int)key_len);
1109 16004 : if (kbio) {
1110 16003 : EVP_PKEY *pkey =
1111 16003 : PEM_read_bio_PrivateKey(kbio, NULL, ctls_pem_passwd_cb, &pw);
1112 16003 : if (pkey) {
1113 16003 : key_ok = SSL_CTX_use_PrivateKey(ctx, pkey) == 1;
1114 16003 : EVP_PKEY_free(pkey);
1115 : }
1116 16003 : BIO_free(kbio);
1117 : }
1118 16004 : if (!key_ok) return false;
1119 :
1120 16003 : bool cert_ok = false;
1121 16003 : BIO *cbio = BIO_new_mem_buf(cert_pem, (int)cert_len);
1122 16003 : if (cbio) {
1123 16001 : STACK_OF(X509_INFO) *inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
1124 16001 : if (inf) {
1125 31970 : for (int i = 0; i < sk_X509_INFO_num(inf); ++i) {
1126 15985 : X509_INFO *tmp = sk_X509_INFO_value(inf, i);
1127 15985 : if (tmp->x509) {
1128 15985 : if (i == 0) {
1129 15985 : cert_ok = SSL_CTX_use_certificate(ctx, tmp->x509) == 1;
1130 0 : } else if (SSL_CTX_add1_chain_cert(ctx, tmp->x509) != 1) {
1131 15985 : cert_ok = false;
1132 : }
1133 : }
1134 : }
1135 15985 : sk_X509_INFO_pop_free(inf, X509_INFO_free);
1136 : }
1137 16001 : BIO_free(cbio);
1138 : }
1139 16028 : return cert_ok && SSL_CTX_check_private_key(ctx) == 1;
1140 : }
1141 :
1142 : // Installs tls's trust store and verify mode on ctx, for the default SSL_CTX
1143 : // and every named one alike, so an SNI dispatch never lands on a weaker mode.
1144 : // A server requires a client certificate (SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
1145 : // unless peer_cert_optional is set; clients ignore that flag. When a bundle
1146 : // holds a CRL, the store gets X509_V_FLAG_CRL_CHECK and _CRL_CHECK_ALL, as
1147 : // nginx ssl_crl does. Every bundle was accepted earlier, so a parse that
1148 : // gives nothing or a failed add is an allocation failure that fails the
1149 : // build; a store missing anchors or a CRL would quietly weaken verification.
1150 : // It reads tls's stored trust fields under the caller's tls->lock and sets
1151 : // *oom when the default CA file couldn't be loaded for lack of memory.
1152 32046 : static bool ctls_apply_trust(SSL_CTX *ctx, ctls_ctx *tls, bool *oom) {
1153 32046 : if (tls->trust_count == 0 && !tls->verify_default_store) return true;
1154 10392 : X509_STORE *store = X509_STORE_new();
1155 10392 : if (!store) return false;
1156 10387 : SSL_CTX_set_cert_store(ctx, store);
1157 10387 : SSL_CTX_set_verify(ctx,
1158 10387 : tls->peer_cert_optional
1159 : ? SSL_VERIFY_PEER
1160 : : SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1161 : NULL);
1162 10387 : if (tls->verify_default_store && !ctls_store_add_system_trust(store, oom))
1163 : return false;
1164 : bool any_crl = false;
1165 12434 : for (size_t i = 0; i < tls->trust_count; ++i) {
1166 2061 : STACK_OF(X509_INFO) *inf =
1167 2061 : ctls_parse_infos(tls->trust_pems[i], tls->trust_lens[i], oom, NULL);
1168 2061 : if (!inf) return false;
1169 7018 : for (int j = 0; j < sk_X509_INFO_num(inf); ++j)
1170 4958 : if (sk_X509_INFO_value(inf, j)->crl) any_crl = true;
1171 2060 : bool added = ctls_store_add_infos(store, inf);
1172 2060 : sk_X509_INFO_pop_free(inf, X509_INFO_free);
1173 2060 : if (!added) return false;
1174 : }
1175 11831 : if (any_crl &&
1176 1458 : X509_STORE_set_flags(
1177 : store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL) != 1)
1178 : return false;
1179 : return true;
1180 : }
1181 :
1182 : // The server ALPN selection callback, run inside SSL_accept(). It picks the
1183 : // first protocol of the client's offer (in, inlen) that tls registered and
1184 : // points *out at a copy in conn's own buffer, because OpenSSL reads *out after
1185 : // the callback and tls->alpn may be freed or moved by a concurrent
1186 : // ctls_ctx_alpn_add(). It reads tls->alpn under tls->lock, after resolving
1187 : // conn through the ex_data index. With no match it gives NOACK and records
1188 : // nothing, so a caller never believes the peer agreed to a protocol it never
1189 : // acknowledged. on_selected fires later from ctls_record_alpn(), after
1190 : // SSL_accept() returns, so a callback can destroy its own connection.
1191 120 : static int ctls_alpn_select_cb(SSL *ssl, const unsigned char **out,
1192 : unsigned char *outlen, const unsigned char *in,
1193 : unsigned int inlen, void *arg) {
1194 120 : ctls_ctx *tls = (ctls_ctx *)arg;
1195 120 : ctls_conn *conn = (ctls_conn *)SSL_get_ex_data(ssl, ctls_conn_ex_idx());
1196 120 : if (!conn) return SSL_TLSEXT_ERR_NOACK;
1197 :
1198 120 : ccol__mutex_lock(tls->lock);
1199 120 : if (tls->alpn_count == 0) {
1200 0 : ccol__mutex_unlock(tls->lock);
1201 0 : return SSL_TLSEXT_ERR_NOACK;
1202 : }
1203 120 : ctls_alpn_entry *matched = NULL;
1204 120 : const unsigned char *p = in;
1205 120 : const unsigned char *end = in + inlen;
1206 240 : while (p < end && !matched) {
1207 120 : uint8_t l = p[0];
1208 120 : const unsigned char *name = p + 1;
1209 120 : p += (size_t)l + 1;
1210 121 : for (size_t i = 0; i < tls->alpn_count; ++i) {
1211 120 : ctls_alpn_entry *e = &tls->alpn[i];
1212 120 : if (e->name_len == l && memcmp(e->name, name, l) == 0) {
1213 : matched = e;
1214 : break;
1215 : }
1216 : }
1217 : }
1218 120 : if (!matched) {
1219 1 : ccol__mutex_unlock(tls->lock);
1220 1 : return SSL_TLSEXT_ERR_NOACK;
1221 : }
1222 :
1223 119 : memcpy(conn->alpn_selected_buf, matched->name, matched->name_len);
1224 119 : conn->alpn_selected_buf[matched->name_len] = '\0';
1225 119 : conn->alpn_selected_name = conn->alpn_selected_buf;
1226 119 : conn->alpn_selected_len = matched->name_len;
1227 119 : ccol__mutex_unlock(tls->lock);
1228 :
1229 119 : *out = (const unsigned char *)conn->alpn_selected_buf;
1230 119 : *outlen = (unsigned char)conn->alpn_selected_len;
1231 119 : return SSL_TLSEXT_ERR_OK;
1232 : }
1233 :
1234 : // Installs tls's ALPN protocols on ctx: The server selection callback, and the
1235 : // client offer list in wire format. It sets *oom when its own allocation
1236 : // fails (that leaves nothing on the error queue); the only other failure,
1237 : // inside SSL_CTX_set_alpn_protos(), is an allocation too. Gives false on
1238 : // failure.
1239 32027 : static bool ctls_apply_alpn(SSL_CTX *ctx, ctls_ctx *tls, bool *oom) {
1240 32027 : if (tls->alpn_count == 0) return true;
1241 : size_t wire_len = 0;
1242 13182 : for (size_t i = 0; i < tls->alpn_count; ++i)
1243 6597 : wire_len += tls->alpn[i].name_len + 1;
1244 13170 : unsigned char *wire =
1245 6585 : (unsigned char *)ccol__mem_alloc(tls->m_procs, wire_len);
1246 6585 : if (!wire) {
1247 21 : *oom = true;
1248 21 : return false;
1249 : }
1250 : size_t pos = 0;
1251 13140 : for (size_t i = 0; i < tls->alpn_count; ++i) {
1252 6576 : wire[pos++] = (unsigned char)tls->alpn[i].name_len;
1253 6576 : memcpy(wire + pos, tls->alpn[i].name, tls->alpn[i].name_len);
1254 6576 : pos += tls->alpn[i].name_len;
1255 : }
1256 6564 : int failed = SSL_CTX_set_alpn_protos(ctx, wire, (unsigned int)wire_len);
1257 6564 : ccol__mem_free(tls->m_procs, wire);
1258 6564 : if (failed != 0) {
1259 1 : *oom = true;
1260 1 : return false;
1261 : }
1262 6563 : SSL_CTX_set_alpn_select_cb(ctx, ctls_alpn_select_cb, tls);
1263 6563 : return true;
1264 : }
1265 :
1266 : // Looks up one registered pattern (lower case) in tls->named_certs and gives
1267 : // its built SSL_CTX, or NULL when it isn't registered. The caller holds
1268 : // tls->lock.
1269 4881 : static SSL_CTX *ctls_named_ctx_for_pattern(ctls_ctx *tls, char *pattern) {
1270 4881 : cmap_pair kp = {.ptr = pattern, .size = strlen(pattern) + 1};
1271 4881 : cmap_pair vp;
1272 4881 : if (chashmap_get_elem_ref(tls->named_certs, &kp, &vp) != ccol_success)
1273 : return NULL;
1274 3312 : ctls_named_cert *nc;
1275 3312 : memcpy(&nc, vp.ptr, sizeof(nc));
1276 3312 : return nc->built_ctx;
1277 : }
1278 :
1279 : // Resolves a ClientHello's SNI name to the SSL_CTX of a named certificate, or
1280 : // NULL. An exact match always wins over the one-label "*." wildcard, so a
1281 : // host with its own certificate never gets the wildcard's whatever the order
1282 : // of registration. Each half is one probe: The only wildcard candidate is
1283 : // "*." plus everything after the first dot, written in place over the copy.
1284 : // The caller holds tls->lock.
1285 6787 : static SSL_CTX *ctls_find_named_ctx(ctls_ctx *tls, const char *sni_name) {
1286 6787 : if (!tls->named_certs || !sni_name || !*sni_name) return NULL;
1287 4090 : char *lower = ctls_strdup_lower(tls->m_procs, sni_name);
1288 4090 : if (!lower) return NULL;
1289 4090 : SSL_CTX *found = ctls_named_ctx_for_pattern(tls, lower);
1290 4090 : if (!found) {
1291 791 : char *dot = strchr(lower, '.');
1292 791 : if (dot && dot > lower && dot[1] != '\0') {
1293 791 : char *pattern = dot - 1;
1294 791 : pattern[0] = '*';
1295 791 : pattern[1] = '.';
1296 791 : found = ctls_named_ctx_for_pattern(tls, pattern);
1297 : }
1298 : }
1299 4090 : ccol__mem_free(tls->m_procs, lower);
1300 : return found;
1301 : }
1302 :
1303 : // Records our reference on installed, the SSL_CTX an SNI dispatch put on
1304 : // conn, dropping the reference an earlier dispatch left (a TLS 1.3
1305 : // HelloRetryRequest runs the callback twice). The caller holds ctx->lock in
1306 : // the same section as the lookup and SSL_set_SSL_CTX(), so no rebuild can
1307 : // free the object in between. The pin makes "every context a live connection
1308 : // can reach is one we hold" a property of ours, not of OpenSSL's internals.
1309 146 : static void ctls_conn_pin_sni_ctx(ctls_conn *conn, SSL_CTX *installed) {
1310 146 : SSL_CTX_up_ref(installed);
1311 146 : if (conn->pinned_sni_ctx) {
1312 0 : SSL_CTX_free(conn->pinned_sni_ctx);
1313 0 : ctls_account_ctx_pins(-1);
1314 : }
1315 146 : conn->pinned_sni_ctx = installed;
1316 146 : ctls_account_ctx_pins(1);
1317 146 : }
1318 :
1319 : // The SNI callback, run during SSL_accept(): Moves the connection onto the
1320 : // SSL_CTX of the named certificate that matches the ClientHello's name, so
1321 : // each host gets its own certificate. conn is resolved before taking
1322 : // tls->lock, which keeps the ex_data mutex and that lock independent. The
1323 : // lookup, SSL_set_SSL_CTX() and the pin happen in one tls->lock section,
1324 : // because a concurrent rebuild frees replaced contexts under that lock. A
1325 : // failed install leaves the connection on its old context and pins nothing.
1326 : // An unknown name keeps the default certificate.
1327 160 : static int ctls_servername_cb(SSL *ssl, int *ad, void *arg) {
1328 160 : (void)ad;
1329 160 : ctls_ctx *tls = (ctls_ctx *)arg;
1330 160 : ctls_conn *conn = (ctls_conn *)SSL_get_ex_data(ssl, ctls_conn_ex_idx());
1331 159 : const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1332 159 : if (!name) return SSL_TLSEXT_ERR_OK;
1333 158 : ccol__mutex_lock(tls->lock);
1334 159 : SSL_CTX *matched = ctls_find_named_ctx(tls, name);
1335 159 : if (matched && SSL_set_SSL_CTX(ssl, matched) && conn)
1336 146 : ctls_conn_pin_sni_ctx(conn, matched);
1337 159 : ccol__mutex_unlock(tls->lock);
1338 159 : return SSL_TLSEXT_ERR_OK;
1339 : }
1340 :
1341 : // Builds one fully configured SSL_CTX from scratch (base settings, an optional
1342 : // certificate, tls's trust store and ALPN protocols), for the default context
1343 : // and for each named certificate, so SSL_set_SSL_CTX() can switch to any of
1344 : // them as a whole. It gives NULL on failure, and the caller keeps the old
1345 : // object. A failed SSL_CTX_new() or trust store counts as out of memory
1346 : // (*oom), since nothing from the caller can make them fail and OpenSSL 3
1347 : // often reports no ERR_R_MALLOC_FAILURE.
1348 32516 : static SSL_CTX *ctls_build_one_ctx(ctls_ctx *tls, const char *cert_pem,
1349 : size_t cert_len, const char *key_pem,
1350 : size_t key_len, const char *pk_password,
1351 : bool self_signed,
1352 : const char *self_signed_name, bool *oom) {
1353 32516 : SSL_CTX *ctx = SSL_CTX_new(TLS_method());
1354 32516 : if (!ctx) {
1355 445 : *oom = true;
1356 445 : return NULL;
1357 : }
1358 64142 : if (!ctls_apply_base_settings(ctx) ||
1359 32071 : !ctls_apply_cert(ctx, cert_pem, cert_len, key_pem, key_len, pk_password,
1360 : self_signed, self_signed_name)) {
1361 25 : SSL_CTX_free(ctx);
1362 25 : return NULL;
1363 : }
1364 32046 : if (!ctls_apply_trust(ctx, tls, oom)) {
1365 19 : *oom = true;
1366 19 : SSL_CTX_free(ctx);
1367 19 : return NULL;
1368 : }
1369 32027 : if (!ctls_apply_alpn(ctx, tls, oom)) {
1370 22 : SSL_CTX_free(ctx);
1371 22 : return NULL;
1372 : }
1373 : return ctx;
1374 : }
1375 :
1376 : // Gives the result of a failed rebuild and empties the thread's error queue:
1377 : // ccol_not_enough_memory when oom is set or the queue holds
1378 : // ERR_R_MALLOC_FAILURE, ccol_http_tls_cert_load_failed otherwise.
1379 525 : static ccol_retval ctls_rebuild_failure(bool oom) {
1380 525 : unsigned long e;
1381 1156 : while ((e = ERR_get_error()) != 0) {
1382 1262 : if (ERR_GET_REASON(e) == ERR_R_MALLOC_FAILURE) oom = true;
1383 : }
1384 525 : return oom ? ccol_not_enough_memory : ccol_http_tls_cert_load_failed;
1385 : }
1386 :
1387 : // Rebuilds the default SSL_CTX and every named certificate's SSL_CTX from the
1388 : // configuration tls stores; every call that changes a context runs it under
1389 : // tls->lock. It never patches an SSL_CTX in place: Everything is built first
1390 : // and committed together (old contexts freed, new ones installed), so a
1391 : // failure leaves every old object serving as before. A caller that changed
1392 : // the stored configuration first must restore it on failure, or the next
1393 : // successful rebuild would commit what this one refused. It gives
1394 : // ccol_success, ccol_not_enough_memory or ccol_http_tls_cert_load_failed, and
1395 : // the error queue is empty on return.
1396 25023 : static ccol_retval ctls_ctx_rebuild_locked(ctls_ctx *tls) {
1397 25023 : ERR_clear_error();
1398 25023 : bool oom = false;
1399 25023 : SSL_CTX *new_default = ctls_build_one_ctx(
1400 : tls, tls->has_default_cert ? tls->default_cert_pem : NULL,
1401 : tls->default_cert_len,
1402 25023 : tls->has_default_cert ? tls->default_key_pem : NULL, tls->default_key_len,
1403 25023 : tls->default_pk_password, tls->default_self_signed,
1404 25023 : tls->default_self_signed_name, &oom);
1405 25023 : if (!new_default) return ctls_rebuild_failure(oom);
1406 :
1407 24567 : if (tls->named_certs && chashmap_size(tls->named_certs) > 0) {
1408 4278 : SSL_CTX_set_tlsext_servername_callback(new_default, ctls_servername_cb);
1409 4278 : SSL_CTX_set_tlsext_servername_arg(new_default, tls);
1410 : }
1411 :
1412 24567 : size_t named_count = tls->named_certs ? chashmap_size(tls->named_certs) : 0;
1413 24567 : SSL_CTX **new_named_ctxs = NULL;
1414 24567 : ctls_named_cert **new_named_entries = NULL;
1415 24567 : if (named_count > 0) {
1416 4278 : new_named_ctxs = (SSL_CTX **)ccol__mem_alloc(
1417 : tls->m_procs, named_count * sizeof(SSL_CTX *));
1418 4278 : new_named_entries = (ctls_named_cert **)ccol__mem_alloc(
1419 : tls->m_procs, named_count * sizeof(ctls_named_cert *));
1420 4278 : if (!new_named_ctxs || !new_named_entries) {
1421 14 : ccol__mem_free(tls->m_procs, new_named_ctxs);
1422 14 : ccol__mem_free(tls->m_procs, new_named_entries);
1423 14 : SSL_CTX_free(new_default);
1424 69 : return ctls_rebuild_failure(true);
1425 : }
1426 4264 : ccol_chmap_walk walk = {0};
1427 4264 : const void *key_bytes;
1428 4264 : const void *val_bytes;
1429 4264 : size_t i = 0;
1430 4264 : bool ok = true;
1431 11702 : while (i < named_count && ccol_chmap_walk_next(tls->named_certs, &walk,
1432 : &key_bytes, &val_bytes)) {
1433 7493 : ctls_named_cert *nc;
1434 7493 : memcpy(&nc, val_bytes, sizeof(nc));
1435 14986 : SSL_CTX *built = ctls_build_one_ctx(
1436 7493 : tls, nc->cert_pem, nc->cert_len, nc->key_pem, nc->key_len,
1437 7493 : nc->pk_password, nc->self_signed, nc->self_signed_name, &oom);
1438 7493 : if (!built) {
1439 55 : ok = false;
1440 55 : break;
1441 : }
1442 7438 : new_named_ctxs[i] = built;
1443 7438 : new_named_entries[i] = nc;
1444 7438 : ++i;
1445 : }
1446 4264 : if (i != named_count) ok = false;
1447 4264 : if (!ok) {
1448 88 : for (size_t j = 0; j < i; ++j) SSL_CTX_free(new_named_ctxs[j]);
1449 55 : ccol__mem_free(tls->m_procs, new_named_ctxs);
1450 55 : ccol__mem_free(tls->m_procs, new_named_entries);
1451 55 : SSL_CTX_free(new_default);
1452 55 : return ctls_rebuild_failure(oom);
1453 : }
1454 : }
1455 :
1456 24498 : if (tls->ctx_default) SSL_CTX_free(tls->ctx_default);
1457 24498 : tls->ctx_default = new_default;
1458 31903 : for (size_t i = 0; i < named_count; ++i) {
1459 7405 : if (new_named_entries[i]->built_ctx)
1460 4998 : SSL_CTX_free(new_named_entries[i]->built_ctx);
1461 7405 : new_named_entries[i]->built_ctx = new_named_ctxs[i];
1462 : }
1463 24498 : ccol__mem_free(tls->m_procs, new_named_ctxs);
1464 24498 : ccol__mem_free(tls->m_procs, new_named_entries);
1465 24498 : ERR_clear_error();
1466 24498 : return ccol_success;
1467 : }
1468 :
1469 : // ctls_ctx construction and mutation
1470 : //
1471 : // Frees a named certificate entry: Its PEM data, password, self-signed name
1472 : // and built SSL_CTX, through tls's allocator.
1473 2441 : static void ctls_named_cert_destroy(ctls_ctx *tls, ctls_named_cert *nc) {
1474 2441 : if (!nc) return;
1475 2441 : ccol__mem_free(tls->m_procs, nc->cert_pem);
1476 2441 : ccol__mem_free(tls->m_procs, nc->key_pem);
1477 2441 : ccol__mem_free(tls->m_procs, nc->pk_password);
1478 2441 : ccol__mem_free(tls->m_procs, nc->self_signed_name);
1479 2441 : if (nc->built_ctx) SSL_CTX_free(nc->built_ctx);
1480 2441 : ccol__mem_free(tls->m_procs, nc);
1481 : }
1482 :
1483 : // Tells whether the PEM key (decrypted with pk_password) matches the leaf
1484 : // certificate at the start of the PEM chain, when ctls_ctx_cert_add() accepts
1485 : // the input. The check happens before anything is stored, because a bad pair
1486 : // that got stored would fail every later rebuild of the context. A key it
1487 : // can't read leaves its reason on the error queue, so the queue is cleared,
1488 : // or a later SSL_get_error() on an unrelated connection would read it.
1489 3509 : static bool ctls_cert_key_pair_matches(const char *cert_pem, size_t cert_len,
1490 : const char *key_pem, size_t key_len,
1491 : const char *pk_password) {
1492 3509 : ctls_pw_ctx pw = {.password = pk_password};
1493 3509 : BIO *kbio = BIO_new_mem_buf(key_pem, (int)key_len);
1494 3509 : if (!kbio) return false;
1495 3506 : EVP_PKEY *pkey = PEM_read_bio_PrivateKey(kbio, NULL, ctls_pem_passwd_cb, &pw);
1496 3506 : BIO_free(kbio);
1497 3506 : if (!pkey) {
1498 2 : ERR_clear_error();
1499 2 : return false;
1500 : }
1501 3504 : bool matches = false;
1502 3504 : BIO *cbio = BIO_new_mem_buf(cert_pem, (int)cert_len);
1503 3504 : if (cbio) {
1504 3504 : STACK_OF(X509_INFO) *inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
1505 3504 : if (inf) {
1506 10500 : X509_INFO *leaf =
1507 3500 : sk_X509_INFO_num(inf) > 0 ? sk_X509_INFO_value(inf, 0) : NULL;
1508 3500 : if (leaf && leaf->x509)
1509 3499 : matches = X509_check_private_key(leaf->x509, pkey) == 1;
1510 3500 : sk_X509_INFO_pop_free(inf, X509_INFO_free);
1511 : }
1512 3504 : BIO_free(cbio);
1513 : }
1514 3504 : EVP_PKEY_free(pkey);
1515 3504 : if (!matches) ERR_clear_error();
1516 : return matches;
1517 : }
1518 :
1519 : // Creates a context with a refcount of 1, a copy of mp (NULL for the default
1520 : // allocator), its mutex, an empty named-certificate map and a first default
1521 : // SSL_CTX, so it can serve clients at once. It gives NULL with *err_str set
1522 : // when any step fails, freeing what was made.
1523 10596 : ctls_ctx *ctls_ctx_new_mp(ccol_memmgmt_procs *mp, char **err_str) {
1524 10596 : ctls_ctx *tls = (ctls_ctx *)ccol__mem_calloc(mp, 1, sizeof(*tls));
1525 10596 : if (!tls) {
1526 6 : if (err_str) *err_str = "ctls_ctx_new: allocation failure";
1527 6 : return NULL;
1528 : }
1529 10590 : if (mp) {
1530 1779 : tls->m_procs = (ccol_memmgmt_procs *)ccol__mem_alloc(mp, sizeof(*mp));
1531 1779 : if (!tls->m_procs) {
1532 6 : ccol__mem_free(mp, tls);
1533 6 : if (err_str) *err_str = "ctls_ctx_new: allocation failure";
1534 6 : return NULL;
1535 : }
1536 1773 : *tls->m_procs = *mp;
1537 : }
1538 10584 : tls->ref = 1;
1539 10584 : if (ccol__mutex_init(tls->lock) != 0) {
1540 0 : ccol__mem_free(mp, tls->m_procs);
1541 0 : ccol__mem_free(mp, tls);
1542 0 : if (err_str) *err_str = "ctls_ctx_new: failed to initialize mutex";
1543 0 : return NULL;
1544 : }
1545 10584 : char *err = NULL;
1546 21168 : tls->named_certs =
1547 10584 : chashmap_create_mp(16, ccol_string, ccol_pointer, tls->m_procs, &err);
1548 10584 : if (!tls->named_certs) {
1549 6 : ccol__mutex_destroy(tls->lock);
1550 6 : ccol__mem_free(mp, tls->m_procs);
1551 6 : ccol__mem_free(mp, tls);
1552 6 : if (err_str) *err_str = "ctls_ctx_new: chmap allocation failure";
1553 6 : return NULL;
1554 : }
1555 10578 : if (ctls_ctx_rebuild_locked(tls) != ccol_success) {
1556 194 : chashmap__destroy(tls->named_certs);
1557 194 : ccol__mutex_destroy(tls->lock);
1558 194 : ccol__mem_free(mp, tls->m_procs);
1559 194 : ccol__mem_free(mp, tls);
1560 194 : if (err_str) *err_str = "ctls_ctx_new: SSL_CTX_new failure";
1561 194 : return NULL;
1562 : }
1563 : return tls;
1564 : }
1565 :
1566 : // Adds or replaces the default or a named certificate of ctx. It reads and
1567 : // checks the files first (readable, matching pair, a pair OpenSSL accepts in
1568 : // a throwaway SSL_CTX), so nothing is stored for a refused input; NULL paths
1569 : // make a self-signed certificate. Under ctx->lock it then stores the new
1570 : // fields and rebuilds. Only a successful rebuild frees the replaced fields or
1571 : // entry; a failed one puts them back (or deletes a name this call added),
1572 : // which can't fail, so every name keeps the certificate it served. A replaced
1573 : // entry's built context lives until the rebuild succeeded, and a connection
1574 : // still using it holds its own reference. Gives the codes of ctls.h.
1575 3772 : ccol_retval ctls_ctx_cert_add(ctls_ctx *ctx, const char *server_name,
1576 : const char *cert_path, const char *key_path,
1577 : const char *pk_password, char **err_str) {
1578 3772 : if (!ctx) return ccol_invalid_args;
1579 3771 : bool have_name = server_name && *server_name;
1580 3771 : bool have_pair = cert_path && key_path;
1581 3771 : bool self_signed = !cert_path && !key_path;
1582 3771 : if (!have_pair && !self_signed) {
1583 1 : if (err_str)
1584 0 : *err_str =
1585 : "ctls_ctx_cert_add: need both cert_path+key_path, or neither (for "
1586 : "a self-signed certificate)";
1587 1 : return ccol_invalid_args;
1588 : }
1589 :
1590 3770 : char *cert_pem = NULL, *key_pem = NULL, *pw_copy = NULL;
1591 3770 : size_t cert_len = 0, key_len = 0;
1592 3770 : if (have_pair) {
1593 3523 : char *why = NULL;
1594 3523 : ccol_retval read_rv =
1595 3523 : ctls_read_file(ctx->m_procs, cert_path, &cert_pem, &cert_len, &why);
1596 3523 : if (read_rv == ccol_success)
1597 3514 : read_rv =
1598 3514 : ctls_read_file(ctx->m_procs, key_path, &key_pem, &key_len, &why);
1599 3514 : if (read_rv != ccol_success) {
1600 14 : ccol__mem_free(ctx->m_procs, cert_pem);
1601 14 : ccol__mem_free(ctx->m_procs, key_pem);
1602 14 : if (err_str) {
1603 4 : *err_str = why ? why : "ctls_ctx_cert_add: cert/key file unreadable";
1604 : }
1605 31 : return read_rv;
1606 : }
1607 3509 : if (!ctls_cert_key_pair_matches(cert_pem, cert_len, key_pem, key_len,
1608 : pk_password)) {
1609 13 : ccol__mem_free(ctx->m_procs, cert_pem);
1610 13 : ccol__mem_free(ctx->m_procs, key_pem);
1611 13 : if (err_str) {
1612 3 : *err_str =
1613 : "ctls_ctx_cert_add: certificate and private key do not match, or "
1614 : "either one is unreadable";
1615 : }
1616 13 : return ccol_http_tls_cert_load_failed;
1617 : }
1618 3496 : SSL_CTX *probe = SSL_CTX_new(TLS_method());
1619 6992 : bool usable = probe && ctls_apply_base_settings(probe) &&
1620 3496 : ctls_apply_cert(probe, cert_pem, cert_len, key_pem, key_len,
1621 : pk_password, false, NULL);
1622 3496 : if (probe) SSL_CTX_free(probe);
1623 3496 : ERR_clear_error();
1624 3496 : if (!usable) {
1625 3 : ccol__mem_free(ctx->m_procs, cert_pem);
1626 3 : ccol__mem_free(ctx->m_procs, key_pem);
1627 3 : if (err_str) {
1628 1 : *err_str =
1629 : "ctls_ctx_cert_add: the TLS library refuses this certificate "
1630 : "(for example a key below its security level, or a weak "
1631 : "signature digest)";
1632 : }
1633 3 : return ccol_http_tls_cert_load_failed;
1634 : }
1635 3493 : if (pk_password) {
1636 46 : pw_copy = ctls_strdup(ctx->m_procs, pk_password);
1637 46 : if (!pw_copy) {
1638 1 : ccol__mem_free(ctx->m_procs, cert_pem);
1639 1 : ccol__mem_free(ctx->m_procs, key_pem);
1640 1 : return ccol_not_enough_memory;
1641 : }
1642 : }
1643 : }
1644 :
1645 3739 : ccol__mutex_lock(ctx->lock);
1646 3739 : ccol_retval rv = ccol_success;
1647 3739 : if (!have_name) {
1648 1290 : char *self_signed_name = NULL;
1649 1290 : if (self_signed) {
1650 69 : self_signed_name = ctls_strdup(ctx->m_procs, "ctls-default");
1651 69 : if (!self_signed_name) {
1652 1 : ccol__mem_free(ctx->m_procs, cert_pem);
1653 1 : ccol__mem_free(ctx->m_procs, key_pem);
1654 1 : ccol__mem_free(ctx->m_procs, pw_copy);
1655 1 : ccol__mutex_unlock(ctx->lock);
1656 1 : return ccol_not_enough_memory;
1657 : }
1658 : }
1659 1289 : char *prev_cert_pem = ctx->default_cert_pem;
1660 1289 : size_t prev_cert_len = ctx->default_cert_len;
1661 1289 : char *prev_key_pem = ctx->default_key_pem;
1662 1289 : size_t prev_key_len = ctx->default_key_len;
1663 1289 : char *prev_pw = ctx->default_pk_password;
1664 1289 : bool prev_self_signed = ctx->default_self_signed;
1665 1289 : char *prev_self_signed_name = ctx->default_self_signed_name;
1666 1289 : bool prev_has_default = ctx->has_default_cert;
1667 1289 : ctx->default_cert_pem = cert_pem;
1668 1289 : ctx->default_cert_len = cert_len;
1669 1289 : ctx->default_key_pem = key_pem;
1670 1289 : ctx->default_key_len = key_len;
1671 1289 : ctx->default_pk_password = pw_copy;
1672 1289 : ctx->default_self_signed = self_signed;
1673 1289 : ctx->default_self_signed_name = self_signed_name;
1674 1289 : ctx->has_default_cert = true;
1675 1289 : rv = ctls_ctx_rebuild_locked(ctx);
1676 1289 : if (rv != ccol_success) {
1677 13 : ctx->default_cert_pem = prev_cert_pem;
1678 13 : ctx->default_cert_len = prev_cert_len;
1679 13 : ctx->default_key_pem = prev_key_pem;
1680 13 : ctx->default_key_len = prev_key_len;
1681 13 : ctx->default_pk_password = prev_pw;
1682 13 : ctx->default_self_signed = prev_self_signed;
1683 13 : ctx->default_self_signed_name = prev_self_signed_name;
1684 13 : ctx->has_default_cert = prev_has_default;
1685 13 : prev_cert_pem = cert_pem;
1686 13 : prev_key_pem = key_pem;
1687 13 : prev_pw = pw_copy;
1688 13 : prev_self_signed_name = self_signed_name;
1689 : }
1690 1289 : ccol__mem_free(ctx->m_procs, prev_cert_pem);
1691 1289 : ccol__mem_free(ctx->m_procs, prev_key_pem);
1692 1289 : ccol__mem_free(ctx->m_procs, prev_pw);
1693 1289 : ccol__mem_free(ctx->m_procs, prev_self_signed_name);
1694 : } else {
1695 2449 : char *lower_name = ctls_strdup_lower(ctx->m_procs, server_name);
1696 2449 : if (!lower_name) {
1697 4 : ccol__mem_free(ctx->m_procs, cert_pem);
1698 4 : ccol__mem_free(ctx->m_procs, key_pem);
1699 4 : ccol__mem_free(ctx->m_procs, pw_copy);
1700 4 : ccol__mutex_unlock(ctx->lock);
1701 17 : return ccol_not_enough_memory;
1702 : }
1703 4890 : ctls_named_cert *nc =
1704 2445 : (ctls_named_cert *)ccol__mem_calloc(ctx->m_procs, 1, sizeof(*nc));
1705 2445 : if (!nc) {
1706 4 : ccol__mem_free(ctx->m_procs, lower_name);
1707 4 : ccol__mem_free(ctx->m_procs, cert_pem);
1708 4 : ccol__mem_free(ctx->m_procs, key_pem);
1709 4 : ccol__mem_free(ctx->m_procs, pw_copy);
1710 4 : ccol__mutex_unlock(ctx->lock);
1711 4 : return ccol_not_enough_memory;
1712 : }
1713 2441 : nc->cert_pem = cert_pem;
1714 2441 : nc->cert_len = cert_len;
1715 2441 : nc->key_pem = key_pem;
1716 2441 : nc->key_len = key_len;
1717 2441 : nc->pk_password = pw_copy;
1718 2441 : nc->self_signed = self_signed;
1719 2441 : if (self_signed) {
1720 176 : nc->self_signed_name = ctls_strdup(ctx->m_procs, lower_name);
1721 176 : if (!nc->self_signed_name) {
1722 2 : ctls_named_cert_destroy(ctx, nc);
1723 2 : ccol__mem_free(ctx->m_procs, lower_name);
1724 2 : ccol__mutex_unlock(ctx->lock);
1725 2 : return ccol_not_enough_memory;
1726 : }
1727 : }
1728 :
1729 2439 : cmap_pair kp = {.ptr = lower_name, .size = strlen(lower_name) + 1};
1730 2439 : cmap_pair old_vp;
1731 2439 : ctls_named_cert *old_nc = NULL;
1732 2439 : if (chashmap_get_elem_ref(ctx->named_certs, &kp, &old_vp) == ccol_success)
1733 179 : memcpy(&old_nc, old_vp.ptr, sizeof(old_nc));
1734 2439 : cmap_pair vp = {.ptr = &nc, .size = sizeof(nc)};
1735 2439 : rv = chashmap_insert_elem(ctx->named_certs, &kp, &vp);
1736 2439 : if (rv != ccol_success && rv != ccol_key_already_present) {
1737 3 : ccol__mem_free(ctx->m_procs, lower_name);
1738 3 : ctls_named_cert_destroy(ctx, nc);
1739 3 : ccol__mutex_unlock(ctx->lock);
1740 3 : return rv;
1741 : }
1742 2436 : rv = ctls_ctx_rebuild_locked(ctx);
1743 2436 : if (rv != ccol_success) {
1744 29 : if (old_nc) {
1745 14 : cmap_pair old_vp_pair = {.ptr = &old_nc, .size = sizeof(old_nc)};
1746 14 : ccol_retval back =
1747 14 : chashmap_insert_elem(ctx->named_certs, &kp, &old_vp_pair);
1748 14 : ccol__assert(back == ccol_key_already_present);
1749 14 : (void)back;
1750 : } else {
1751 15 : ccol_retval gone = chashmap_remove_elem(ctx->named_certs, &kp);
1752 15 : ccol__assert(gone == ccol_success);
1753 29 : (void)gone;
1754 : }
1755 29 : ctls_named_cert_destroy(ctx, nc);
1756 2407 : } else if (old_nc) {
1757 165 : ctls_named_cert_destroy(ctx, old_nc);
1758 : }
1759 2436 : ccol__mem_free(ctx->m_procs, lower_name);
1760 : }
1761 3725 : ccol__mutex_unlock(ctx->lock);
1762 3725 : if (rv != ccol_success && err_str)
1763 0 : *err_str = "ctls_ctx_cert_add: SSL_CTX rebuild failure";
1764 : return rv;
1765 : }
1766 :
1767 : // Tells whether the PEM buffer (pem, len) holds at least one certificate,
1768 : // when ctls_ctx_trust() accepts a bundle. OpenSSL parses an empty file, a
1769 : // lone key or non-PEM text into an empty set with no error, and such a bundle
1770 : // would turn verification on with a store that trusts nothing (a server would
1771 : // then silently accept every anonymous client). A CRL alone names no issuer,
1772 : // so it doesn't count. It gives ccol_success, ccol_not_enough_memory when the
1773 : // parse ran out of memory, or ccol_http_tls_cert_load_failed.
1774 858 : static ccol_retval ctls_pem_has_certificate(const char *pem, size_t len) {
1775 858 : bool oom = false;
1776 858 : STACK_OF(X509_INFO) *inf = ctls_parse_infos(pem, len, &oom, NULL);
1777 858 : if (oom) return ccol_not_enough_memory;
1778 : bool found = false;
1779 1709 : for (int i = 0; inf && i < sk_X509_INFO_num(inf) && !found; ++i) {
1780 853 : X509_INFO *entry = sk_X509_INFO_value(inf, i);
1781 854 : if (entry && entry->x509) found = true;
1782 : }
1783 856 : sk_X509_INFO_pop_free(inf, X509_INFO_free);
1784 856 : return found ? ccol_success : ccol_http_tls_cert_load_failed;
1785 : }
1786 :
1787 : // Adds the CA bundle at ca_bundle_path to ctx's trust store and turns on peer
1788 : // verification. The file is read and checked for a certificate before
1789 : // anything is stored, since a stored bad bundle would fail every later
1790 : // rebuild. Under ctx->lock it grows trust_pems and trust_lens (each new
1791 : // pointer is stored at once, so a second failed realloc can't leave the first
1792 : // dangling), appends the bundle, sets verify_peer and rebuilds. A failed
1793 : // rebuild takes the bundle and the flag back out; the bigger arrays stay.
1794 : // Gives the codes of ctls.h, with *err_str set on failure.
1795 874 : ccol_retval ctls_ctx_trust(ctls_ctx *ctx, const char *ca_bundle_path,
1796 : char **err_str) {
1797 874 : if (!ctx || !ca_bundle_path) return ccol_invalid_args;
1798 872 : char *pem = NULL;
1799 872 : size_t len = 0;
1800 872 : char *why = NULL;
1801 872 : ccol_retval read_rv =
1802 872 : ctls_read_file(ctx->m_procs, ca_bundle_path, &pem, &len, &why);
1803 872 : if (read_rv != ccol_success) {
1804 14 : if (err_str) {
1805 6 : *err_str = why ? why : "ctls_ctx_trust: CA bundle file unreadable";
1806 : }
1807 14 : return read_rv;
1808 : }
1809 858 : ccol_retval has_rv = ctls_pem_has_certificate(pem, len);
1810 858 : if (has_rv != ccol_success) {
1811 6 : ccol__mem_free(ctx->m_procs, pem);
1812 6 : if (err_str) {
1813 2 : *err_str = has_rv == ccol_not_enough_memory
1814 : ? "ctls_ctx_trust: out of memory while parsing the CA "
1815 : "bundle"
1816 2 : : "ctls_ctx_trust: CA bundle contains no certificates";
1817 : }
1818 6 : return has_rv;
1819 : }
1820 :
1821 852 : ccol__mutex_lock(ctx->lock);
1822 852 : if (ctx->trust_count == ctx->trust_cap) {
1823 821 : size_t new_cap = ctx->trust_cap ? ctx->trust_cap * 2 : 4;
1824 821 : char **new_pems = (char **)ccol__mem_realloc(ctx->m_procs, ctx->trust_pems,
1825 : new_cap * sizeof(char *));
1826 821 : if (!new_pems) {
1827 6 : ccol__mem_free(ctx->m_procs, pem);
1828 6 : ccol__mutex_unlock(ctx->lock);
1829 6 : return ccol_not_enough_memory;
1830 : }
1831 815 : ctx->trust_pems = new_pems;
1832 815 : size_t *new_lens = (size_t *)ccol__mem_realloc(
1833 : ctx->m_procs, ctx->trust_lens, new_cap * sizeof(size_t));
1834 815 : if (!new_lens) {
1835 6 : ccol__mem_free(ctx->m_procs, pem);
1836 6 : ccol__mutex_unlock(ctx->lock);
1837 6 : return ccol_not_enough_memory;
1838 : }
1839 809 : ctx->trust_lens = new_lens;
1840 809 : ctx->trust_cap = new_cap;
1841 : }
1842 840 : bool prev_verify_peer = ctx->verify_peer;
1843 840 : ctx->trust_pems[ctx->trust_count] = pem;
1844 840 : ctx->trust_lens[ctx->trust_count] = len;
1845 840 : ctx->trust_count++;
1846 840 : ctx->verify_peer = true;
1847 840 : ccol_retval rv = ctls_ctx_rebuild_locked(ctx);
1848 840 : if (rv != ccol_success) {
1849 44 : ctx->trust_count--;
1850 44 : ctx->verify_peer = prev_verify_peer;
1851 44 : ccol__mem_free(ctx->m_procs, pem);
1852 : }
1853 840 : ccol__mutex_unlock(ctx->lock);
1854 840 : if (rv != ccol_success && err_str)
1855 0 : *err_str = "ctls_ctx_trust: SSL_CTX rebuild failure";
1856 : return rv;
1857 : }
1858 :
1859 : // Makes ctx trust the system CA store and turns on peer verification: Under
1860 : // ctx->lock it sets verify_default_store and verify_peer and rebuilds,
1861 : // restoring both flags when the rebuild fails.
1862 8533 : ccol_retval ctls_ctx_trust_system(ctls_ctx *ctx) {
1863 8533 : if (!ctx) return ccol_invalid_args;
1864 8532 : ccol__mutex_lock(ctx->lock);
1865 8532 : bool prev_default_store = ctx->verify_default_store;
1866 8532 : bool prev_verify_peer = ctx->verify_peer;
1867 8532 : ctx->verify_default_store = true;
1868 8532 : ctx->verify_peer = true;
1869 8532 : ccol_retval rv = ctls_ctx_rebuild_locked(ctx);
1870 8532 : if (rv != ccol_success) {
1871 216 : ctx->verify_default_store = prev_default_store;
1872 216 : ctx->verify_peer = prev_verify_peer;
1873 : }
1874 8532 : ccol__mutex_unlock(ctx->lock);
1875 8532 : return rv;
1876 : }
1877 :
1878 : // Sets whether a server only asks for a client certificate. Under ctx->lock
1879 : // it stores the flag and, when a trust store exists, rebuilds, restoring the
1880 : // old flag on failure; without a trust store the first trust call builds with
1881 : // it.
1882 15 : ccol_retval ctls_ctx_peer_cert_optional(ctls_ctx *ctx, bool optional) {
1883 15 : if (!ctx) return ccol_invalid_args;
1884 14 : ccol__mutex_lock(ctx->lock);
1885 14 : if (ctx->peer_cert_optional == optional) {
1886 0 : ccol__mutex_unlock(ctx->lock);
1887 0 : return ccol_success;
1888 : }
1889 14 : bool previous = ctx->peer_cert_optional;
1890 14 : ctx->peer_cert_optional = optional;
1891 8 : ccol_retval rv = (ctx->trust_count == 0 && !ctx->verify_default_store)
1892 : ? ccol_success
1893 14 : : ctls_ctx_rebuild_locked(ctx);
1894 6 : if (rv != ccol_success) ctx->peer_cert_optional = previous;
1895 14 : ccol__mutex_unlock(ctx->lock);
1896 14 : return rv;
1897 : }
1898 :
1899 : // Registers or replaces an ALPN protocol on ctx. Under ctx->lock it stores the
1900 : // registration (replacing one of the same name in place, or appending) and
1901 : // rebuilds; a failed rebuild restores the old registration or removes the new
1902 : // one, so nothing of the caller's is kept and its on_cleanup never runs. The
1903 : // replaced registration's cleanup runs after the lock is released, because it
1904 : // may call back into this context. Gives the codes of ctls.h, with *err_str
1905 : // set on failure.
1906 1349 : ccol_retval ctls_ctx_alpn_add(ctls_ctx *ctx, const char *protocol_name,
1907 : ctls_alpn_selected_fn on_selected,
1908 : void *alpn_udata, ctls_alpn_cleanup_fn on_cleanup,
1909 : char **err_str) {
1910 1349 : if (!ctx || !protocol_name) return ccol_invalid_args;
1911 1347 : size_t name_len = strlen(protocol_name);
1912 1347 : if (name_len == 0 || name_len > 255) {
1913 1 : if (err_str)
1914 0 : *err_str = "ctls_ctx_alpn_add: protocol name must be 1-255 bytes";
1915 1 : return ccol_invalid_args;
1916 : }
1917 1346 : char *name_copy = ctls_strdup(ctx->m_procs, protocol_name);
1918 1346 : if (!name_copy) return ccol_not_enough_memory;
1919 :
1920 1344 : ccol__mutex_lock(ctx->lock);
1921 1356 : for (size_t i = 0; i < ctx->alpn_count; ++i) {
1922 265 : if (ctx->alpn[i].name_len == name_len &&
1923 253 : memcmp(ctx->alpn[i].name, name_copy, name_len) == 0) {
1924 253 : ctls_alpn_entry old = ctx->alpn[i];
1925 253 : ctx->alpn[i] = (ctls_alpn_entry){.name = name_copy,
1926 : .name_len = name_len,
1927 : .on_selected = on_selected,
1928 : .udata = alpn_udata,
1929 : .on_cleanup = on_cleanup};
1930 253 : ccol_retval rv = ctls_ctx_rebuild_locked(ctx);
1931 253 : if (rv != ccol_success) {
1932 28 : ctx->alpn[i] = old;
1933 28 : ccol__mutex_unlock(ctx->lock);
1934 28 : ccol__mem_free(ctx->m_procs, name_copy);
1935 28 : if (err_str) *err_str = "ctls_ctx_alpn_add: SSL_CTX rebuild failure";
1936 28 : return rv;
1937 : }
1938 225 : ccol__mutex_unlock(ctx->lock);
1939 225 : ccol__mem_free(ctx->m_procs, old.name);
1940 225 : if (old.on_cleanup) old.on_cleanup(old.udata);
1941 225 : return ccol_success;
1942 : }
1943 : }
1944 1091 : if (ctx->alpn_count == ctx->alpn_cap) {
1945 1078 : size_t new_cap = ctx->alpn_cap ? ctx->alpn_cap * 2 : 4;
1946 1078 : ctls_alpn_entry *new_alpn = (ctls_alpn_entry *)ccol__mem_realloc(
1947 : ctx->m_procs, ctx->alpn, new_cap * sizeof(ctls_alpn_entry));
1948 1078 : if (!new_alpn) {
1949 2 : ccol__mem_free(ctx->m_procs, name_copy);
1950 2 : ccol__mutex_unlock(ctx->lock);
1951 2 : return ccol_not_enough_memory;
1952 : }
1953 1076 : ctx->alpn = new_alpn;
1954 1076 : ctx->alpn_cap = new_cap;
1955 : }
1956 1089 : ctx->alpn[ctx->alpn_count++] = (ctls_alpn_entry){.name = name_copy,
1957 : .name_len = name_len,
1958 : .on_selected = on_selected,
1959 : .udata = alpn_udata,
1960 : .on_cleanup = on_cleanup};
1961 1089 : ccol_retval rv = ctls_ctx_rebuild_locked(ctx);
1962 1089 : if (rv != ccol_success) ctx->alpn_count--;
1963 1089 : ccol__mutex_unlock(ctx->lock);
1964 1089 : if (rv != ccol_success) {
1965 1 : ccol__mem_free(ctx->m_procs, name_copy);
1966 1 : if (err_str) *err_str = "ctls_ctx_alpn_add: SSL_CTX rebuild failure";
1967 : }
1968 : return rv;
1969 : }
1970 :
1971 : // Gives ctx->alpn_count, read without the lock, or 0 for NULL.
1972 44 : size_t ctls_ctx_alpn_count(const ctls_ctx *ctx) {
1973 44 : return ctx ? ctx->alpn_count : 0;
1974 : }
1975 :
1976 : // Adds a reference to ctx under its lock, for a connection or a request that
1977 : // keeps using it. NULL is ignored.
1978 2390 : void ctls_ctx_retain(ctls_ctx *ctx) {
1979 2390 : if (!ctx) return;
1980 2390 : ccol__mutex_lock(ctx->lock);
1981 2390 : ctx->ref++;
1982 2390 : ccol__mutex_unlock(ctx->lock);
1983 : }
1984 :
1985 : // Drops a reference to ctx and, at zero, frees everything it owns: The built
1986 : // contexts, the stored certificates and bundles, every named certificate
1987 : // (walked without allocating, so a release under memory pressure still frees
1988 : // them all), and the ALPN registrations after calling their cleanups. ctx is
1989 : // freed before its procs copy, because that copy holds the free function the
1990 : // first free needs. NULL is fine.
1991 12752 : void ctls_ctx_release(ctls_ctx *ctx) {
1992 12752 : if (!ctx) return;
1993 12751 : ccol__mutex_lock(ctx->lock);
1994 12751 : size_t remaining = --ctx->ref;
1995 12751 : ccol__mutex_unlock(ctx->lock);
1996 12750 : if (remaining > 0) return;
1997 :
1998 10371 : if (ctx->ctx_default) SSL_CTX_free(ctx->ctx_default);
1999 10371 : ccol__mem_free(ctx->m_procs, ctx->default_cert_pem);
2000 10371 : ccol__mem_free(ctx->m_procs, ctx->default_key_pem);
2001 10371 : ccol__mem_free(ctx->m_procs, ctx->default_pk_password);
2002 10371 : ccol__mem_free(ctx->m_procs, ctx->default_self_signed_name);
2003 :
2004 10371 : if (ctx->named_certs) {
2005 10371 : ccol_chmap_walk walk = {0};
2006 10371 : const void *key_bytes;
2007 10371 : const void *val_bytes;
2008 10371 : while (
2009 12613 : ccol_chmap_walk_next(ctx->named_certs, &walk, &key_bytes, &val_bytes)) {
2010 2242 : ctls_named_cert *nc;
2011 2242 : memcpy(&nc, val_bytes, sizeof(nc));
2012 2242 : ctls_named_cert_destroy(ctx, nc);
2013 : }
2014 10371 : chashmap__destroy(ctx->named_certs);
2015 : }
2016 :
2017 11165 : for (size_t i = 0; i < ctx->trust_count; ++i)
2018 794 : ccol__mem_free(ctx->m_procs, ctx->trust_pems[i]);
2019 10371 : ccol__mem_free(ctx->m_procs, ctx->trust_pems);
2020 10371 : ccol__mem_free(ctx->m_procs, ctx->trust_lens);
2021 :
2022 11459 : for (size_t i = 0; i < ctx->alpn_count; ++i) {
2023 1088 : if (ctx->alpn[i].on_cleanup) ctx->alpn[i].on_cleanup(ctx->alpn[i].udata);
2024 1088 : ccol__mem_free(ctx->m_procs, ctx->alpn[i].name);
2025 : }
2026 10371 : ccol__mem_free(ctx->m_procs, ctx->alpn);
2027 :
2028 10371 : ccol__mutex_destroy(ctx->lock);
2029 10371 : ccol_memmgmt_procs *mp = ctx->m_procs;
2030 10371 : ccol__mem_free(mp, ctx);
2031 10371 : ccol__mem_free(mp, mp);
2032 : }
2033 :
2034 : // Connections
2035 : //
2036 : // Frees conn's SSL (and with it the BIO) and drops both SSL_CTX pins in one
2037 : // ctx->lock section, then releases the BIO method count after the lock. The
2038 : // lock orders the connection's last use of a shared SSL_CTX before a rebuild,
2039 : // which frees replaced contexts under the same lock, can destroy it. It
2040 : // doesn't call SSL_shutdown(): Holding the lock across a write to one peer
2041 : // would stall every create, destroy and configuration change of the context.
2042 : // It updates the pin accounting only for pins really taken.
2043 842 : static void ctls_conn_release_ssl(ctls_conn *conn) {
2044 842 : ctls_ctx *ctx = conn->ctx;
2045 842 : ccol__mutex_lock(ctx->lock);
2046 842 : if (conn->ssl) {
2047 821 : SSL_free(conn->ssl);
2048 821 : conn->ssl = NULL;
2049 : }
2050 842 : bool release_sock_bio = conn->holds_sock_bio;
2051 842 : conn->holds_sock_bio = false;
2052 842 : if (conn->pinned_sni_ctx) {
2053 146 : SSL_CTX_free(conn->pinned_sni_ctx);
2054 146 : conn->pinned_sni_ctx = NULL;
2055 146 : ctls_account_ctx_pins(-1);
2056 : }
2057 842 : if (conn->pinned_ctx_default) {
2058 821 : SSL_CTX_free(conn->pinned_ctx_default);
2059 821 : conn->pinned_ctx_default = NULL;
2060 821 : ctls_account_ctx_pins(-1);
2061 : }
2062 842 : ccol__mutex_unlock(ctx->lock);
2063 842 : if (release_sock_bio) ctls_sock_bio_release();
2064 842 : }
2065 :
2066 : // Undoes a connection that failed during its own construction: Releases its
2067 : // SSL state and pins, drops the context reference ctls_conn_alloc() took, and
2068 : // frees the record. The procs are copied by value first, because that release
2069 : // may free the context and the procs copy it holds.
2070 37 : static void ctls_conn_create_unwind(ctls_conn *conn) {
2071 37 : ctls_conn_release_ssl(conn);
2072 37 : ctls_ctx *ctx = conn->ctx;
2073 37 : ccol_memmgmt_procs procs;
2074 37 : ccol_memmgmt_procs *mp = NULL;
2075 37 : if (ctx->m_procs) {
2076 37 : procs = *ctx->m_procs;
2077 37 : mp = &procs;
2078 : }
2079 37 : ctls_ctx_release(ctx);
2080 37 : ccol__mem_free(mp, conn);
2081 37 : }
2082 :
2083 : // Allocates a zeroed connection record from ctx's allocator for a create
2084 : // function, with its mode set and a reference on ctx. NULL when the
2085 : // allocation fails.
2086 846 : static ctls_conn *ctls_conn_alloc(ctls_ctx *ctx, bool is_server) {
2087 1692 : ctls_conn *conn =
2088 846 : (ctls_conn *)ccol__mem_calloc(ctx->m_procs, 1, sizeof(*conn));
2089 846 : if (!conn) return NULL;
2090 844 : conn->ctx = ctx;
2091 844 : conn->is_server = is_server;
2092 844 : ctls_ctx_retain(ctx);
2093 844 : return conn;
2094 : }
2095 :
2096 : // Creates a client connection on fd for hostname. verify_host with no
2097 : // hostname is refused, so it never connects without the name check it was
2098 : // asked for. Under ctx->lock it calls SSL_new() on the default SSL_CTX and
2099 : // pins that object in the same section, and publishes conn->ssl at once so
2100 : // every later failure unwinds through ctls_conn_create_unwind(). It then sets
2101 : // the ex_data, SNI (not for an IP literal), the host or IP check, the client
2102 : // mode and one socket BIO for both directions. Gives NULL with *err_str set on
2103 : // failure.
2104 484 : ctls_conn *ctls_conn_create_client(ctls_ctx *ctx, int fd, const char *hostname,
2105 : bool verify_host, char **err_str) {
2106 484 : if (!ctx || fd < 0) {
2107 2 : if (err_str) *err_str = "ctls_conn_create_client: invalid arguments";
2108 2 : return NULL;
2109 : }
2110 482 : if (verify_host && (!hostname || !*hostname)) {
2111 4 : if (err_str)
2112 4 : *err_str =
2113 : "ctls_conn_create_client: hostname verification requested with no "
2114 : "hostname";
2115 4 : return NULL;
2116 : }
2117 478 : ctls_conn *conn = ctls_conn_alloc(ctx, false);
2118 478 : if (!conn) {
2119 1 : if (err_str) *err_str = "ctls_conn_create_client: allocation failure";
2120 1 : return NULL;
2121 : }
2122 :
2123 477 : ccol__mutex_lock(ctx->lock);
2124 477 : SSL *ssl = SSL_new(ctx->ctx_default);
2125 477 : if (ssl) {
2126 463 : SSL_CTX_up_ref(ctx->ctx_default);
2127 463 : conn->pinned_ctx_default = ctx->ctx_default;
2128 463 : ctls_account_ctx_pins(1);
2129 463 : conn->ssl = ssl;
2130 : }
2131 477 : ccol__mutex_unlock(ctx->lock);
2132 477 : if (!ssl) {
2133 14 : ctls_conn_create_unwind(conn);
2134 14 : if (err_str) *err_str = "ctls_conn_create_client: SSL_new failure";
2135 14 : return NULL;
2136 : }
2137 463 : if (!SSL_set_ex_data(ssl, ctls_conn_ex_idx(), conn)) {
2138 4 : ctls_conn_create_unwind(conn);
2139 4 : if (err_str) *err_str = "ctls_conn_create_client: SSL_set_ex_data failure";
2140 4 : return NULL;
2141 : }
2142 :
2143 459 : BIO *bio = ctls_sock_bio_new(fd);
2144 459 : if (!bio) {
2145 4 : ctls_conn_create_unwind(conn);
2146 4 : if (err_str) *err_str = "ctls_conn_create_client: socket BIO failure";
2147 4 : return NULL;
2148 : }
2149 455 : SSL_set_bio(ssl, bio, bio);
2150 455 : conn->holds_sock_bio = true;
2151 455 : BIO_set_callback_arg(bio, (char *)&conn->rec_track);
2152 :
2153 455 : if (hostname && *hostname) {
2154 346 : struct in_addr v4;
2155 346 : struct in6_addr v6;
2156 525 : bool is_ip = inet_pton(AF_INET, hostname, &v4) == 1 ||
2157 179 : inet_pton(AF_INET6, hostname, &v6) == 1;
2158 346 : if (!is_ip) SSL_set_tlsext_host_name(ssl, hostname);
2159 346 : if (verify_host) {
2160 180 : X509_VERIFY_PARAM *param = SSL_get0_param(ssl);
2161 180 : bool ok;
2162 180 : if (is_ip) {
2163 162 : ok = X509_VERIFY_PARAM_set1_ip_asc(param, hostname) == 1;
2164 : } else {
2165 18 : X509_VERIFY_PARAM_set_hostflags(param,
2166 : X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
2167 18 : ok = X509_VERIFY_PARAM_set1_host(param, hostname, 0) == 1;
2168 : }
2169 180 : if (!ok) {
2170 4 : ctls_conn_create_unwind(conn);
2171 4 : if (err_str)
2172 4 : *err_str =
2173 : "ctls_conn_create_client: could not configure hostname "
2174 : "verification target";
2175 4 : return NULL;
2176 : }
2177 : }
2178 : }
2179 451 : SSL_set_connect_state(ssl);
2180 451 : return conn;
2181 : }
2182 :
2183 : // Creates a server connection on the accepted fd, keeping udata for
2184 : // ctls_conn_udata(). Like the client create, SSL_new() and the pin of the
2185 : // default SSL_CTX happen under ctx->lock, and failures unwind through
2186 : // ctls_conn_create_unwind(). It sets the ex_data the SNI and ALPN callbacks
2187 : // read, the server mode and one socket BIO. Gives NULL with *err_str set on
2188 : // failure.
2189 369 : ctls_conn *ctls_conn_create_server(ctls_ctx *ctx, int fd, void *udata,
2190 : char **err_str) {
2191 369 : if (!ctx || fd < 0) {
2192 1 : if (err_str) *err_str = "ctls_conn_create_server: invalid arguments";
2193 1 : return NULL;
2194 : }
2195 368 : ctls_conn *conn = ctls_conn_alloc(ctx, true);
2196 368 : if (!conn) {
2197 1 : if (err_str) *err_str = "ctls_conn_create_server: allocation failure";
2198 1 : return NULL;
2199 : }
2200 367 : conn->udata = udata;
2201 :
2202 367 : ccol__mutex_lock(ctx->lock);
2203 367 : SSL *ssl = SSL_new(ctx->ctx_default);
2204 367 : if (ssl) {
2205 360 : SSL_CTX_up_ref(ctx->ctx_default);
2206 360 : conn->pinned_ctx_default = ctx->ctx_default;
2207 360 : ctls_account_ctx_pins(1);
2208 360 : conn->ssl = ssl;
2209 : }
2210 367 : ccol__mutex_unlock(ctx->lock);
2211 367 : if (!ssl) {
2212 7 : ctls_conn_create_unwind(conn);
2213 7 : if (err_str) *err_str = "ctls_conn_create_server: SSL_new failure";
2214 7 : return NULL;
2215 : }
2216 360 : if (!SSL_set_ex_data(ssl, ctls_conn_ex_idx(), conn)) {
2217 2 : ctls_conn_create_unwind(conn);
2218 2 : if (err_str) *err_str = "ctls_conn_create_server: SSL_set_ex_data failure";
2219 2 : return NULL;
2220 : }
2221 :
2222 358 : BIO *bio = ctls_sock_bio_new(fd);
2223 358 : if (!bio) {
2224 2 : ctls_conn_create_unwind(conn);
2225 2 : if (err_str) *err_str = "ctls_conn_create_server: socket BIO failure";
2226 2 : return NULL;
2227 : }
2228 356 : SSL_set_bio(ssl, bio, bio);
2229 356 : conn->holds_sock_bio = true;
2230 356 : BIO_set_callback_arg(bio, (char *)&conn->rec_track);
2231 356 : SSL_set_accept_state(ssl);
2232 356 : return conn;
2233 : }
2234 :
2235 : // Records the protocol conn's handshake agreed on, by copying its name into
2236 : // conn's own buffer under tls->lock, and then fires the registration's
2237 : // on_selected with no lock held, since it may call back into the same
2238 : // context. ctls_conn_handshake_step() calls it in both modes as its last use
2239 : // of conn, so the callback may destroy the connection. When nothing was
2240 : // agreed, nothing is recorded and no callback fires; reporting a registered
2241 : // name would make a client speak a protocol the server never accepted.
2242 716 : static void ctls_record_alpn(ctls_conn *conn) {
2243 716 : ctls_ctx *tls = conn->ctx;
2244 716 : const unsigned char *proto = NULL;
2245 716 : unsigned int proto_len = 0;
2246 716 : SSL_get0_alpn_selected(conn->ssl, &proto, &proto_len);
2247 716 : ccol__mutex_lock(tls->lock);
2248 716 : if (tls->alpn_count == 0) {
2249 473 : ccol__mutex_unlock(tls->lock);
2250 951 : return;
2251 : }
2252 243 : ctls_alpn_entry *matched = NULL;
2253 243 : if (proto_len > 0) {
2254 238 : for (size_t i = 0; i < tls->alpn_count; ++i) {
2255 238 : if (tls->alpn[i].name_len == proto_len &&
2256 238 : memcmp(tls->alpn[i].name, proto, proto_len) == 0) {
2257 : matched = &tls->alpn[i];
2258 : break;
2259 : }
2260 : }
2261 : }
2262 238 : if (!matched) {
2263 5 : ccol__mutex_unlock(tls->lock);
2264 5 : return;
2265 : }
2266 238 : memcpy(conn->alpn_selected_buf, matched->name, matched->name_len);
2267 238 : conn->alpn_selected_buf[matched->name_len] = '\0';
2268 238 : conn->alpn_selected_name = conn->alpn_selected_buf;
2269 238 : conn->alpn_selected_len = matched->name_len;
2270 238 : ctls_alpn_selected_fn cb = matched->on_selected;
2271 238 : size_t name_len = matched->name_len;
2272 238 : void *udata = matched->udata;
2273 238 : ccol__mutex_unlock(tls->lock);
2274 238 : if (cb) cb(conn, conn->alpn_selected_buf, name_len, udata);
2275 : }
2276 :
2277 : // Runs one SSL_accept() or SSL_connect() step on conn, with a clean error
2278 : // queue, and maps the result to DONE, WANT_READ, WANT_WRITE or ERROR. On DONE
2279 : // it sets handshake_done and records the ALPN result, which may fire the
2280 : // callback. See ctls.h for the ThreadSanitizer report inside OpenSSL that
2281 : // this call can show.
2282 1577 : ctls_handshake_result ctls_conn_handshake_step(ctls_conn *conn) {
2283 1577 : if (!conn || !conn->ssl) return CTLS_HANDSHAKE_ERROR;
2284 1576 : ERR_clear_error();
2285 1576 : int ri = conn->is_server ? SSL_accept(conn->ssl) : SSL_connect(conn->ssl);
2286 1576 : if (ri == 1) {
2287 716 : conn->handshake_done = true;
2288 716 : ctls_record_alpn(conn);
2289 716 : return CTLS_HANDSHAKE_DONE;
2290 : }
2291 860 : switch (SSL_get_error(conn->ssl, ri)) {
2292 : case SSL_ERROR_WANT_READ:
2293 : return CTLS_HANDSHAKE_WANT_READ;
2294 0 : case SSL_ERROR_WANT_WRITE:
2295 0 : return CTLS_HANDSHAKE_WANT_WRITE;
2296 : default:
2297 : return CTLS_HANDSHAKE_ERROR;
2298 : }
2299 : }
2300 :
2301 : // Turns an SSL_read() or SSL_write() result ret into the read(2)-like result
2302 : // of ctls_conn_read() and ctls_conn_write(): Bytes, 0 for close_notify, or -1
2303 : // with errno. SSL_ERROR_SSL and SSL_ERROR_SYSCALL are ECONNRESET (a syscall
2304 : // error never becomes a retry that could spin), and the "want" results are
2305 : // EWOULDBLOCK with the direction stored in conn->last_io_wants_write. The
2306 : // callers clear the error queue before the I/O, because many connections
2307 : // share a few threads.
2308 1154 : static ssize_t ctls_classify_io_result(ctls_conn *conn, int ret) {
2309 1154 : if (ret > 0) return ret;
2310 275 : int err = SSL_get_error(conn->ssl, ret);
2311 275 : switch (err) {
2312 : case SSL_ERROR_ZERO_RETURN:
2313 : return 0;
2314 8 : case SSL_ERROR_SSL:
2315 8 : errno = ECONNRESET;
2316 8 : return -1;
2317 47 : case SSL_ERROR_SYSCALL:
2318 47 : if (!errno) errno = ECONNRESET;
2319 : return -1;
2320 2 : case SSL_ERROR_WANT_WRITE:
2321 2 : conn->last_io_wants_write = true;
2322 2 : errno = EWOULDBLOCK;
2323 2 : return -1;
2324 197 : default:
2325 197 : conn->last_io_wants_write = false;
2326 197 : errno = EWOULDBLOCK;
2327 197 : return -1;
2328 : }
2329 : }
2330 :
2331 : // Clamps a size_t length to the int SSL_read() and SSL_write() take. A plain
2332 : // cast would truncate or go negative above INT_MAX; the clamp turns that into
2333 : // a short transfer, which the callers already loop on (a streaming handler
2334 : // can pass a buffer that large).
2335 1177 : static inline int ctls_clamp_io_len(size_t len) {
2336 1177 : return len > (size_t)INT_MAX ? INT_MAX : (int)len;
2337 : }
2338 :
2339 : // Tells whether a failed SSL_read() (ret) is the peer closing the socket
2340 : // without close_notify on a record boundary, which ctls_conn_read() reports as
2341 : // end of data, as curl and Go do. It needs the OpenSSL 3 unexpected-EOF reason
2342 : // or a SSL_ERROR_SYSCALL (OpenSSL 1.1, LibreSSL), the BIO's EOF flag, and a
2343 : // record tracker that isn't inside a record. A close inside a record stays an
2344 : // error, as in Go.
2345 295 : static bool ctls_eof_on_record_boundary(ctls_conn *conn, int ret) {
2346 295 : int err = SSL_get_error(conn->ssl, ret);
2347 295 : if (err != SSL_ERROR_SYSCALL && err != SSL_ERROR_SSL) return false;
2348 77 : BIO *rb = SSL_get_rbio(conn->ssl);
2349 77 : if (!rb || !BIO_test_flags(rb, CTLS_SOCK_BIO_EOF)) return false;
2350 26 : if (conn->rec_track.hdr_got != 0 || conn->rec_track.lost) return false;
2351 23 : if (err == SSL_ERROR_SYSCALL) return true;
2352 : #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
2353 23 : unsigned long e = ERR_peek_error();
2354 46 : return ERR_GET_LIB(e) == ERR_LIB_SSL &&
2355 23 : ERR_GET_REASON(e) == SSL_R_UNEXPECTED_EOF_WHILE_READING;
2356 : #else
2357 : return false;
2358 : #endif
2359 : }
2360 :
2361 : // Reads up to len decrypted bytes into buf with SSL_read(), clamping the
2362 : // length and clearing the error queue first. A len of 0 gives 0 at once (the
2363 : // classification would read SSL_read()'s 0 as a reset). A close on a record
2364 : // boundary without close_notify gives 0. Otherwise it gives what
2365 : // ctls_classify_io_result() makes of the result, and that may set
2366 : // last_io_wants_write.
2367 564 : ssize_t ctls_conn_read(ctls_conn *conn, void *buf, size_t len) {
2368 564 : if (!conn || !conn->ssl) {
2369 1 : errno = EINVAL;
2370 1 : return -1;
2371 : }
2372 563 : if (len == 0) return 0;
2373 561 : ERR_clear_error();
2374 561 : int ret = SSL_read(conn->ssl, buf, ctls_clamp_io_len(len));
2375 561 : if (ret <= 0 && ctls_eof_on_record_boundary(conn, ret)) {
2376 23 : ERR_clear_error();
2377 23 : return 0;
2378 : }
2379 538 : return ctls_classify_io_result(conn, ret);
2380 : }
2381 :
2382 : // Writes up to len bytes of buf with SSL_write(), clamping the length and
2383 : // clearing the error queue first. A len of 0 gives 0 at once. It gives what
2384 : // ctls_classify_io_result() makes of the result, which may set
2385 : // last_io_wants_write.
2386 618 : ssize_t ctls_conn_write(ctls_conn *conn, const void *buf, size_t len) {
2387 618 : if (!conn || !conn->ssl) {
2388 1 : errno = EINVAL;
2389 1 : return -1;
2390 : }
2391 617 : if (len == 0) return 0;
2392 616 : ERR_clear_error();
2393 616 : int ret = SSL_write(conn->ssl, buf, ctls_clamp_io_len(len));
2394 616 : return ctls_classify_io_result(conn, ret);
2395 : }
2396 :
2397 : // Gives conn->last_io_wants_write, or false for NULL.
2398 123 : bool ctls_conn_wants_write(const ctls_conn *conn) {
2399 123 : return conn && conn->last_io_wants_write;
2400 : }
2401 :
2402 : // Tells whether conn holds input a read can take without the socket:
2403 : // SSL_pending() plus SSL_has_pending() on OpenSSL, SSL_pending() plus the
2404 : // record tracker on LibreSSL, which has no SSL_has_pending(). No buffer of
2405 : // ours sits between the BIO and OpenSSL, so that's the whole answer. NULL
2406 : // gives false.
2407 310 : bool ctls_conn_has_pending_input(const ctls_conn *conn) {
2408 310 : if (!conn || !conn->ssl) return false;
2409 : #if defined(LIBRESSL_VERSION_NUMBER)
2410 : return SSL_pending(conn->ssl) > 0 || conn->rec_track.hdr_got != 0 ||
2411 : conn->rec_track.lost;
2412 : #else
2413 319 : return SSL_pending(conn->ssl) > 0 || SSL_has_pending(conn->ssl) == 1;
2414 : #endif
2415 : }
2416 :
2417 : // Gives the peer certificate of ssl without a new reference (the session keeps
2418 : // one). OpenSSL 1.1.1 and LibreSSL have no SSL_get0_peer_certificate(), so
2419 : // their referenced result is dropped at once.
2420 144 : static X509 *ctls_peer_cert0(const SSL *ssl) {
2421 : #if defined(LIBRESSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x30000000L
2422 : X509 *cert = SSL_get_peer_certificate(ssl);
2423 : X509_free(cert);
2424 : return cert;
2425 : #else
2426 144 : return SSL_get0_peer_certificate(ssl);
2427 : #endif
2428 : }
2429 :
2430 : // Gives SSL_get_verify_result() of conn, so a caller can tell a certificate
2431 : // failure from another, or -1 for NULL or a connection without an SSL.
2432 41 : long ctls_conn_verify_result(const ctls_conn *conn) {
2433 41 : if (!conn || !conn->ssl) return -1;
2434 40 : return SSL_get_verify_result(conn->ssl);
2435 : }
2436 :
2437 : // Tells whether conn's peer presented a certificate that verified: It needs
2438 : // a finished handshake, SSL_VERIFY_PEER in the mode, a peer certificate and
2439 : // X509_V_OK, because OpenSSL reports X509_V_OK for a peer that sent nothing.
2440 : // A resumed session carries the answer of its original handshake.
2441 97 : bool ctls_conn_peer_cert_verified(const ctls_conn *conn) {
2442 97 : if (!conn || !conn->ssl || !conn->handshake_done) return false;
2443 91 : return (SSL_get_verify_mode(conn->ssl) & SSL_VERIFY_PEER) != 0 &&
2444 182 : ctls_peer_cert0(conn->ssl) != NULL &&
2445 70 : SSL_get_verify_result(conn->ssl) == X509_V_OK;
2446 : }
2447 :
2448 : // Makes, once per certificate, the DER encoding and the RFC 2253 subject of
2449 : // the verified peer certificate in conn's peer_der and peer_subject, from the
2450 : // context's allocator, for the three peer-certificate accessors. It holds a
2451 : // reference on the certificate in peer_info_cert, so a renegotiated one makes
2452 : // them again. XN_FLAG_RFC2253 escapes every byte above 0x7F and every control
2453 : // byte, so the subject is printable ASCII. It gives the certificate, or NULL
2454 : // when there's no verified one or an allocation fails (what failed stays
2455 : // NULL).
2456 80 : static const X509 *ctls_conn_peer_info(ctls_conn *conn) {
2457 80 : if (!ctls_conn_peer_cert_verified(conn)) return NULL;
2458 62 : X509 *cert = ctls_peer_cert0(conn->ssl);
2459 62 : if (!cert) return NULL;
2460 62 : if (conn->peer_info_cert == cert) return cert;
2461 30 : ccol_memmgmt_procs *mp = conn->ctx->m_procs;
2462 30 : ccol__mem_free(mp, conn->peer_der);
2463 30 : ccol__mem_free(mp, conn->peer_subject);
2464 30 : conn->peer_der = NULL;
2465 30 : conn->peer_der_len = 0;
2466 30 : conn->peer_subject = NULL;
2467 30 : X509_free(conn->peer_info_cert);
2468 30 : conn->peer_info_cert = NULL;
2469 :
2470 30 : int der_len = i2d_X509(cert, NULL);
2471 30 : if (der_len <= 0) {
2472 0 : ERR_clear_error();
2473 0 : return NULL;
2474 : }
2475 30 : unsigned char *der = (unsigned char *)ccol__mem_alloc(mp, (size_t)der_len);
2476 30 : if (!der) return NULL;
2477 29 : unsigned char *w = der;
2478 29 : if (i2d_X509(cert, &w) != der_len) {
2479 0 : ERR_clear_error();
2480 0 : ccol__mem_free(mp, der);
2481 0 : return NULL;
2482 : }
2483 :
2484 29 : char *subject = NULL;
2485 29 : BIO *bio = BIO_new(BIO_s_mem());
2486 29 : if (bio && X509_NAME_print_ex(bio, X509_get_subject_name(cert), 0,
2487 : XN_FLAG_RFC2253) >= 0) {
2488 21 : char *text = NULL;
2489 21 : long text_len = BIO_get_mem_data(bio, &text);
2490 21 : if (text_len >= 0) {
2491 21 : subject = (char *)ccol__mem_alloc(mp, (size_t)text_len + 1);
2492 21 : if (subject) {
2493 20 : if (text_len) memcpy(subject, text, (size_t)text_len);
2494 20 : subject[text_len] = '\0';
2495 : }
2496 : }
2497 : }
2498 29 : BIO_free(bio);
2499 29 : ERR_clear_error();
2500 29 : if (!subject || X509_up_ref(cert) != 1) {
2501 9 : ccol__mem_free(mp, subject);
2502 9 : ccol__mem_free(mp, der);
2503 9 : return NULL;
2504 : }
2505 20 : conn->peer_der = der;
2506 20 : conn->peer_der_len = (size_t)der_len;
2507 20 : conn->peer_subject = subject;
2508 20 : conn->peer_info_cert = cert;
2509 20 : return cert;
2510 : }
2511 :
2512 : // Gives conn's verified peer certificate in DER, owned by conn, with its
2513 : // length in *len_out (may be NULL); NULL and 0 when there's none.
2514 40 : const unsigned char *ctls_conn_peer_cert_der(ctls_conn *conn, size_t *len_out) {
2515 40 : if (len_out) *len_out = 0;
2516 40 : if (!ctls_conn_peer_info(conn)) return NULL;
2517 23 : if (len_out) *len_out = conn->peer_der_len;
2518 23 : return conn->peer_der;
2519 : }
2520 :
2521 : // Writes the SHA-256 of the peer certificate's DER encoding to out. It zeroes
2522 : // out first and again on a failed digest, and gives false for a NULL out, no
2523 : // verified certificate or a failed digest.
2524 13 : bool ctls_conn_peer_cert_sha256(ctls_conn *conn,
2525 : unsigned char out[CTLS_SHA256_LEN]) {
2526 13 : if (!out) return false;
2527 13 : memset(out, 0, CTLS_SHA256_LEN);
2528 13 : if (!ctls_conn_peer_info(conn)) return false;
2529 8 : unsigned int md_len = 0;
2530 8 : if (EVP_Digest(conn->peer_der, conn->peer_der_len, out, &md_len, EVP_sha256(),
2531 6 : NULL) != 1 ||
2532 6 : md_len != CTLS_SHA256_LEN) {
2533 2 : ERR_clear_error();
2534 2 : memset(out, 0, CTLS_SHA256_LEN);
2535 2 : return false;
2536 : }
2537 : return true;
2538 : }
2539 :
2540 : // Gives conn's verified peer certificate subject, owned by conn, or NULL.
2541 27 : const char *ctls_conn_peer_cert_subject(ctls_conn *conn) {
2542 27 : if (!ctls_conn_peer_info(conn)) return NULL;
2543 21 : return conn->peer_subject;
2544 : }
2545 :
2546 : // Gives the protocol name recorded on conn after the handshake, with its
2547 : // length in *len_out (may be NULL), or NULL when none was agreed.
2548 84 : const char *ctls_conn_alpn_selected(const ctls_conn *conn, size_t *len_out) {
2549 84 : if (!conn || !conn->alpn_selected_name) {
2550 3 : if (len_out) *len_out = 0;
2551 3 : return NULL;
2552 : }
2553 81 : if (len_out) *len_out = conn->alpn_selected_len;
2554 : return conn->alpn_selected_name;
2555 : }
2556 :
2557 : // Gives the udata conn was created with, or NULL for NULL.
2558 2 : void *ctls_conn_udata(const ctls_conn *conn) {
2559 2 : return conn ? conn->udata : NULL;
2560 : }
2561 :
2562 : // Destroys conn when its connection ends. After a finished handshake it sends
2563 : // close_notify with no lock held (holding ctx->lock across a peer's socket
2564 : // would queue every other connection behind it) and clears the thread's error
2565 : // queue whatever happened. It then releases the SSL and both pins under
2566 : // ctx->lock (see ctls_conn_release_ssl()), frees the peer-certificate cache,
2567 : // drops its context reference and frees the record with a by-value copy of
2568 : // the procs, since that release may free the context and its procs. NULL is
2569 : // fine.
2570 810 : void ctls_conn_destroy(ctls_conn *conn) {
2571 810 : if (!conn) return;
2572 805 : if (conn->ssl && conn->handshake_done) SSL_shutdown(conn->ssl);
2573 805 : ERR_clear_error();
2574 805 : ctls_conn_release_ssl(conn);
2575 805 : ccol_memmgmt_procs procs;
2576 805 : ccol_memmgmt_procs *mp = NULL;
2577 805 : if (conn->ctx->m_procs) {
2578 53 : procs = *conn->ctx->m_procs;
2579 53 : mp = &procs;
2580 : }
2581 53 : ccol__mem_free(mp, conn->peer_der);
2582 805 : ccol__mem_free(mp, conn->peer_subject);
2583 805 : X509_free(conn->peer_info_cert);
2584 805 : ctls_ctx_release(conn->ctx);
2585 805 : ccol__mem_free(mp, conn);
2586 : }
2587 :
2588 : #ifdef RUNNING_UNIT_TESTS
2589 : // Gives conn's SSL, so a test can inspect the agreed peer certificate and
2590 : // check the SNI dispatch.
2591 41 : SSL *ctls__conn_ssl_for_tests(ctls_conn *conn) {
2592 41 : return conn ? conn->ssl : NULL;
2593 : }
2594 :
2595 : // Gives the SSL_CTX conn pinned for an SNI dispatch, or NULL, so a test can
2596 : // check that the context a connection serves from is one we hold.
2597 3 : SSL_CTX *ctls__conn_pinned_sni_ctx_for_tests(ctls_conn *conn) {
2598 3 : return conn ? conn->pinned_sni_ctx : NULL;
2599 : }
2600 :
2601 : // Gives the SSL_CTX a ClientHello naming server_name would be served from
2602 : // (the matching named context, found as the SNI callback finds it, or the
2603 : // default), read under tls->lock, so a test can check every name after a
2604 : // configuration change without a handshake.
2605 6628 : SSL_CTX *ctls__ctx_served_ctx_for_tests(ctls_ctx *tls,
2606 : const char *server_name) {
2607 6628 : if (!tls) return NULL;
2608 6628 : ccol__mutex_lock(tls->lock);
2609 6628 : SSL_CTX *found = ctls_find_named_ctx(tls, server_name);
2610 6628 : if (!found) found = tls->ctx_default;
2611 6628 : ccol__mutex_unlock(tls->lock);
2612 6628 : return found;
2613 : }
2614 : #endif
|