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 : #pragma once
26 :
27 : // Internal only. An OpenSSL wrapper with no reactor of its own: It configures
28 : // a TLS context (certificates, trust, ALPN, dispatch by server name) and
29 : // drives one connection's handshake, reads and writes step by step, without
30 : // blocking, in client and server mode. Only chttpclient.c and chttpserver.c
31 : // include it.
32 : //
33 : // Every connection talks to its socket through our own BIO, which writes with
34 : // send(2) and MSG_NOSIGNAL, so a write to a gone peer (the close_notify of
35 : // ctls_conn_destroy() included) gives EPIPE and never SIGPIPE. The fd must be
36 : // a socket. Failures come back as NULL or a ccol_retval; a bad configuration
37 : // never stops the process.
38 : //
39 : // A ctls_ctx is a refcounted, mutex-protected configuration shared by many
40 : // connections. Each call that changes it rebuilds every SSL_CTX from the
41 : // stored configuration, so the live SSL_CTX objects are always a function of
42 : // that configuration. A named certificate gets its own SSL_CTX, and a
43 : // servername callback on the default SSL_CTX moves the connection there with
44 : // SSL_set_SSL_CTX(). ALPN callbacks fire synchronously inside
45 : // ctls_conn_handshake_step().
46 : //
47 : // Resumption works for TLS 1.2 and 1.3, with or without a client certificate
48 : // and across an SNI dispatch: Every SSL_CTX gets the same session id context,
49 : // which OpenSSL needs to resume on a context with SSL_VERIFY_PEER. Each SSL_CTX
50 : // also gets partial and moving-buffer writes, TLS 1.2 as the minimum and no
51 : // compression. A configuration change builds new SSL_CTX objects (new cache,
52 : // new ticket keys), so an older session gets a full handshake, never a
53 : // failure.
54 :
55 : #include <common.h>
56 : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
57 : #include <stdbool.h>
58 : #endif
59 : #include <stddef.h>
60 : #include <sys/types.h>
61 :
62 : // A refcounted TLS configuration: Certificates, trust store, ALPN protocols.
63 : typedef struct ctls_ctx ctls_ctx;
64 :
65 : // One connection: An SSL object and its BIO.
66 : typedef struct ctls_conn ctls_conn;
67 :
68 : // The result of ctls_conn_handshake_step(). WANT_READ and WANT_WRITE say which
69 : // readiness to wait for before the next step; after ERROR destroy the
70 : // connection.
71 : typedef enum ctls_handshake_result {
72 : CTLS_HANDSHAKE_DONE = 0,
73 : CTLS_HANDSHAKE_WANT_READ,
74 : CTLS_HANDSHAKE_WANT_WRITE,
75 : CTLS_HANDSHAKE_ERROR
76 : } ctls_handshake_result;
77 :
78 : // Called from the ctls_conn_handshake_step() that completes a handshake which
79 : // agreed on this registration's protocol (a server when the client offered it,
80 : // a client when the server picked it). The TLS library is done with conn by
81 : // then, so the callback may destroy it, as long as the caller of the step stops
82 : // using it. protocol_name is raw wire bytes, not NUL-terminated. alpn_udata is
83 : // what ctls_ctx_alpn_add() got; ctls_conn_udata() gives the connection's own
84 : // pointer. A handshake that agrees on nothing fires no callback, and
85 : // ctls_conn_alpn_selected() gives NULL.
86 : typedef void (*ctls_alpn_selected_fn)(ctls_conn *conn,
87 : const char *protocol_name,
88 : size_t protocol_len, void *alpn_udata);
89 :
90 : // Frees an ALPN registration's alpn_udata when the context is destroyed or a
91 : // later ctls_ctx_alpn_add() replaces it. No lock of this module is held, so it
92 : // may call back into the module. It may be NULL.
93 : typedef void (*ctls_alpn_cleanup_fn)(void *alpn_udata);
94 :
95 : // Contexts
96 : //
97 : // Creates an empty context with a refcount of 1; both HTTP modules hold their
98 : // TLS configuration in one. mp is the allocator (NULL for the default). It
99 : // can serve client connections that present no certificate at once; a server
100 : // needs ctls_ctx_cert_add() first. It gives NULL when the allocation fails,
101 : // with a static message in *err_str.
102 : ctls_ctx *ctls_ctx_new_mp(ccol_memmgmt_procs *mp, char **err_str);
103 :
104 : // Creates a context like ctls_ctx_new_mp(), with the default allocator.
105 5893 : static inline __attribute__((always_inline)) ctls_ctx *ctls_ctx_new(
106 : char **err_str) {
107 5909 : return ctls_ctx_new_mp(NULL, err_str);
108 : }
109 :
110 : // Adds or replaces a certificate and key, which a server needs to serve and a
111 : // client needs for mutual TLS. A NULL or empty server_name sets the default
112 : // certificate: A client presents it, and a server uses it when the peer sends
113 : // no SNI name or one that nothing matches. Any other name registers (or
114 : // replaces) a named certificate, matched case-insensitively against the SNI
115 : // name. "*.example.com" matches one label ("foo.example.com", not
116 : // "example.com" or "a.b.example.com"), and an exact name always wins over a
117 : // wildcard.
118 : //
119 : // cert_path and key_path must both be set or both be NULL. Set, the PEM files
120 : // are read once during the call, and a key that doesn't match the certificate
121 : // is refused. NULL generates a self-signed certificate whose subject is
122 : // server_name, or a fixed name for the default slot. pk_password may decrypt
123 : // the key.
124 : //
125 : // It gives ccol_success, ccol_invalid_args (NULL ctx, bad combination),
126 : // ccol_http_tls_cert_load_failed (an unreadable path or one that isn't a
127 : // regular file of at most 16 MB, a malformed file, a mismatched pair, or a
128 : // pair OpenSSL won't serve, such as a weak key or digest) or
129 : // ccol_not_enough_memory. A failed rebuild gives ccol_not_enough_memory for an
130 : // allocation and ccol_http_tls_cert_load_failed otherwise. On any failure
131 : // nothing changes: Every name keeps its old certificate and a new name isn't
132 : // registered.
133 : ccol_retval ctls_ctx_cert_add(ctls_ctx *ctx, const char *server_name,
134 : const char *cert_path, const char *key_path,
135 : const char *pk_password, char **err_str);
136 :
137 : // Adds a PEM CA bundle to the trust store and turns on SSL_VERIFY_PEER, so a
138 : // client can verify a server against a private CA and a server can require
139 : // client certificates. A client verifies the server's chain with it; a server
140 : // asks for a client certificate and by default requires one
141 : // (SSL_VERIFY_FAIL_IF_NO_PEER_CERT), see ctls_ctx_peer_cert_optional(). Calls
142 : // add up.
143 : //
144 : // The bundle must contribute at least one certificate: An empty file, a lone
145 : // key, a file that isn't PEM or one with only CRLs is refused, so verification
146 : // never runs against an empty store. CRLs in any bundle turn on revocation
147 : // checks for the whole chain (X509_V_FLAG_CRL_CHECK and _ALL, as nginx
148 : // ssl_crl does): Each certificate below the anchor needs its issuer's CRL, and
149 : // a revoked certificate, a missing or an expired CRL fails. The path must be a
150 : // regular file of at most 16 MB; anything else is refused at once.
151 : //
152 : // It gives ccol_success, ccol_invalid_args, ccol_not_enough_memory or
153 : // ccol_http_tls_cert_load_failed. On failure the bundle isn't stored and the
154 : // verify settings stay.
155 : ccol_retval ctls_ctx_trust(ctls_ctx *ctx, const char *ca_bundle_path,
156 : char **err_str);
157 :
158 : // Trusts the system CA store as well and turns on SSL_VERIFY_PEER, which is
159 : // what a client needs for public HTTPS servers. The store is OpenSSL's
160 : // default CA file (SSL_CERT_FILE unless the process is setuid or setgid, else
161 : // the built-in path), read through a close-on-exec descriptor and parsed once
162 : // per process at the first call; later changes of the file or the variable
163 : // have no effect, and a failed load isn't remembered. Only when that file is
164 : // absent or holds no certificate does it use the hashed directory
165 : // (SSL_CERT_DIR or the built-in one), whose files OpenSSL opens during
166 : // handshakes without close-on-exec. It gives ccol_success, ccol_invalid_args,
167 : // ccol_not_enough_memory or ccol_http_tls_cert_load_failed (no default store,
168 : // for example); on failure the verify settings stay.
169 : ccol_retval ctls_ctx_trust_system(ctls_ctx *ctx);
170 :
171 : // Chooses whether a server with a trust store only asks for a client
172 : // certificate (optional true; one that's sent must still verify) or requires
173 : // one (false, the default), so a server can serve anonymous clients next to
174 : // authenticated ones. It applies to every SSL_CTX of ctx, before or after
175 : // ctls_ctx_trust(). Clients ignore it. A failed rebuild gives
176 : // ccol_not_enough_memory or ccol_http_tls_cert_load_failed and keeps the old
177 : // setting; NULL ctx gives ccol_invalid_args.
178 : ccol_retval ctls_ctx_peer_cert_optional(ctls_ctx *ctx, bool optional);
179 :
180 : // Registers an ALPN protocol (1 to 255 bytes), so the two sides can agree on
181 : // the application protocol during the handshake. A server selects the
182 : // registered protocol the client offers first; registration order doesn't
183 : // matter, and no common protocol means nothing is agreed. on_selected (may be
184 : // NULL) fires with alpn_udata when it's chosen, and on_cleanup (may be NULL)
185 : // frees alpn_udata later. It gives ccol_invalid_args for a NULL ctx or name
186 : // and a bad length, and ccol_not_enough_memory or
187 : // ccol_http_tls_cert_load_failed when the rebuild fails. On failure nothing is
188 : // stored, on_cleanup isn't called and a registration of the same name stays.
189 : ccol_retval ctls_ctx_alpn_add(ctls_ctx *ctx, const char *protocol_name,
190 : ctls_alpn_selected_fn on_selected,
191 : void *alpn_udata, ctls_alpn_cleanup_fn on_cleanup,
192 : char **err_str);
193 :
194 : // Gives the number of ALPN protocols ctx holds, so a caller can tell whether
195 : // ALPN is in use.
196 : size_t ctls_ctx_alpn_count(const ctls_ctx *ctx);
197 :
198 : // Adds a reference to ctx, so it stays alive for a connection or a request in
199 : // flight; pair it with ctls_ctx_release(). Changing the configuration while
200 : // connections are live is fine independently of this count: The rebuild
201 : // replaces the SSL_CTX objects, and each live connection holds a reference on
202 : // every SSL_CTX it can reach until ctls_conn_destroy(), so a handshake in
203 : // flight finishes with the configuration it started with.
204 : void ctls_ctx_retain(ctls_ctx *ctx);
205 :
206 : // Drops a reference to ctx and frees it when the last one goes. NULL is
207 : // fine.
208 : void ctls_ctx_release(ctls_ctx *ctx);
209 :
210 : // Connections
211 : //
212 : // Creates a client connection on fd, connected or with a non-blocking connect
213 : // in progress, for an HTTPS request. It does no I/O, retains ctx and doesn't
214 : // own fd (close it after ctls_conn_destroy()). hostname is used for SNI (not
215 : // for an IP literal, as RFC 6066 says) and, with verify_host, for the name
216 : // check. verify_host with a NULL or empty hostname is refused. A name check
217 : // without a trusted chain proves nothing, so call ctls_ctx_trust() or
218 : // ctls_ctx_trust_system() too. It gives NULL, with a message in *err_str, for
219 : // a bad ctx or fd, a refused hostname, an allocation failure or a
220 : // verification target that can't be set.
221 : ctls_conn *ctls_conn_create_client(ctls_ctx *ctx, int fd, const char *hostname,
222 : bool verify_host, char **err_str);
223 :
224 : // Creates a server connection on an accepted fd, for an HTTPS server. ctx
225 : // needs a default certificate or the handshake fails (only the handshake
226 : // checks). udata comes back from ctls_conn_udata(). It gives NULL on failure,
227 : // with a message in *err_str.
228 : ctls_conn *ctls_conn_create_server(ctls_ctx *ctx, int fd, void *udata,
229 : char **err_str);
230 :
231 : // Drives one non-blocking handshake step, so a reactor or a blocking loop can
232 : // run the handshake without this module waiting. Call it again after the
233 : // readiness the result asks for. On DONE the agreed ALPN callback has fired
234 : // and reads and writes may start.
235 : //
236 : // ThreadSanitizer reports a race inside OpenSSL (ASN1_STRING_cmp against
237 : // ASN1_STRING_set) when many client handshakes share one trust store. Every
238 : // object this module owns is per connection and SSL_new() runs under the
239 : // context lock; a program with only libssl reproduces the report and neither
240 : // stack has a frame of ours. We add no lock around verification on purpose,
241 : // since it would serialize the handshakes. Revisit it only if a handshake
242 : // outcome is ever wrong.
243 : ctls_handshake_result ctls_conn_handshake_step(ctls_conn *conn);
244 :
245 : // Reads decrypted data into buf, like a non-blocking read(2), for the HTTP
246 : // modules' receive paths. -1 with EWOULDBLOCK may mean OpenSSL needs to write
247 : // first (a deferred session ticket, a TLS 1.2 renegotiation), so ask
248 : // ctls_conn_wants_write() which way to wait. It gives the bytes read, 0 after
249 : // close_notify or a socket close on a record boundary (as curl and Go
250 : // accept), 0 for a len of 0, or -1 with errno on an error; a close inside a
251 : // record is an error. Valid only after the handshake.
252 : ssize_t ctls_conn_read(ctls_conn *conn, void *buf, size_t len);
253 :
254 : // Encrypts and writes len bytes of buf, like a non-blocking write(2), for the
255 : // HTTP modules' send paths. EWOULDBLOCK may mean OpenSSL needs to read first,
256 : // so ask ctls_conn_wants_write(). It gives the bytes taken (partial writes are
257 : // on), 0 for a len of 0, or -1 with errno. Valid only after the handshake.
258 : ssize_t ctls_conn_write(ctls_conn *conn, const void *buf, size_t len);
259 :
260 : // Tells whether conn holds input ctls_conn_read() can take without a new
261 : // socket byte. It's needed because OpenSSL reads whole records (up to 16 KB),
262 : // so a small read leaves the rest in the TLS layer where poll(2) can't see it.
263 : // Call this before every wait for readability and read while it's true; it
264 : // can also cover the start of an incomplete record, and then the read gives
265 : // EWOULDBLOCK and waiting is correct. NULL gives false.
266 : bool ctls_conn_has_pending_input(const ctls_conn *conn);
267 :
268 : // Tells which readiness the last read or write that gave EWOULDBLOCK needs:
269 : // true for writable, false for readable (also the answer before any I/O).
270 : // Always waiting for the call's own direction can stall a connection forever
271 : // when OpenSSL needs the other one. NULL gives false.
272 : bool ctls_conn_wants_write(const ctls_conn *conn);
273 :
274 : // Gives the peer verification result (X509_V_OK or X509_V_ERR_*), so a caller
275 : // can tell a certificate failure from another handshake error.
276 : long ctls_conn_verify_result(const ctls_conn *conn);
277 :
278 : // Gives the agreed ALPN protocol, so a caller can pick the protocol to speak
279 : // (not NUL-terminated; its length goes to *len_out, which may be NULL), or
280 : // NULL when nothing was agreed.
281 : const char *ctls_conn_alpn_selected(const ctls_conn *conn, size_t *len_out);
282 :
283 : // Tells whether the peer presented a certificate and it verified against the
284 : // trust store, so a server handler can tell an authenticated client from an
285 : // anonymous one. False for NULL, before the handshake is done, without a
286 : // trust store, and for a peer that sent nothing. A resumed session gives the
287 : // answer of the handshake that made it.
288 : bool ctls_conn_peer_cert_verified(const ctls_conn *conn);
289 :
290 : // The length of a SHA-256 digest, the size of the buffer
291 : // ctls_conn_peer_cert_sha256() fills.
292 : #define CTLS_SHA256_LEN 32
293 :
294 : // Gives the DER encoding of the verified peer certificate, for handlers that
295 : // identify a client by its certificate. The bytes are owned by conn until
296 : // it's destroyed and the length goes to *len_out; NULL and 0 when there's none
297 : // or an allocation fails. It's made on first use, so (like every call on one
298 : // conn) it isn't safe from two threads at once.
299 : const unsigned char *ctls_conn_peer_cert_der(ctls_conn *conn, size_t *len_out);
300 :
301 : // Writes the SHA-256 of that DER encoding to out, a fingerprint for pinning or
302 : // logging a client. False, with out zeroed, when there's no verified
303 : // certificate or an allocation fails, and for a NULL out.
304 : bool ctls_conn_peer_cert_sha256(ctls_conn *conn,
305 : unsigned char out[CTLS_SHA256_LEN]);
306 :
307 : // Gives the verified peer certificate's subject as an RFC 2253 name
308 : // ("CN=client,O=Example"), for authorization and logs. It's escaped to
309 : // printable ASCII and owned by conn. NULL when there's no verified
310 : // certificate or an allocation fails.
311 : const char *ctls_conn_peer_cert_subject(ctls_conn *conn);
312 :
313 : // Gives the udata given to ctls_conn_create_server(), so an ALPN callback can
314 : // find the caller's connection object.
315 : void *ctls_conn_udata(const ctls_conn *conn);
316 :
317 : // Frees conn and its reference on ctx when a connection ends; it never closes
318 : // the fd. NULL is fine. After a finished handshake it first sends
319 : // close_notify, without holding a lock, and leaves the thread's OpenSSL error
320 : // queue empty either way. Then, briefly under the context lock, it frees the
321 : // SSL state and the references on every SSL_CTX it held, which orders its
322 : // last use of a shared SSL_CTX before a concurrent rebuild can free it. No
323 : // callback runs under that lock, so it may be called from anywhere, an ALPN
324 : // callback included.
325 : void ctls_conn_destroy(ctls_conn *conn);
|