1 /*
2 * mod_openssl - openssl support for lighttpd
3 *
4 * Fully-rewritten from original
5 * Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com All rights reserved
6 * License: BSD 3-clause (same as lighttpd)
7 */
8 /*
9 * Note: If session tickets are -not- disabled with
10 * ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
11 * mod_openssl rotates server ticket encryption key (STEK) every 8 hours
12 * and keeps the prior two STEKs around, so ticket lifetime is 24 hours.
13 * This is fine for use with a single lighttpd instance, but with multiple
14 * lighttpd workers, no coordinated STEK (server ticket encryption key)
15 * rotation occurs unless ssl.stek-file is defined and maintained (preferred),
16 * or if some external job restarts lighttpd. Restarting lighttpd generates a
17 * new key that is shared by lighttpd workers for the lifetime of the new key.
18 * If the rotation period expires and lighttpd has not been restarted, and if
19 * ssl.stek-file is not in use, then lighttpd workers will generate new
20 * independent keys, making session tickets less effective for session
21 * resumption, since clients have a lower chance for future connections to
22 * reach the same lighttpd worker. However, things will still work, and a new
23 * session will be created if session resumption fails. Admins should plan to
24 * restart lighttpd at least every 8 hours if session tickets are enabled and
25 * multiple lighttpd workers are configured. Since that is likely disruptive,
26 * if multiple lighttpd workers are configured, ssl.stek-file should be
27 * defined and the file maintained externally.
28 */
29 #include "first.h"
30
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include "sys-time.h"
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 /*(not needed)*/
41 /* correction; needed for:
42 * SSL_load_client_CA_file()
43 * X509_STORE_load_locations()
44 */
45 /*#define OPENSSL_NO_STDIO*/
46
47 #ifndef HAVE_KRB5
48 #ifndef OPENSSL_NO_KRB5
49 #define OPENSSL_NO_KRB5
50 #endif
51 #endif
52
53 #ifdef BORINGSSL_API_VERSION
54 #undef OPENSSL_NO_STDIO /* for X509_STORE_load_locations() */
55 #endif
56
57 #include <openssl/ssl.h>
58 #include <openssl/bio.h>
59 #include <openssl/bn.h>
60 #include <openssl/err.h>
61 #include <openssl/objects.h>
62 #include <openssl/pem.h>
63 #include <openssl/rand.h>
64 #include <openssl/tls1.h>
65 #ifndef OPENSSL_NO_DH
66 #include <openssl/dh.h>
67 #endif
68 #ifndef OPENSSL_NO_OCSP
69 #include <openssl/ocsp.h>
70 #endif
71 #ifdef BORINGSSL_API_VERSION
72 /* BoringSSL purports to have some OCSP support */
73 #undef OPENSSL_NO_OCSP
74 #endif
75
76 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
77 #ifndef OPENSSL_NO_ECDH
78 #include <openssl/ecdh.h>
79 #endif
80 #endif
81
82 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
83 #include <openssl/core_names.h>
84 #include <openssl/store.h>
85 #endif
86
87 #include "base.h"
88 #include "ck.h"
89 #include "fdevent.h"
90 #include "http_date.h"
91 #include "http_header.h"
92 #include "http_kv.h"
93 #include "log.h"
94 #include "plugin.h"
95
96 typedef struct {
97 /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
98 EVP_PKEY *ssl_pemfile_pkey;
99 X509 *ssl_pemfile_x509;
100 STACK_OF(X509) *ssl_pemfile_chain;
101 buffer *ssl_stapling;
102 const buffer *ssl_pemfile;
103 const buffer *ssl_privkey;
104 const buffer *ssl_stapling_file;
105 unix_time64_t ssl_stapling_loadts;
106 unix_time64_t ssl_stapling_nextts;
107 char must_staple;
108 char self_issued;
109 } plugin_cert;
110
111 typedef struct {
112 SSL_CTX *ssl_ctx;
113 } plugin_ssl_ctx;
114
115 typedef struct {
116 STACK_OF(X509_NAME) *names;
117 X509_STORE *certs;
118 } plugin_cacerts;
119
120 typedef struct {
121 SSL_CTX *ssl_ctx; /* output from network_init_ssl() */
122
123 /*(used only during startup; not patched)*/
124 unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
125 unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
126 const buffer *ssl_cipher_list;
127 array *ssl_conf_cmd;
128
129 /*(copied from plugin_data for socket ssl_ctx config)*/
130 const plugin_cert *pc;
131 const plugin_cacerts *ssl_ca_file;
132 STACK_OF(X509_NAME) *ssl_ca_dn_file;
133 const buffer *ssl_ca_crl_file;
134 unsigned char ssl_verifyclient;
135 unsigned char ssl_verifyclient_enforce;
136 unsigned char ssl_verifyclient_depth;
137 unsigned char ssl_read_ahead;
138 } plugin_config_socket; /*(used at startup during configuration)*/
139
140 typedef struct {
141 /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
142 plugin_cert *pc;
143 const plugin_cacerts *ssl_ca_file;
144 STACK_OF(X509_NAME) *ssl_ca_dn_file;
145 const buffer *ssl_ca_crl_file;
146
147 unsigned char ssl_verifyclient;
148 unsigned char ssl_verifyclient_enforce;
149 unsigned char ssl_verifyclient_depth;
150 unsigned char ssl_verifyclient_export_cert;
151 unsigned char ssl_read_ahead;
152 unsigned char ssl_log_noise;
153 const buffer *ssl_verifyclient_username;
154 const buffer *ssl_acme_tls_1;
155 } plugin_config;
156
157 typedef struct {
158 PLUGIN_DATA;
159 plugin_ssl_ctx *ssl_ctxs;
160 plugin_config defaults;
161 server *srv;
162 array *cafiles;
163 const char *ssl_stek_file;
164 } plugin_data;
165
166 static int ssl_is_init;
167 /* need assigned p->id for deep access of module handler_ctx for connection
168 * i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
169 static plugin_data *plugin_data_singleton;
170 #define LOCAL_SEND_BUFSIZE (16 * 1024)
171 static char *local_send_buffer;
172
173 typedef struct {
174 SSL *ssl;
175 request_st *r;
176 connection *con;
177 short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
178 short close_notify;
179 unsigned short alpn;
180 plugin_config conf;
181 buffer *tmp_buf;
182 log_error_st *errh;
183 } handler_ctx;
184
185
186 static handler_ctx *
handler_ctx_init(void)187 handler_ctx_init (void)
188 {
189 return ck_calloc(1, sizeof(handler_ctx));
190 }
191
192
193 static void
handler_ctx_free(handler_ctx * hctx)194 handler_ctx_free (handler_ctx *hctx)
195 {
196 if (hctx->ssl) SSL_free(hctx->ssl);
197 free(hctx);
198 }
199
200
201 #ifdef TLSEXT_TYPE_session_ticket
202 /* ssl/ssl_local.h */
203 #define TLSEXT_KEYNAME_LENGTH 16
204 #define TLSEXT_TICK_KEY_LENGTH 32
205
206 /* openssl has a huge number of interfaces, but not the most useful;
207 * construct our own session ticket encryption key structure */
208 typedef struct tlsext_ticket_key_st {
209 unix_time64_t active_ts; /* tickets not issued w/ key until activation ts*/
210 unix_time64_t expire_ts; /* key not valid after expiration timestamp */
211 unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
212 unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
213 unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
214 } tlsext_ticket_key_t;
215
216 static tlsext_ticket_key_t session_ticket_keys[4];
217 static unix_time64_t stek_rotate_ts;
218
219
220 static int
mod_openssl_session_ticket_key_generate(unix_time64_t active_ts,unix_time64_t expire_ts)221 mod_openssl_session_ticket_key_generate (unix_time64_t active_ts, unix_time64_t expire_ts)
222 {
223 /* openssl RAND_*bytes() functions are called multiple times since the
224 * funcs might have a 32-byte limit on number of bytes returned each call
225 *
226 * (Note: session ticket encryption key generation is not expected to fail)
227 *
228 * 3 keys are stored in session_ticket_keys[]
229 * The 4th element of session_ticket_keys[] is used for STEK construction
230 */
231 /*(RAND_priv_bytes() not in openssl 1.1.0; introduced in openssl 1.1.1)*/
232 #if OPENSSL_VERSION_NUMBER < 0x10101000L \
233 || defined(BORINGSSL_API_VERSION) \
234 || defined(LIBRESSL_VERSION_NUMBER)
235 #define RAND_priv_bytes(x,sz) RAND_bytes((x),(sz))
236 #endif
237 if (RAND_bytes(session_ticket_keys[3].tick_key_name,
238 TLSEXT_KEYNAME_LENGTH) <= 0
239 || RAND_priv_bytes(session_ticket_keys[3].tick_hmac_key,
240 TLSEXT_TICK_KEY_LENGTH) <= 0
241 || RAND_priv_bytes(session_ticket_keys[3].tick_aes_key,
242 TLSEXT_TICK_KEY_LENGTH) <= 0)
243 return 0;
244 session_ticket_keys[3].active_ts = active_ts;
245 session_ticket_keys[3].expire_ts = expire_ts;
246 return 1;
247 }
248
249
250 static void
mod_openssl_session_ticket_key_rotate(void)251 mod_openssl_session_ticket_key_rotate (void)
252 {
253 /* discard oldest key (session_ticket_keys[2]) and put newest key first
254 * 3 keys are stored in session_ticket_keys[0], [1], [2]
255 * session_ticket_keys[3] is used to construct and pass new STEK */
256
257 session_ticket_keys[2] = session_ticket_keys[1];
258 session_ticket_keys[1] = session_ticket_keys[0];
259 /*memmove(session_ticket_keys+1,
260 session_ticket_keys+0, sizeof(tlsext_ticket_key_t)*2);*/
261 session_ticket_keys[0] = session_ticket_keys[3];
262
263 OPENSSL_cleanse(session_ticket_keys+3, sizeof(tlsext_ticket_key_t));
264 }
265
266
267 static tlsext_ticket_key_t *
tlsext_ticket_key_get(void)268 tlsext_ticket_key_get (void)
269 {
270 const unix_time64_t cur_ts = log_epoch_secs;
271 const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
272 for (int i = 0; i < e; ++i) {
273 if (session_ticket_keys[i].active_ts > cur_ts) continue;
274 if (session_ticket_keys[i].expire_ts < cur_ts) continue;
275 return &session_ticket_keys[i];
276 }
277 return NULL;
278 }
279
280
281 static tlsext_ticket_key_t *
tlsext_ticket_key_find(unsigned char key_name[16],int * refresh)282 tlsext_ticket_key_find (unsigned char key_name[16], int *refresh)
283 {
284 *refresh = 0;
285 const unix_time64_t cur_ts = log_epoch_secs;
286 const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
287 for (int i = 0; i < e; ++i) {
288 if (session_ticket_keys[i].expire_ts < cur_ts) continue;
289 if (0 == memcmp(session_ticket_keys[i].tick_key_name, key_name, 16))
290 return &session_ticket_keys[i];
291 if (session_ticket_keys[i].active_ts <= cur_ts)
292 *refresh = 1; /* newer active key is available */
293 }
294 return NULL;
295 }
296
297
298 static void
tlsext_ticket_wipe_expired(const unix_time64_t cur_ts)299 tlsext_ticket_wipe_expired (const unix_time64_t cur_ts)
300 {
301 const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
302 for (int i = 0; i < e; ++i) {
303 if (session_ticket_keys[i].expire_ts != 0
304 && session_ticket_keys[i].expire_ts < cur_ts)
305 OPENSSL_cleanse(session_ticket_keys+i, sizeof(tlsext_ticket_key_t));
306 }
307 }
308
309
310 #if OPENSSL_VERSION_NUMBER < 0x30000000L
311 /* based on reference implementation from openssl 1.1.1g man page
312 * man SSL_CTX_set_tlsext_ticket_key_cb
313 * but mod_openssl code uses EVP_aes_256_cbc() instead of EVP_aes_128_cbc()
314 */
315 static int
ssl_tlsext_ticket_key_cb(SSL * s,unsigned char key_name[16],unsigned char iv[EVP_MAX_IV_LENGTH],EVP_CIPHER_CTX * ctx,HMAC_CTX * hctx,int enc)316 ssl_tlsext_ticket_key_cb (SSL *s, unsigned char key_name[16],
317 unsigned char iv[EVP_MAX_IV_LENGTH],
318 EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
319 #else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
320 /* based on reference implementation from openssl 3.0.0 man page
321 * man SSL_CTX_set_tlsext_ticket_key_cb
322 */
323 static int
324 ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16],
325 unsigned char *iv, EVP_CIPHER_CTX *ctx,
326 EVP_MAC_CTX *hctx, int enc)
327 #endif
328 {
329 UNUSED(s);
330 if (enc) { /* create new session */
331 tlsext_ticket_key_t *k = tlsext_ticket_key_get();
332 if (NULL == k)
333 return 0; /* current key does not exist or is not valid */
334 memcpy(key_name, k->tick_key_name, 16);
335 if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
336 return -1; /* insufficient random */
337 EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
338 #if OPENSSL_VERSION_NUMBER < 0x30000000L
339 HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
340 EVP_sha256(), NULL);
341 #else
342 OSSL_PARAM params[] = {
343 OSSL_PARAM_DEFN(OSSL_MAC_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
344 k->tick_hmac_key, sizeof(k->tick_hmac_key)),
345 OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
346 "sha256", sizeof("sha256")),
347 OSSL_PARAM_END
348 };
349 EVP_MAC_CTX_set_params(hctx, params);
350 #endif
351 return 1;
352 }
353 else { /* retrieve session */
354 int refresh;
355 tlsext_ticket_key_t *k = tlsext_ticket_key_find(key_name, &refresh);
356 if (NULL == k)
357 return 0;
358 #if OPENSSL_VERSION_NUMBER < 0x30000000L
359 HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
360 EVP_sha256(), NULL);
361 #else
362 OSSL_PARAM params[] = {
363 OSSL_PARAM_DEFN(OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
364 k->tick_hmac_key, sizeof(k->tick_hmac_key)),
365 OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
366 "sha256", sizeof("sha256")),
367 OSSL_PARAM_END
368 };
369 EVP_MAC_CTX_set_params(hctx, params);
370 #endif
371 EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
372 return refresh ? 2 : 1;
373 /* 'refresh' will trigger issuing new ticket for session
374 * even though the current ticket is still valid */
375 }
376 }
377
378
379 static int
mod_openssl_session_ticket_key_file(const char * fn)380 mod_openssl_session_ticket_key_file (const char *fn)
381 {
382 /* session ticket encryption key (STEK)
383 *
384 * STEK file should be stored in non-persistent storage,
385 * e.g. /dev/shm/lighttpd/stek-file (in memory)
386 * with appropriate permissions set to keep stek-file from being
387 * read by other users. Where possible, systems should also be
388 * configured without swap.
389 *
390 * admin should schedule an independent job to periodically
391 * generate new STEK up to 3 times during key lifetime
392 * (lighttpd stores up to 3 keys)
393 *
394 * format of binary file is:
395 * 4-byte - format version (always 0; for use if format changes)
396 * 4-byte - activation timestamp
397 * 4-byte - expiration timestamp
398 * 16-byte - session ticket key name
399 * 32-byte - session ticket HMAC encrpytion key
400 * 32-byte - session ticket AES encrpytion key
401 *
402 * STEK file can be created with a command such as:
403 * dd if=/dev/random bs=1 count=80 status=none | \
404 * perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
405 * > STEK-file.$$ && mv STEK-file.$$ STEK-file
406 *
407 * The above delays activation time by 5 mins (+300 sec) to allow file to
408 * be propagated to other machines. (admin must handle this independently)
409 * If STEK generation is performed immediately prior to starting lighttpd,
410 * admin should activate keys immediately (without +300).
411 */
412 int buf[23]; /* 92 bytes */
413 int rc = 0; /*(will retry on next check interval upon any error)*/
414 if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
415 return rc;
416 if (buf[0] == 0) { /*(format version 0)*/
417 session_ticket_keys[3].active_ts = TIME64_CAST(buf[1]);
418 session_ticket_keys[3].expire_ts = TIME64_CAST(buf[2]);
419 #ifndef __COVERITY__ /* intentional; hide from Coverity Scan */
420 /* intentionally copy 80 bytes into consecutive arrays
421 * tick_key_name[], tick_hmac_key[], tick_aes_key[] */
422 memcpy(&session_ticket_keys[3].tick_key_name, buf+3, 80);
423 #endif
424 rc = 1;
425 }
426
427 OPENSSL_cleanse(buf, sizeof(buf));
428 return rc;
429 }
430
431
432 static void
mod_openssl_session_ticket_key_check(const plugin_data * p,const unix_time64_t cur_ts)433 mod_openssl_session_ticket_key_check (const plugin_data *p, const unix_time64_t cur_ts)
434 {
435 static unix_time64_t detect_retrograde_ts;
436 if (detect_retrograde_ts > cur_ts && detect_retrograde_ts - cur_ts > 28800)
437 stek_rotate_ts = 0;
438 detect_retrograde_ts = cur_ts;
439
440 int rotate = 0;
441 if (p->ssl_stek_file) {
442 struct stat st;
443 if (0 == stat(p->ssl_stek_file, &st)
444 && TIME64_CAST(st.st_mtime) > stek_rotate_ts)
445 rotate = mod_openssl_session_ticket_key_file(p->ssl_stek_file);
446 tlsext_ticket_wipe_expired(cur_ts);
447 }
448 else if (cur_ts - 28800 >= stek_rotate_ts || 0 == stek_rotate_ts)/*(8 hrs)*/
449 rotate = mod_openssl_session_ticket_key_generate(cur_ts, cur_ts+86400);
450
451 if (rotate) {
452 mod_openssl_session_ticket_key_rotate();
453 stek_rotate_ts = cur_ts;
454 }
455 }
456
457 #endif /* TLSEXT_TYPE_session_ticket */
458
459
460 #ifndef OPENSSL_NO_OCSP
461 #ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
462 static int
ssl_tlsext_status_cb(SSL * ssl,void * arg)463 ssl_tlsext_status_cb(SSL *ssl, void *arg)
464 {
465 #ifdef SSL_get_tlsext_status_type
466 if (TLSEXT_STATUSTYPE_ocsp != SSL_get_tlsext_status_type(ssl))
467 return SSL_TLSEXT_ERR_NOACK; /* ignore if not client OCSP request */
468 #endif
469
470 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
471 if (NULL == hctx->conf.pc) return SSL_TLSEXT_ERR_NOACK;/*should not happen*/
472 buffer *ssl_stapling = hctx->conf.pc->ssl_stapling;
473 if (NULL == ssl_stapling) return SSL_TLSEXT_ERR_NOACK;
474 UNUSED(arg);
475
476 int len = (int)buffer_clen(ssl_stapling);
477
478 /* OpenSSL and LibreSSL require copy (BoringSSL, too, if using compat API)*/
479 uint8_t *ocsp_resp = OPENSSL_malloc(len);
480 if (NULL == ocsp_resp)
481 return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
482 memcpy(ocsp_resp, ssl_stapling->ptr, len);
483
484 if (!SSL_set_tlsext_status_ocsp_resp(ssl, ocsp_resp, len)) {
485 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
486 "SSL: failed to set OCSP response for TLS server name %s: %s",
487 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
488 OPENSSL_free(ocsp_resp);
489 return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
490 /*return SSL_TLSEXT_ERR_ALERT_FATAL;*/
491 }
492 return SSL_TLSEXT_ERR_OK;
493 }
494 #endif
495 #endif
496
497
INIT_FUNC(mod_openssl_init)498 INIT_FUNC(mod_openssl_init)
499 {
500 plugin_data_singleton = (plugin_data *)ck_calloc(1, sizeof(plugin_data));
501 return plugin_data_singleton;
502 }
503
504
mod_openssl_init_once_openssl(server * srv)505 static int mod_openssl_init_once_openssl (server *srv)
506 {
507 if (ssl_is_init) return 1;
508
509 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
510 && (!defined(LIBRESSL_VERSION_NUMBER) \
511 || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
512 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
513 |OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
514 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
515 |OPENSSL_INIT_ADD_ALL_DIGESTS
516 |OPENSSL_INIT_LOAD_CONFIG, NULL);
517 #else
518 SSL_load_error_strings();
519 SSL_library_init();
520 OpenSSL_add_all_algorithms();
521 #endif
522 ssl_is_init = 1;
523
524 if (0 == RAND_status()) {
525 log_error(srv->errh, __FILE__, __LINE__,
526 "SSL: not enough entropy in the pool");
527 return 0;
528 }
529
530 local_send_buffer = ck_malloc(LOCAL_SEND_BUFSIZE);
531 return 1;
532 }
533
534
mod_openssl_free_openssl(void)535 static void mod_openssl_free_openssl (void)
536 {
537 if (!ssl_is_init) return;
538
539 #ifdef TLSEXT_TYPE_session_ticket
540 OPENSSL_cleanse(session_ticket_keys, sizeof(session_ticket_keys));
541 stek_rotate_ts = 0;
542 #endif
543
544 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
545 && !defined(LIBRESSL_VERSION_NUMBER)
546 /*(OpenSSL libraries handle thread init and deinit)
547 * https://github.com/openssl/openssl/pull/1048 */
548 #else
549 CRYPTO_cleanup_all_ex_data();
550 ERR_free_strings();
551 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
552 ERR_remove_thread_state(NULL);
553 #else
554 ERR_remove_state(0);
555 #endif
556 EVP_cleanup();
557 #endif
558
559 free(local_send_buffer);
560 ssl_is_init = 0;
561 }
562
563
564 static void
mod_openssl_free_config(server * srv,plugin_data * const p)565 mod_openssl_free_config (server *srv, plugin_data * const p)
566 {
567 array_free(p->cafiles);
568
569 if (NULL != p->ssl_ctxs) {
570 SSL_CTX * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
571 /* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
572 for (uint32_t i = 1; i < srv->config_context->used; ++i) {
573 plugin_ssl_ctx * const s = p->ssl_ctxs + i;
574 if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope)
575 SSL_CTX_free(s->ssl_ctx);
576 }
577 /* free ssl_ctx from global scope */
578 if (ssl_ctx_global_scope)
579 SSL_CTX_free(ssl_ctx_global_scope);
580 free(p->ssl_ctxs);
581 }
582
583 if (NULL == p->cvlist) return;
584 /* (init i to 0 if global context; to 1 to skip empty global context) */
585 for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
586 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
587 for (; -1 != cpv->k_id; ++cpv) {
588 switch (cpv->k_id) {
589 case 0: /* ssl.pemfile */
590 if (cpv->vtype == T_CONFIG_LOCAL) {
591 plugin_cert *pc = cpv->v.v;
592 EVP_PKEY_free(pc->ssl_pemfile_pkey);
593 X509_free(pc->ssl_pemfile_x509);
594 sk_X509_pop_free(pc->ssl_pemfile_chain, X509_free);
595 buffer_free(pc->ssl_stapling);
596 free(pc);
597 }
598 break;
599 case 2: /* ssl.ca-file */
600 if (cpv->vtype == T_CONFIG_LOCAL) {
601 plugin_cacerts *cacerts = cpv->v.v;
602 sk_X509_NAME_pop_free(cacerts->names, X509_NAME_free);
603 X509_STORE_free(cacerts->certs);
604 free(cacerts);
605 }
606 break;
607 case 3: /* ssl.ca-dn-file */
608 if (cpv->vtype == T_CONFIG_LOCAL)
609 sk_X509_NAME_pop_free(cpv->v.v, X509_NAME_free);
610 break;
611 default:
612 break;
613 }
614 }
615 }
616 }
617
618
619 /* use memory from openssl secure heap for temporary buffers, returned storage
620 * (pemfile might contain a private key in addition to certificate chain)
621 * Interfaces similar to those constructed in include/openssl/pem.h for
622 * PEM_read_bio_X509(), except this is named PEM_read_bio_X509_secmem().
623 * Similar for PEM_read_bio_X509_AUX_secmem().
624 *
625 * Supporting routine PEM_ASN1_read_bio_secmem() modified from openssl
626 * crypto/pem/pem_oth.c:PEM_ASN1_read_bio():
627 * uses PEM_bytes_read_bio_secmem() instead of PEM_bytes_read_bio()
628 * uses OPENSSL_secure_clear_free() instead of OPENSSL_free()
629 *
630 * 'man PEM_bytes_read_bio_secmem()' and see NOTES section for more info
631 * PEM_bytes_read_bio_secmem() openssl 1.1.1 or later
632 * OPENSSL_secure_clear_free() openssl 1.1.0g or later
633 * As this comment is being written, only openssl 1.1.1 is actively maintained.
634 * Earlier vers of openssl no longer receive security patches from openssl.org.
635 */
636 static void *
PEM_ASN1_read_bio_secmem(d2i_of_void * d2i,const char * name,BIO * bp,void ** x,pem_password_cb * cb,void * u)637 PEM_ASN1_read_bio_secmem(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
638 pem_password_cb *cb, void *u)
639 {
640 const unsigned char *p = NULL;
641 unsigned char *data = NULL;
642 long len = 0;
643 char *ret = NULL;
644
645 #if OPENSSL_VERSION_NUMBER >= 0x10101000L \
646 && !defined(BORINGSSL_API_VERSION) \
647 && !defined(LIBRESSL_VERSION_NUMBER)
648 if (!PEM_bytes_read_bio_secmem(&data, &len, NULL, name, bp, cb, u))
649 #else
650 if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
651 #endif
652 return NULL;
653 p = data;
654 ret = d2i(x, &p, len);
655 #ifndef BORINGSSL_API_VERSION /* missing PEMerr() macro */
656 if (ret == NULL)
657 PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB);
658 #endif
659 /* boringssl provides OPENSSL_secure_clear_free() in commit
660 * 8a1542fc41b43bdcd67cd341c1d332d2e05e2340 (not yet in a release)
661 * (note: boringssl already calls OPENSSL_cleanse() in OPENSSL_free()) */
662 #if OPENSSL_VERSION_NUMBER >= 0x10101000L \
663 && !defined(BORINGSSL_API_VERSION) \
664 && !defined(LIBRESSL_VERSION_NUMBER)
665 OPENSSL_secure_clear_free(data, len);
666 #else
667 OPENSSL_cleanse(data, len);
668 OPENSSL_free(data);
669 #endif
670 return ret;
671 }
672
673
674 static X509 *
PEM_read_bio_X509_secmem(BIO * bp,X509 ** x,pem_password_cb * cb,void * u)675 PEM_read_bio_X509_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
676 {
677 return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509,
678 PEM_STRING_X509,
679 bp, (void **)x, cb, u);
680 }
681
682
683 static X509 *
PEM_read_bio_X509_AUX_secmem(BIO * bp,X509 ** x,pem_password_cb * cb,void * u)684 PEM_read_bio_X509_AUX_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
685 {
686 return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509_AUX,
687 PEM_STRING_X509_TRUSTED,
688 bp, (void **)x, cb, u);
689 }
690
691
692 static int
mod_openssl_load_X509_sk(const char * file,log_error_st * errh,STACK_OF (X509)** chain,BIO * in)693 mod_openssl_load_X509_sk (const char *file, log_error_st *errh, STACK_OF(X509) **chain, BIO *in)
694 {
695 STACK_OF(X509) *chain_sk = NULL;
696 for (X509 *ca; (ca = PEM_read_bio_X509_secmem(in,NULL,NULL,NULL)); ) {
697 if (NULL == chain_sk) /*(allocate only if it will not be empty)*/
698 chain_sk = sk_X509_new_null();
699 if (!chain_sk || !sk_X509_push(chain_sk, ca)) {
700 log_error(errh, __FILE__, __LINE__,
701 "SSL: couldn't read X509 certificates from '%s'", file);
702 if (chain_sk) sk_X509_pop_free(chain_sk, X509_free);
703 X509_free(ca);
704 return 0;
705 }
706 }
707 *chain = chain_sk;
708 return 1;
709 }
710
711
712 static int
mod_openssl_load_X509_STORE(const char * file,log_error_st * errh,X509_STORE ** chain,BIO * in)713 mod_openssl_load_X509_STORE (const char *file, log_error_st *errh, X509_STORE **chain, BIO *in)
714 {
715 X509_STORE *chain_store = NULL;
716 for (X509 *ca; (ca = PEM_read_bio_X509(in,NULL,NULL,NULL)); X509_free(ca)) {
717 if (NULL == chain_store) /*(allocate only if it will not be empty)*/
718 chain_store = X509_STORE_new();
719 if (!chain_store || !X509_STORE_add_cert(chain_store, ca)) {
720 log_error(errh, __FILE__, __LINE__,
721 "SSL: couldn't read X509 certificates from '%s'", file);
722 if (chain_store) X509_STORE_free(chain_store);
723 X509_free(ca);
724 return 0;
725 }
726 }
727 *chain = chain_store;
728 return 1;
729 }
730
731
732 static plugin_cacerts *
mod_openssl_load_cacerts(const buffer * ssl_ca_file,log_error_st * errh)733 mod_openssl_load_cacerts (const buffer *ssl_ca_file, log_error_st *errh)
734 {
735 const char *file = ssl_ca_file->ptr;
736 BIO *in = BIO_new(BIO_s_file());
737 if (NULL == in) {
738 log_error(errh, __FILE__, __LINE__,
739 "SSL: BIO_new(BIO_s_file()) failed");
740 return NULL;
741 }
742
743 if (BIO_read_filename(in, file) <= 0) {
744 log_error(errh, __FILE__, __LINE__,
745 "SSL: BIO_read_filename('%s') failed", file);
746 BIO_free(in);
747 return NULL;
748 }
749
750 X509_STORE *chain_store = NULL;
751 if (!mod_openssl_load_X509_STORE(file, errh, &chain_store, in)) {
752 BIO_free(in);
753 return NULL;
754 }
755
756 BIO_free(in);
757
758 if (NULL == chain_store) {
759 log_error(errh, __FILE__, __LINE__,
760 "SSL: ssl.verifyclient.ca-file is empty %s", file);
761 return NULL;
762 }
763
764 plugin_cacerts *cacerts = ck_malloc(sizeof(plugin_cacerts));
765
766 /* (would be more efficient to walk the X509_STORE and build the list,
767 * but this works for now and matches how ssl.ca-dn-file is handled) */
768 cacerts->names = SSL_load_client_CA_file(file);
769 if (NULL == cacerts->names) {
770 X509_STORE_free(chain_store);
771 free(cacerts);
772 return NULL;
773 }
774
775 cacerts->certs = chain_store;
776 return cacerts;
777 }
778
779
780 static int
mod_openssl_load_cacrls(X509_STORE * store,const buffer * ssl_ca_crl_file,server * srv)781 mod_openssl_load_cacrls (X509_STORE *store, const buffer *ssl_ca_crl_file, server *srv)
782 {
783 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
784 if (1 != X509_STORE_load_file(store, ssl_ca_crl_file->ptr))
785 #else
786 if (1 != X509_STORE_load_locations(store, ssl_ca_crl_file->ptr, NULL))
787 #endif
788 {
789 log_error(srv->errh, __FILE__, __LINE__,
790 "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
791 ssl_ca_crl_file->ptr);
792 return 0;
793 }
794 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
795 return 1;
796 }
797
798
799 #if OPENSSL_VERSION_NUMBER < 0x10002000 \
800 || defined(LIBRESSL_VERSION_NUMBER)
801 static int
mod_openssl_load_verify_locn(SSL_CTX * ssl_ctx,const buffer * b,server * srv)802 mod_openssl_load_verify_locn (SSL_CTX *ssl_ctx, const buffer *b, server *srv)
803 {
804 const char *fn = b->ptr;
805 if (1 == SSL_CTX_load_verify_locations(ssl_ctx, fn, NULL))
806 return 1;
807
808 log_error(srv->errh, __FILE__, __LINE__,
809 "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), fn);
810 return 0;
811 }
812
813
814 static int
mod_openssl_load_ca_files(SSL_CTX * ssl_ctx,plugin_data * p,server * srv)815 mod_openssl_load_ca_files (SSL_CTX *ssl_ctx, plugin_data *p, server *srv)
816 {
817 /* load all ssl.ca-files specified in the config into each SSL_CTX */
818
819 for (uint32_t i = 0, used = p->cafiles->used; i < used; ++i) {
820 const buffer *b = &((data_string *)p->cafiles->data[i])->value;
821 if (!mod_openssl_load_verify_locn(ssl_ctx, b, srv))
822 return 0;
823 }
824 return 1;
825 }
826 #endif
827
828
FREE_FUNC(mod_openssl_free)829 FREE_FUNC(mod_openssl_free)
830 {
831 plugin_data *p = p_d;
832 if (NULL == p->srv) return;
833 mod_openssl_free_config(p->srv, p);
834 mod_openssl_free_openssl();
835 }
836
837
838 static void
mod_openssl_merge_config_cpv(plugin_config * const pconf,const config_plugin_value_t * const cpv)839 mod_openssl_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
840 {
841 switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
842 case 0: /* ssl.pemfile */
843 if (cpv->vtype == T_CONFIG_LOCAL)
844 pconf->pc = cpv->v.v;
845 break;
846 case 1: /* ssl.privkey */
847 break;
848 case 2: /* ssl.ca-file */
849 if (cpv->vtype == T_CONFIG_LOCAL)
850 pconf->ssl_ca_file = cpv->v.v;
851 break;
852 case 3: /* ssl.ca-dn-file */
853 if (cpv->vtype == T_CONFIG_LOCAL)
854 pconf->ssl_ca_dn_file = cpv->v.v;
855 break;
856 case 4: /* ssl.ca-crl-file */
857 pconf->ssl_ca_crl_file = cpv->v.b;
858 break;
859 case 5: /* ssl.read-ahead */
860 pconf->ssl_read_ahead = (0 != cpv->v.u);
861 break;
862 case 6: /* ssl.disable-client-renegotiation */
863 /*(ignored; unsafe renegotiation disabled by default)*/
864 break;
865 case 7: /* ssl.verifyclient.activate */
866 pconf->ssl_verifyclient = (0 != cpv->v.u);
867 break;
868 case 8: /* ssl.verifyclient.enforce */
869 pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
870 break;
871 case 9: /* ssl.verifyclient.depth */
872 pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
873 break;
874 case 10:/* ssl.verifyclient.username */
875 pconf->ssl_verifyclient_username = cpv->v.b;
876 break;
877 case 11:/* ssl.verifyclient.exportcert */
878 pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
879 break;
880 case 12:/* ssl.acme-tls-1 */
881 pconf->ssl_acme_tls_1 = cpv->v.b;
882 break;
883 case 13:/* ssl.stapling-file */
884 break;
885 case 14:/* debug.log-ssl-noise */
886 pconf->ssl_log_noise = (0 != cpv->v.u);
887 break;
888 #if 0 /*(cpk->k_id remapped in mod_openssl_set_defaults())*/
889 case 15:/* ssl.verifyclient.ca-file */
890 case 16:/* ssl.verifyclient.ca-dn-file */
891 case 17:/* ssl.verifyclient.ca-crl-file */
892 break;
893 #endif
894 default:/* should not happen */
895 return;
896 }
897 }
898
899
900 static void
mod_openssl_merge_config(plugin_config * const pconf,const config_plugin_value_t * cpv)901 mod_openssl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
902 {
903 do {
904 mod_openssl_merge_config_cpv(pconf, cpv);
905 } while ((++cpv)->k_id != -1);
906 }
907
908
909 static void
mod_openssl_patch_config(request_st * const r,plugin_config * const pconf)910 mod_openssl_patch_config (request_st * const r, plugin_config * const pconf)
911 {
912 plugin_data * const p = plugin_data_singleton;
913 memcpy(pconf, &p->defaults, sizeof(plugin_config));
914 for (int i = 1, used = p->nconfig; i < used; ++i) {
915 if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
916 mod_openssl_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
917 }
918 }
919
920
921 static int
safer_X509_NAME_oneline(X509_NAME * name,char * buf,size_t sz)922 safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
923 {
924 BIO *bio = BIO_new(BIO_s_mem());
925 if (bio) {
926 int len = X509_NAME_print_ex(bio, name, 0,
927 XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);
928 BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
929 BIO_free(bio);
930 return len; /*return value has similar semantics to that of snprintf()*/
931 }
932 else {
933 buf[0] = '\0';
934 return -1;
935 }
936 }
937
938
939 static void
ssl_info_callback(const SSL * ssl,int where,int ret)940 ssl_info_callback (const SSL *ssl, int where, int ret)
941 {
942 UNUSED(ret);
943
944 if (0 != (where & SSL_CB_HANDSHAKE_START)) {
945 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
946 if (hctx->renegotiations >= 0) ++hctx->renegotiations;
947 }
948 #ifdef TLS1_3_VERSION
949 /* https://github.com/openssl/openssl/issues/5721
950 * "TLSv1.3 unexpected InfoCallback after handshake completed" */
951 if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
952 /* SSL_version() is valid after initial handshake completed */
953 if (SSL_version(ssl) >= TLS1_3_VERSION) {
954 /* https://wiki.openssl.org/index.php/TLS1.3
955 * "Renegotiation is not possible in a TLSv1.3 connection" */
956 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
957 hctx->renegotiations = -1;
958 }
959 }
960 #endif
961 }
962
963 /* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
964 static int
verify_callback(int preverify_ok,X509_STORE_CTX * ctx)965 verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
966 {
967 char buf[256];
968 X509 *err_cert;
969 int err, depth;
970 SSL *ssl;
971 handler_ctx *hctx;
972
973 err = X509_STORE_CTX_get_error(ctx);
974 depth = X509_STORE_CTX_get_error_depth(ctx);
975
976 /*
977 * Retrieve the pointer to the SSL of the connection currently treated
978 * and the application specific data stored into the SSL object.
979 */
980 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
981 hctx = (handler_ctx *) SSL_get_app_data(ssl);
982
983 /*
984 * Catch a too long certificate chain. The depth limit set using
985 * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
986 * that whenever the "depth>verify_depth" condition is met, we
987 * have violated the limit and want to log this error condition.
988 * We must do it here, because the CHAIN_TOO_LONG error would not
989 * be found explicitly; only errors introduced by cutting off the
990 * additional certificates would be logged.
991 */
992 if (depth > hctx->conf.ssl_verifyclient_depth) {
993 preverify_ok = 0;
994 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
995 X509_STORE_CTX_set_error(ctx, err);
996 }
997
998 if (preverify_ok && 0 == depth && NULL != hctx->conf.ssl_ca_dn_file) {
999 /* verify that client cert is issued by CA in ssl.ca-dn-file
1000 * if both ssl.ca-dn-file and ssl.ca-file were configured */
1001 STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file;
1002 X509_NAME *issuer;
1003 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1004 err_cert = X509_STORE_CTX_get_current_cert(ctx);
1005 #else
1006 err_cert = ctx->current_cert;
1007 #endif
1008 if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
1009 issuer = X509_get_issuer_name(err_cert);
1010 #if 0 /*(?desirable/undesirable to have cert_names sorted?)*/
1011 if (-1 != sk_X509_NAME_find(cert_names, issuer))
1012 return preverify_ok; /* match */
1013 #else
1014 for (int i = 0, len = sk_X509_NAME_num(cert_names); i < len; ++i) {
1015 if (0 == X509_NAME_cmp(sk_X509_NAME_value(cert_names, i), issuer))
1016 return preverify_ok; /* match */
1017 }
1018 #endif
1019
1020 preverify_ok = 0;
1021 err = X509_V_ERR_CERT_REJECTED;
1022 X509_STORE_CTX_set_error(ctx, err);
1023 }
1024
1025 if (preverify_ok) {
1026 return preverify_ok;
1027 }
1028
1029 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1030 err_cert = X509_STORE_CTX_get_current_cert(ctx);
1031 #else
1032 err_cert = ctx->current_cert;
1033 #endif
1034 if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
1035 safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf));
1036 log_error_st *errh = hctx->r->conf.errh;
1037 log_error(errh, __FILE__, __LINE__,
1038 "SSL: verify error:num=%d:%s:depth=%d:subject=%s",
1039 err, X509_verify_cert_error_string(err), depth, buf);
1040
1041 /*
1042 * At this point, err contains the last verification error. We can use
1043 * it for something special
1044 */
1045 if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
1046 err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
1047 safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf));
1048 log_error(errh, __FILE__, __LINE__, "SSL: issuer=%s", buf);
1049 }
1050
1051 return !hctx->conf.ssl_verifyclient_enforce;
1052 }
1053
1054 enum {
1055 MOD_OPENSSL_ALPN_HTTP11 = 1
1056 ,MOD_OPENSSL_ALPN_HTTP10 = 2
1057 ,MOD_OPENSSL_ALPN_H2 = 3
1058 ,MOD_OPENSSL_ALPN_ACME_TLS_1 = 4
1059 };
1060
1061 static int
mod_openssl_cert_cb(SSL * ssl,void * arg)1062 mod_openssl_cert_cb (SSL *ssl, void *arg)
1063 {
1064 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1065 plugin_cert *pc = hctx->conf.pc;
1066 UNUSED(arg);
1067 if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) return 1;
1068
1069 if (!pc || NULL == pc->ssl_pemfile_x509 || NULL == pc->ssl_pemfile_pkey) {
1070 /* x509/pkey available <=> pemfile was set <=> pemfile got patched:
1071 * so this should never happen, unless you nest $SERVER["socket"] */
1072 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1073 "SSL: no certificate/private key for TLS server name \"%s\". "
1074 "$SERVER[\"socket\"] should not be nested in other conditions.",
1075 hctx->r->uri.authority.ptr);
1076 return 0;
1077 }
1078
1079 /* first set certificate!
1080 * setting private key checks whether certificate matches it */
1081 if (1 != SSL_use_certificate(ssl, pc->ssl_pemfile_x509)) {
1082 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1083 "SSL: failed to set certificate for TLS server name %s: %s",
1084 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1085 return 0;
1086 }
1087
1088 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
1089 && (!defined(LIBRESSL_VERSION_NUMBER) \
1090 || LIBRESSL_VERSION_NUMBER >= 0x3000000fL)
1091 if (pc->ssl_pemfile_chain)
1092 SSL_set1_chain(ssl, pc->ssl_pemfile_chain);
1093 #if !defined(BORINGSSL_API_VERSION) \
1094 && !defined(LIBRESSL_VERSION_NUMBER)
1095 /* (missing SSL_set1_chain_cert_store() and SSL_build_cert_chain()) */
1096 else if (hctx->conf.ssl_ca_file && !pc->self_issued) {
1097 /* preserve legacy behavior whereby openssl will reuse CAs trusted for
1098 * certificate verification (set by SSL_CTX_load_verify_locations() in
1099 * SSL_CTX) in order to build certificate chain for server certificate
1100 * sent to client */
1101 SSL_set1_chain_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
1102
1103 if (1 != SSL_build_cert_chain(ssl,
1104 SSL_BUILD_CHAIN_FLAG_NO_ROOT
1105 | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR
1106 | SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)) {
1107 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1108 "SSL: building cert chain for TLS server name %s: %s",
1109 hctx->r->uri.authority.ptr,
1110 ERR_error_string(ERR_get_error(), NULL));
1111 return 0;
1112 }
1113 else { /* copy chain for future reuse */
1114 STACK_OF(X509) *chain = NULL;
1115 SSL_get0_chain_certs(ssl, &chain);
1116 pc->ssl_pemfile_chain = X509_chain_up_ref(chain);
1117 SSL_set1_chain_cert_store(ssl, NULL);
1118 }
1119 }
1120 #endif
1121 #endif
1122
1123 if (1 != SSL_use_PrivateKey(ssl, pc->ssl_pemfile_pkey)) {
1124 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1125 "SSL: failed to set private key for TLS server name %s: %s",
1126 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1127 return 0;
1128 }
1129
1130 #ifndef OPENSSL_NO_OCSP
1131 #ifdef BORINGSSL_API_VERSION
1132 /* BoringSSL suggests API different than SSL_CTX_set_tlsext_status_cb() */
1133 buffer *ocsp_resp = pc->ssl_stapling;
1134 if (NULL != ocsp_resp
1135 && !SSL_set_ocsp_response(ssl, (uint8_t *)BUF_PTR_LEN(ocsp_resp))) {
1136 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1137 "SSL: failed to set OCSP response for TLS server name %s: %s",
1138 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1139 return 0;
1140 }
1141 #endif
1142 #endif
1143
1144 if (hctx->conf.ssl_verifyclient) {
1145 if (NULL == hctx->conf.ssl_ca_file) {
1146 log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1147 "SSL: can't verify client without ssl.verifyclient.ca-file "
1148 "for TLS server name %s", hctx->r->uri.authority.ptr);
1149 return 0;
1150 }
1151 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
1152 && !defined(LIBRESSL_VERSION_NUMBER)
1153 SSL_set1_verify_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
1154 #endif
1155 /* WTH openssl? SSL_set_client_CA_list() calls set0_CA_list(),
1156 * but there is no set1_CA_list() to simply up the reference count
1157 * (without needing to duplicate the list) */
1158 /* WolfSSL does not support setting per-session CA list;
1159 * limitation is to per-CTX CA list, and is not changed after SNI */
1160 STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file
1161 ? hctx->conf.ssl_ca_dn_file
1162 : hctx->conf.ssl_ca_file->names;
1163 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(cert_names));
1164 int mode = SSL_VERIFY_PEER;
1165 if (hctx->conf.ssl_verifyclient_enforce)
1166 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1167 SSL_set_verify(ssl, mode, verify_callback);
1168 SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
1169 }
1170 else {
1171 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1172 }
1173
1174 return 1;
1175 }
1176
1177 #ifndef OPENSSL_NO_TLSEXT
1178 static int
mod_openssl_SNI(handler_ctx * hctx,const char * servername,size_t len)1179 mod_openssl_SNI (handler_ctx *hctx, const char *servername, size_t len)
1180 {
1181 request_st * const r = hctx->r;
1182 if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
1183 log_error(r->conf.errh, __FILE__, __LINE__,
1184 "SSL: SNI name too long %.*s", (int)len, servername);
1185 return SSL_TLSEXT_ERR_ALERT_FATAL;
1186 }
1187
1188 /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
1189 buffer_copy_string_len_lc(&r->uri.authority, servername, len);
1190 #if 0
1191 /*(r->uri.authority used below for configuration before request read;
1192 * revisit for h2)*/
1193 if (0 != http_request_host_policy(&r->uri.authority,
1194 r->conf.http_parseopts, 443))
1195 return SSL_TLSEXT_ERR_ALERT_FATAL;
1196 #endif
1197
1198 r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
1199 | (1 << COMP_HTTP_HOST);
1200 mod_openssl_patch_config(r, &hctx->conf);
1201 /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
1202 /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
1203 /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
1204 /*buffer_clear(&r->uri.authority);*/
1205
1206 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1207 && !defined(LIBRESSL_VERSION_NUMBER)
1208 return SSL_TLSEXT_ERR_OK;
1209 #else
1210 return (mod_openssl_cert_cb(hctx->ssl, NULL) == 1)
1211 ? SSL_TLSEXT_ERR_OK
1212 : SSL_TLSEXT_ERR_ALERT_FATAL;
1213 #endif
1214 }
1215
1216 #ifdef SSL_CLIENT_HELLO_SUCCESS
1217 static int
mod_openssl_client_hello_cb(SSL * ssl,int * al,void * srv)1218 mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv)
1219 {
1220 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1221 buffer_copy_string_len(&hctx->r->uri.scheme, CONST_STR_LEN("https"));
1222 UNUSED(srv);
1223
1224 const unsigned char *name;
1225 size_t len, slen;
1226 if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) {
1227 return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */
1228 }
1229
1230 /* expecting single element in the server_name extension; parse first one */
1231 if (len > 5
1232 && (size_t)((name[0] << 8) + name[1]) == len-2
1233 && name[2] == TLSEXT_TYPE_server_name
1234 && (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/
1235 int read_ahead = hctx->conf.ssl_read_ahead;
1236 int rc = mod_openssl_SNI(hctx, (const char *)name+5, slen);
1237 if (!read_ahead && hctx->conf.ssl_read_ahead)
1238 SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
1239 if (rc == SSL_TLSEXT_ERR_OK)
1240 return SSL_CLIENT_HELLO_SUCCESS;
1241 }
1242
1243 *al = TLS1_AD_UNRECOGNIZED_NAME;
1244 return SSL_CLIENT_HELLO_ERROR;
1245 }
1246 #else
1247 static int
network_ssl_servername_callback(SSL * ssl,int * al,void * srv)1248 network_ssl_servername_callback (SSL *ssl, int *al, void *srv)
1249 {
1250 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1251 buffer_copy_string_len(&hctx->r->uri.scheme, CONST_STR_LEN("https"));
1252 UNUSED(al);
1253 UNUSED(srv);
1254
1255 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1256 if (NULL == servername)
1257 return SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */
1258 size_t len = strlen(servername);
1259 int read_ahead = hctx->conf.ssl_read_ahead;
1260 int rc = mod_openssl_SNI(hctx, servername, len);
1261 if (!read_ahead && hctx->conf.ssl_read_ahead)
1262 SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
1263 return rc;
1264 }
1265 #endif
1266 #endif
1267
1268
1269 #if OPENSSL_VERSION_NUMBER < 0x10101000L \
1270 || defined(BORINGSSL_API_VERSION) \
1271 ||(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3060000fL)
1272 static unix_time64_t
1273 mod_openssl_asn1_time_to_posix (const ASN1_TIME *asn1time);
1274 #endif
1275
1276 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1277 && !defined(BORINGSSL_API_VERSION) \
1278 && !defined(LIBRESSL_VERSION_NUMBER)
1279 #define X509_get0_notBefore X509_get_notBefore
1280 #define X509_get0_notAfter X509_get_notAfter
1281 #endif
1282
1283 static int
mod_openssl_cert_is_active(const X509 * crt)1284 mod_openssl_cert_is_active (const X509 *crt)
1285 {
1286 const ASN1_TIME *notBefore = X509_get0_notBefore(crt);
1287 const ASN1_TIME *notAfter = X509_get0_notAfter(crt);
1288 #if OPENSSL_VERSION_NUMBER < 0x10101000L \
1289 || defined(BORINGSSL_API_VERSION) \
1290 ||(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3060000fL)
1291 const unix_time64_t before = mod_openssl_asn1_time_to_posix(notBefore);
1292 const unix_time64_t after = mod_openssl_asn1_time_to_posix(notAfter);
1293 const unix_time64_t now = log_epoch_secs;
1294 return (before <= now && now <= after);
1295 #else /*(-2 is an error from ASN1_TIME_cmp_time_t(); test cmp for -1, 0, 1)*/
1296 const unix_time64_t now = log_epoch_secs;
1297 const int before_cmp = ASN1_TIME_cmp_time_t(notBefore, (time_t)now);
1298 const int after_cmp = ASN1_TIME_cmp_time_t(notAfter, (time_t)now);
1299 return ((before_cmp == -1 || before_cmp == 0) && 0 <= after_cmp);
1300 #endif
1301 }
1302
1303
1304 static X509 *
mod_openssl_load_pem_file(const char * file,log_error_st * errh,STACK_OF (X509)** chain)1305 mod_openssl_load_pem_file (const char *file, log_error_st *errh, STACK_OF(X509) **chain)
1306 {
1307 *chain = NULL;
1308
1309 off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
1310 char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1311 if (NULL == data) return NULL;
1312
1313 BIO *in = BIO_new_mem_buf(data, (int)dlen);
1314 if (NULL == in) {
1315 log_error(errh, __FILE__, __LINE__,
1316 "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1317 if (dlen) ck_memzero(data, dlen);
1318 free(data);
1319 return NULL;
1320 }
1321
1322 int is_pem = (NULL != strstr(data, "-----"));
1323 X509 *x = is_pem
1324 ? PEM_read_bio_X509_AUX_secmem(in, NULL, NULL, NULL)
1325 : d2i_X509_bio(in, NULL);
1326 if (NULL == x) {
1327 log_error(errh, __FILE__, __LINE__,
1328 "SSL: couldn't read X509 certificate from '%s'", file);
1329 }
1330 else if (is_pem && !mod_openssl_load_X509_sk(file, errh, chain, in)) {
1331 X509_free(x);
1332 x = NULL;
1333 }
1334 else if (!mod_openssl_cert_is_active(x)) {
1335 log_error(errh, __FILE__, __LINE__,
1336 "SSL: inactive/expired X509 certificate '%s'", file);
1337 }
1338
1339 BIO_free(in);
1340 if (dlen) ck_memzero(data, dlen);
1341 free(data);
1342 return x;
1343 }
1344
1345
1346 static EVP_PKEY *
mod_openssl_evp_pkey_load_pem_file(const char * file,log_error_st * errh)1347 mod_openssl_evp_pkey_load_pem_file (const char *file, log_error_st *errh)
1348 {
1349 off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
1350 char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1351 if (NULL == data) return NULL;
1352 EVP_PKEY *x = NULL;
1353 BIO *in = BIO_new_mem_buf(data, (int)dlen);
1354 if (NULL != in) {
1355 x = (NULL != strstr(data, "-----"))
1356 ? PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)
1357 : d2i_PrivateKey_bio(in, NULL);
1358 BIO_free(in);
1359 }
1360 if (dlen) ck_memzero(data, dlen);
1361 free(data);
1362
1363 if (NULL == in)
1364 log_error(errh, __FILE__, __LINE__,
1365 "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1366 else if (NULL == x)
1367 log_error(errh, __FILE__, __LINE__,
1368 "SSL: couldn't read private key from '%s'", file);
1369
1370 return x;
1371 }
1372
1373
1374 #ifndef OPENSSL_NO_OCSP
1375
1376 static buffer *
mod_openssl_load_stapling_file(const char * file,log_error_st * errh,buffer * b)1377 mod_openssl_load_stapling_file (const char *file, log_error_st *errh, buffer *b)
1378 {
1379 /* load stapling .der into buffer *b only if successful
1380 *
1381 * Note: for some TLS libs, the OCSP stapling response is not copied when
1382 * assigned to a session (and is reasonable since not changed frequently)
1383 * - BoringSSL SSL_set_ocsp_response()
1384 * - WolfSSL SSL_set_tlsext_status_ocsp_resp() (differs from OpenSSL API)
1385 * Therefore, there is a potential race condition if the OCSP response is
1386 * assigned to the session during the handshake and the Server Hello is
1387 * partially sent, AND (unlikely, if possible at all), the TLS library is
1388 * in the middle of reading this OSCP response buffer. If the OCSP response
1389 * is replaced due to an updated ssl.stapling-file (checked periodically),
1390 * AND the buffer is resized, this would be a problem. Resizing the buffer
1391 * is unlikely since updated OSCP response for same certificate are
1392 * typically the same size with the signature and dates refreshed.
1393 */
1394
1395 /* load raw .der file */
1396 off_t dlen = 1*1024*1024;/*(arbitrary limit: 1 MB file; expect < 1 KB)*/
1397 char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1398 if (NULL == data) return NULL;
1399
1400 #if defined(BORINGSSL_API_VERSION)
1401
1402 if (NULL == b)
1403 b = buffer_init();
1404 else if (b->ptr)
1405 free(b->ptr);
1406 b->ptr = data;
1407 b->used = (uint32_t)dlen;
1408 b->size = (uint32_t)dlen+1;
1409 return b;
1410
1411 #else
1412
1413 BIO *in = BIO_new_mem_buf(data, (int)dlen);
1414 if (NULL == in) {
1415 log_error(errh, __FILE__, __LINE__,
1416 "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1417 free(data);
1418 return NULL;
1419 }
1420
1421 OCSP_RESPONSE *x = d2i_OCSP_RESPONSE_bio(in, NULL);
1422 BIO_free(in);
1423 free(data);
1424 if (NULL == x) {
1425 log_error(errh, __FILE__, __LINE__,
1426 "SSL: OCSP stapling file read error: %s %s",
1427 ERR_error_string(ERR_get_error(), NULL), file);
1428 return NULL;
1429 }
1430
1431 unsigned char *rspder = NULL;
1432 int rspderlen = i2d_OCSP_RESPONSE(x, &rspder);
1433
1434 if (rspderlen > 0) {
1435 if (NULL == b) b = buffer_init();
1436 buffer_copy_string_len(b, (char *)rspder, (uint32_t)rspderlen);
1437 }
1438
1439 OPENSSL_free(rspder);
1440 OCSP_RESPONSE_free(x);
1441 return rspderlen ? b : NULL;
1442
1443 #endif
1444 }
1445
1446
1447 static unix_time64_t
mod_openssl_asn1_time_to_posix(const ASN1_TIME * asn1time)1448 mod_openssl_asn1_time_to_posix (const ASN1_TIME *asn1time)
1449 {
1450 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3050000fL
1451 /* LibreSSL was forked from OpenSSL 1.0.1; does not have ASN1_TIME_diff */
1452
1453 /*(Note: all certificate times are expected to use UTC)*/
1454 /*(Note: does not strictly validate string contains appropriate digits)*/
1455 /*(Note: incorrectly assumes GMT if 'Z' or offset not provided)*/
1456 /*(Note: incorrectly ignores if local timezone might be in DST)*/
1457
1458 if (NULL == asn1time || NULL == asn1time->data) return -1;
1459 const char *s = (const char *)asn1time->data;
1460 size_t len = strlen(s);
1461 struct tm x;
1462 x.tm_isdst = 0;
1463 x.tm_yday = 0;
1464 x.tm_wday = 0;
1465 switch (asn1time->type) {
1466 case V_ASN1_UTCTIME: /* 2-digit year */
1467 if (len < 8) return -1;
1468 len -= 8;
1469 x.tm_year = (s[0]-'0')*10 + (s[1]-'0');
1470 x.tm_year += (x.tm_year < 50 ? 2000 : 1900);
1471 s += 2;
1472 break;
1473 case V_ASN1_GENERALIZEDTIME: /* 4-digit year */
1474 if (len < 10) return -1;
1475 len -= 10;
1476 x.tm_year = (s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+(s[3]-'0');
1477 s += 4;
1478 break;
1479 default:
1480 return -1;
1481 }
1482 x.tm_mon = (s[0]-'0')*10 + (s[1]-'0');
1483 x.tm_mday = (s[2]-'0')*10 + (s[3]-'0');
1484 x.tm_hour = (s[4]-'0')*10 + (s[5]-'0');
1485 x.tm_min = 0;
1486 x.tm_sec = 0;
1487 s += 6;
1488 if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') {
1489 len -= 2;
1490 x.tm_min = (s[0]-'0')*10 + (s[1]-'0');
1491 s += 2;
1492 if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') {
1493 len -= 2;
1494 x.tm_sec = (s[0]-'0')*10 + (s[1]-'0');
1495 s += 2;
1496 if (len && s[0] == '.') {
1497 /*(ignore .fff fractional seconds;
1498 * should be up to 3 digits but we ignore more)*/
1499 do { ++s; --len; } while (*s >= '0' && *s <= '9');
1500 }
1501 }
1502 }
1503 int offset = 0;
1504 if ((*s == '-' || *s == '+') && len != 5) {
1505 offset = ((s[1]-'0')*10 + (s[2]-'0')) * 3600
1506 + ((s[3]-'0')*10 + (s[4]-'0')) * 60;
1507 if (*s == '-') offset = -offset;
1508 }
1509 else if (s[0] != '\0' && (s[0] != 'Z' || s[1] != '\0'))
1510 return -1;
1511
1512 if (x.tm_year == 9999 && x.tm_mon == 12 && x.tm_mday == 31
1513 && x.tm_hour == 23 && x.tm_min == 59 && x.tm_sec == 59 && s[0] == 'Z')
1514 return -1; // 99991231235959Z RFC 5280
1515
1516 x.tm_year-= 1900;
1517 x.tm_mon -= 1;
1518 time_t t = timegm(&x);
1519 return (t != -1) ? TIME64_CAST(t) + offset : t;
1520
1521 #else
1522
1523 /* Note: this does not check for integer overflow of time_t! */
1524 int day, sec;
1525 return ASN1_TIME_diff(&day, &sec, NULL, asn1time)
1526 ? log_epoch_secs + day*86400 + sec
1527 : -1;
1528
1529 #endif
1530 }
1531
1532
1533 static unix_time64_t
mod_openssl_ocsp_next_update(plugin_cert * pc)1534 mod_openssl_ocsp_next_update (plugin_cert *pc)
1535 {
1536 #if defined(BORINGSSL_API_VERSION)
1537 UNUSED(pc);
1538 return -1; /*(not implemented)*/
1539 #else
1540 buffer *der = pc->ssl_stapling;
1541 const unsigned char *p = (unsigned char *)der->ptr; /*(p gets modified)*/
1542 OCSP_RESPONSE *ocsp = d2i_OCSP_RESPONSE(NULL, &p, buffer_clen(der));
1543 if (NULL == ocsp) return -1;
1544 OCSP_BASICRESP *bs = OCSP_response_get1_basic(ocsp);
1545 if (NULL == bs) {
1546 OCSP_RESPONSE_free(ocsp);
1547 return -1;
1548 }
1549
1550 /* XXX: should save and evaluate cert status returned by these calls */
1551 ASN1_TIME *nextupd = NULL;
1552 OCSP_single_get0_status(OCSP_resp_get0(bs, 0), NULL, NULL, NULL, &nextupd);
1553 unix_time64_t t = nextupd ? mod_openssl_asn1_time_to_posix(nextupd) : -1;
1554
1555 /* Note: trust external process which creates ssl.stapling-file to verify
1556 * (as well as to validate certificate status)
1557 * future: verify OCSP response here to double-check */
1558
1559 OCSP_BASICRESP_free(bs);
1560 OCSP_RESPONSE_free(ocsp);
1561
1562 return t;
1563 #endif
1564 }
1565
1566
1567 __attribute_cold__
1568 static void
mod_openssl_expire_stapling_file(server * srv,plugin_cert * pc)1569 mod_openssl_expire_stapling_file (server *srv, plugin_cert *pc)
1570 {
1571 if (NULL == pc->ssl_stapling) /*(previously discarded or never loaded)*/
1572 return;
1573
1574 /* discard expired OCSP stapling response */
1575 buffer_free(pc->ssl_stapling);
1576 pc->ssl_stapling = NULL;
1577 if (pc->must_staple)
1578 log_error(srv->errh, __FILE__, __LINE__,
1579 "certificate marked OCSP Must-Staple, "
1580 "but OCSP response expired from ssl.stapling-file %s",
1581 pc->ssl_stapling_file->ptr);
1582 }
1583
1584
1585 static int
mod_openssl_reload_stapling_file(server * srv,plugin_cert * pc,const unix_time64_t cur_ts)1586 mod_openssl_reload_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts)
1587 {
1588 buffer *b = mod_openssl_load_stapling_file(pc->ssl_stapling_file->ptr,
1589 srv->errh, pc->ssl_stapling);
1590 if (!b) return 0;
1591
1592 pc->ssl_stapling = b; /*(unchanged unless orig was NULL)*/
1593 pc->ssl_stapling_loadts = cur_ts;
1594 pc->ssl_stapling_nextts = mod_openssl_ocsp_next_update(pc);
1595 if (pc->ssl_stapling_nextts == -1) {
1596 /* "Next Update" might not be provided by OCSP responder
1597 * Use 3600 sec (1 hour) in that case. */
1598 /* retry in 1 hour if unable to determine Next Update */
1599 pc->ssl_stapling_nextts = cur_ts + 3600;
1600 pc->ssl_stapling_loadts = 0;
1601 }
1602 else if (pc->ssl_stapling_nextts < cur_ts) {
1603 mod_openssl_expire_stapling_file(srv, pc);
1604 return 0;
1605 }
1606
1607 return 1;
1608 }
1609
1610
1611 static int
mod_openssl_refresh_stapling_file(server * srv,plugin_cert * pc,const unix_time64_t cur_ts)1612 mod_openssl_refresh_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts)
1613 {
1614 if (pc->ssl_stapling && pc->ssl_stapling_nextts > cur_ts + 256)
1615 return 1; /* skip check for refresh unless close to expire */
1616 struct stat st;
1617 if (0 != stat(pc->ssl_stapling_file->ptr, &st)
1618 || TIME64_CAST(st.st_mtime) <= pc->ssl_stapling_loadts) {
1619 if (pc->ssl_stapling && pc->ssl_stapling_nextts < cur_ts)
1620 mod_openssl_expire_stapling_file(srv, pc);
1621 return 1;
1622 }
1623 return mod_openssl_reload_stapling_file(srv, pc, cur_ts);
1624 }
1625
1626
1627 static void
mod_openssl_refresh_stapling_files(server * srv,const plugin_data * p,const unix_time64_t cur_ts)1628 mod_openssl_refresh_stapling_files (server *srv, const plugin_data *p, const unix_time64_t cur_ts)
1629 {
1630 /* future: might construct array of (plugin_cert *) at startup
1631 * to avoid the need to search for them here */
1632 /* (init i to 0 if global context; to 1 to skip empty global context) */
1633 if (NULL == p->cvlist) return;
1634 for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
1635 const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1636 for (; cpv->k_id != -1; ++cpv) {
1637 if (cpv->k_id != 0) continue; /* k_id == 0 for ssl.pemfile */
1638 if (cpv->vtype != T_CONFIG_LOCAL) continue;
1639 plugin_cert *pc = cpv->v.v;
1640 if (pc->ssl_stapling_file)
1641 mod_openssl_refresh_stapling_file(srv, pc, cur_ts);
1642 }
1643 }
1644 }
1645
1646
1647 static int
mod_openssl_crt_must_staple(const X509 * crt)1648 mod_openssl_crt_must_staple (const X509 *crt)
1649 {
1650 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1651 || defined(BORINGSSL_API_VERSION) \
1652 || defined(LIBRESSL_VERSION_NUMBER)
1653 /*(not currently supported in BoringSSL or LibreSSL)*/
1654 UNUSED(crt);
1655 return 0;
1656 #else
1657 /* openssl/x509v3.h:typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE; */
1658
1659 TLS_FEATURE *tlsf = X509_get_ext_d2i(crt, NID_tlsfeature, NULL, NULL);
1660 if (NULL == tlsf) return 0;
1661
1662 int rc = 0;
1663
1664 for (int i = 0; i < sk_ASN1_INTEGER_num(tlsf); ++i) {
1665 ASN1_INTEGER *ai = sk_ASN1_INTEGER_value(tlsf, i);
1666 long tlsextid = ASN1_INTEGER_get(ai);
1667 if (tlsextid == 5) { /* 5 = OCSP Must-Staple */
1668 rc = 1;
1669 break;
1670 }
1671 }
1672
1673 sk_ASN1_INTEGER_pop_free(tlsf, ASN1_INTEGER_free);
1674 return rc; /* 1 if OCSP Must-Staple found; 0 if not */
1675 #endif
1676 }
1677
1678 #endif /* OPENSSL_NO_OCSP */
1679
1680
1681 static plugin_cert *
network_openssl_load_pemfile(server * srv,const buffer * pemfile,const buffer * privkey,const buffer * ssl_stapling_file)1682 network_openssl_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey, const buffer *ssl_stapling_file)
1683 {
1684 if (!mod_openssl_init_once_openssl(srv)) return NULL;
1685
1686 STACK_OF(X509) *ssl_pemfile_chain = NULL;
1687 X509 *ssl_pemfile_x509 =
1688 mod_openssl_load_pem_file(pemfile->ptr, srv->errh, &ssl_pemfile_chain);
1689 if (NULL == ssl_pemfile_x509)
1690 return NULL;
1691
1692 EVP_PKEY *ssl_pemfile_pkey =
1693 mod_openssl_evp_pkey_load_pem_file(privkey->ptr, srv->errh);
1694 if (NULL == ssl_pemfile_pkey) {
1695 X509_free(ssl_pemfile_x509);
1696 sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1697 return NULL;
1698 }
1699
1700 if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1701 log_error(srv->errh, __FILE__, __LINE__, "SSL:"
1702 "Private key does not match the certificate public key, "
1703 "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
1704 pemfile->ptr, privkey->ptr);
1705 EVP_PKEY_free(ssl_pemfile_pkey);
1706 X509_free(ssl_pemfile_x509);
1707 sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1708 return NULL;
1709 }
1710
1711 plugin_cert *pc = ck_malloc(sizeof(plugin_cert));
1712 pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
1713 pc->ssl_pemfile_x509 = ssl_pemfile_x509;
1714 pc->ssl_pemfile_chain= ssl_pemfile_chain;
1715 pc->ssl_pemfile = pemfile;
1716 pc->ssl_privkey = privkey;
1717 pc->ssl_stapling = NULL;
1718 pc->ssl_stapling_file= ssl_stapling_file;
1719 pc->ssl_stapling_loadts = 0;
1720 pc->ssl_stapling_nextts = 0;
1721 #ifndef OPENSSL_NO_OCSP
1722 pc->must_staple = mod_openssl_crt_must_staple(ssl_pemfile_x509);
1723 #else
1724 pc->must_staple = 0;
1725 #endif
1726 pc->self_issued =
1727 (0 == X509_NAME_cmp(X509_get_subject_name(ssl_pemfile_x509),
1728 X509_get_issuer_name(ssl_pemfile_x509)));
1729
1730 if (pc->ssl_stapling_file) {
1731 #ifndef OPENSSL_NO_OCSP
1732 if (!mod_openssl_reload_stapling_file(srv, pc, log_epoch_secs)) {
1733 /* continue without OCSP response if there is an error */
1734 }
1735 #else
1736 log_error(srv->errh, __FILE__, __LINE__, "SSL:"
1737 "OCSP stapling not supported; ignoring %s",
1738 pc->ssl_stapling_file->ptr);
1739 #endif
1740 }
1741 else if (pc->must_staple) {
1742 log_error(srv->errh, __FILE__, __LINE__,
1743 "certificate %s marked OCSP Must-Staple, "
1744 "but ssl.stapling-file not provided", pemfile->ptr);
1745 }
1746
1747 #if 0
1748 const ASN1_TIME *notAfter = X509_get0_notAfter(ssl_pemfile_x509);
1749 pc->notAfter = mod_openssl_asn1_time_to_posix(notAfter);
1750 #endif
1751
1752 return pc;
1753 }
1754
1755
1756 #ifndef OPENSSL_NO_TLSEXT
1757
1758 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1759
1760 static int
mod_openssl_acme_tls_1(SSL * ssl,handler_ctx * hctx)1761 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
1762 {
1763 buffer * const b = hctx->tmp_buf;
1764 const buffer * const name = &hctx->r->uri.authority;
1765 log_error_st * const errh = hctx->r->conf.errh;
1766 X509 *ssl_pemfile_x509 = NULL;
1767 STACK_OF(X509) *ssl_pemfile_chain = NULL;
1768 EVP_PKEY *ssl_pemfile_pkey = NULL;
1769 size_t len;
1770 int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
1771
1772 /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
1773 if (!hctx->conf.ssl_acme_tls_1)
1774 return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
1775
1776 /* check if SNI set server name (required for acme-tls/1 protocol)
1777 * and perform simple path checks for no '/'
1778 * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
1779 if (buffer_is_blank(name)) return rc;
1780 if (NULL != strchr(name->ptr, '/')) return rc;
1781 if (name->ptr[0] == '.') return rc;
1782 #if 0
1783 if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443))
1784 return rc;
1785 #endif
1786 buffer_copy_path_len2(b, BUF_PTR_LEN(hctx->conf.ssl_acme_tls_1),
1787 BUF_PTR_LEN(name));
1788 len = buffer_clen(b);
1789
1790 do {
1791 buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
1792 ssl_pemfile_x509 =
1793 mod_openssl_load_pem_file(b->ptr, errh, &ssl_pemfile_chain);
1794 if (NULL == ssl_pemfile_x509) {
1795 log_error(errh, __FILE__, __LINE__,
1796 "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1797 break;
1798 }
1799
1800 buffer_truncate(b, len); /*(remove ".crt.pem")*/
1801 buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
1802 ssl_pemfile_pkey = mod_openssl_evp_pkey_load_pem_file(b->ptr, errh);
1803 if (NULL == ssl_pemfile_pkey) {
1804 log_error(errh, __FILE__, __LINE__,
1805 "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1806 break;
1807 }
1808
1809 #if 0 /* redundant with below? */
1810 if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1811 log_error(errh, __FILE__, __LINE__,
1812 "SSL: Private key does not match acme-tls/1 "
1813 "certificate public key, reason: %s %s"
1814 ERR_error_string(ERR_get_error(), NULL), b->ptr);
1815 break;
1816 }
1817 #endif
1818
1819 /* first set certificate!
1820 * setting private key checks whether certificate matches it */
1821 if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
1822 log_error(errh, __FILE__, __LINE__,
1823 "SSL: failed to set acme-tls/1 certificate for TLS server "
1824 "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1825 break;
1826 }
1827
1828 if (ssl_pemfile_chain) {
1829 SSL_set0_chain(ssl, ssl_pemfile_chain);
1830 ssl_pemfile_chain = NULL;
1831 }
1832
1833 if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
1834 log_error(errh, __FILE__, __LINE__,
1835 "SSL: failed to set acme-tls/1 private key for TLS server "
1836 "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1837 break;
1838 }
1839
1840 hctx->conf.ssl_verifyclient_enforce = 0;
1841 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1842 rc = SSL_TLSEXT_ERR_OK;
1843 } while (0);
1844
1845 if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
1846 if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
1847 if (ssl_pemfile_chain)
1848 sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1849
1850 return rc;
1851 }
1852
1853 static int
mod_openssl_alpn_h2_policy(handler_ctx * const hctx)1854 mod_openssl_alpn_h2_policy (handler_ctx * const hctx)
1855 {
1856 /*(currently called after handshake has completed)*/
1857 #if 0 /* SNI omitted by client when connecting to IP instead of to name */
1858 if (buffer_is_blank(&hctx->r->uri.authority)) {
1859 log_error(hctx->errh, __FILE__, __LINE__,
1860 "SSL: error ALPN h2 without SNI");
1861 return -1;
1862 }
1863 #endif
1864 if (SSL_version(hctx->ssl) < TLS1_2_VERSION) {
1865 log_error(hctx->errh, __FILE__, __LINE__,
1866 "SSL: error ALPN h2 requires TLSv1.2 or later");
1867 return -1;
1868 }
1869
1870 return 0;
1871 }
1872
1873 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
1874 static int
mod_openssl_alpn_select_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1875 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
1876 {
1877 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1878 unsigned short proto;
1879 UNUSED(arg);
1880
1881 for (unsigned int i = 0, n; i < inlen; i += n) {
1882 n = in[i++];
1883 if (i+n > inlen || 0 == n) break;
1884 switch (n) {
1885 case 2: /* "h2" */
1886 if (in[i] == 'h' && in[i+1] == '2') {
1887 if (!hctx->r->conf.h2proto) continue;
1888 proto = MOD_OPENSSL_ALPN_H2;
1889 if (hctx->r->handler_module == NULL)/*(e.g. not mod_sockproxy)*/
1890 hctx->r->http_version = HTTP_VERSION_2;
1891 break;
1892 }
1893 continue;
1894 case 8: /* "http/1.1" "http/1.0" */
1895 if (0 == memcmp(in+i, "http/1.", 7)) {
1896 if (in[i+7] == '1') {
1897 proto = MOD_OPENSSL_ALPN_HTTP11;
1898 break;
1899 }
1900 if (in[i+7] == '0') {
1901 proto = MOD_OPENSSL_ALPN_HTTP10;
1902 break;
1903 }
1904 }
1905 continue;
1906 case 10: /* "acme-tls/1" */
1907 if (0 == memcmp(in+i, "acme-tls/1", 10)) {
1908 int rc = mod_openssl_acme_tls_1(ssl, hctx);
1909 if (rc == SSL_TLSEXT_ERR_OK) {
1910 proto = MOD_OPENSSL_ALPN_ACME_TLS_1;
1911 break;
1912 }
1913 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */
1914 if (rc == SSL_TLSEXT_ERR_NOACK) continue;
1915 return rc;
1916 }
1917 continue;
1918 default:
1919 continue;
1920 }
1921
1922 hctx->alpn = proto;
1923 *out = in+i;
1924 *outlen = n;
1925 return SSL_TLSEXT_ERR_OK;
1926 }
1927
1928 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1929 return SSL_TLSEXT_ERR_NOACK;
1930 #else
1931 return hctx->r->handler_module /*(e.g. mod_sockproxy)*/
1932 ? SSL_TLSEXT_ERR_NOACK
1933 : SSL_TLSEXT_ERR_ALERT_FATAL;
1934 #endif
1935 }
1936
1937 #endif /* TLSEXT_TYPE_application_layer_protocol_negotiation */
1938
1939 #endif /* OPENSSL_NO_TLSEXT */
1940
1941
1942 #if defined(BORINGSSL_API_VERSION) \
1943 || defined(LIBRESSL_VERSION_NUMBER)
1944 static int
1945 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s);
1946 #endif
1947
1948
1949 static int
network_openssl_ssl_conf_cmd(server * srv,plugin_config_socket * s)1950 network_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s)
1951 {
1952 #ifdef SSL_CONF_FLAG_CMDLINE
1953
1954 int rc = 0;
1955 const data_string *ds;
1956 SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new();
1957 SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx);
1958 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE
1959 | SSL_CONF_FLAG_SERVER
1960 | SSL_CONF_FLAG_SHOW_ERRORS
1961 | SSL_CONF_FLAG_CERTIFICATE);
1962
1963 /* always disable null and export ciphers */
1964 ds = (const data_string *)
1965 array_get_element_klen(s->ssl_conf_cmd,
1966 CONST_STR_LEN("CipherString"));
1967 if (NULL != ds) {
1968 buffer *cipher_string =
1969 array_get_buf_ptr(s->ssl_conf_cmd, CONST_STR_LEN("CipherString"));
1970 if (buffer_is_blank(cipher_string))
1971 buffer_append_string_len(cipher_string, CONST_STR_LEN("HIGH"));
1972 buffer_append_string_len(cipher_string,
1973 CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
1974 }
1975
1976 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
1977 ds = (data_string *)s->ssl_conf_cmd->data[i];
1978 /* ("SecurityLevel" is lighttpd extension to SSL_CONF_cmd() syntax)
1979 * SSL_CTX_set_security_level() is specific to OpenSSL >= 1.1.0 */
1980 if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("SecurityLevel"))) {
1981 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1982 int level = atoi(ds->value.ptr);
1983 if (level >= 0) SSL_CTX_set_security_level(s->ssl_ctx, level);
1984 #endif
1985 continue;
1986 }
1987 ERR_clear_error();
1988 if (SSL_CONF_cmd(cctx, ds->key.ptr, ds->value.ptr) <= 0) {
1989 log_error(srv->errh, __FILE__, __LINE__,
1990 "SSL: SSL_CONF_cmd %s %s: %s", ds->key.ptr, ds->value.ptr,
1991 ERR_error_string(ERR_get_error(), NULL));
1992 rc = -1;
1993 break;
1994 }
1995 }
1996
1997 if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) {
1998 log_error(srv->errh, __FILE__, __LINE__,
1999 "SSL: SSL_CONF_CTX_finish(): %s",
2000 ERR_error_string(ERR_get_error(), NULL));
2001 rc = -1;
2002 }
2003
2004 SSL_CONF_CTX_free(cctx);
2005 return rc;
2006
2007 #elif defined(BORINGSSL_API_VERSION) \
2008 || defined(LIBRESSL_VERSION_NUMBER)
2009
2010 return mod_openssl_ssl_conf_cmd(srv, s);
2011
2012 #else
2013
2014 UNUSED(s);
2015 log_error(srv->errh, __FILE__, __LINE__,
2016 "SSL: ssl.openssl.ssl-conf-cmd not available; ignored");
2017 return 0;
2018
2019 #endif
2020 }
2021
2022
2023 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2024 #ifndef OPENSSL_NO_DH
2025 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
2026 || (defined(LIBRESSL_VERSION_NUMBER) \
2027 && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
2028 #define DH_set0_pqg(dh, dh_p, NULL, dh_g) \
2029 ((dh)->p = (dh_p), (dh)->g = (dh_g), (dh_p) != NULL && (dh_g) != NULL)
2030 #endif
2031 /* https://tools.ietf.org/html/rfc7919#appendix-A.1
2032 * A.1. ffdhe2048
2033 *
2034 * https://ssl-config.mozilla.org/ffdhe2048.txt
2035 * C code generated with: openssl dhparam -C -in ffdhe2048.txt
2036 */
get_dh2048(void)2037 static DH *get_dh2048(void)
2038 {
2039 static unsigned char dhp_2048[] = {
2040 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8,
2041 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, 0xAF, 0xDC, 0x56, 0x20,
2042 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D,
2043 0x36, 0x95, 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
2044 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, 0x7D, 0x2F,
2045 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02,
2046 0xAE, 0xC4, 0x61, 0x7A, 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD,
2047 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
2048 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57,
2049 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, 0x98, 0x4F, 0x0C, 0x70,
2050 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF,
2051 0xE8, 0x72, 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
2052 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, 0xBC, 0x0A,
2053 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B,
2054 0xB2, 0xC8, 0xE3, 0xFB, 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7,
2055 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
2056 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07,
2057 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, 0x9E, 0x02, 0xFC, 0xE1,
2058 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34,
2059 0x2F, 0x61, 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
2060 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, 0xC3, 0xFE,
2061 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC,
2062 0x2E, 0xC2, 0x20, 0x05, 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16,
2063 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
2064 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, 0xFF, 0xFF,
2065 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
2066 };
2067 static unsigned char dhg_2048[] = {
2068 0x02
2069 };
2070 DH *dh = DH_new();
2071 BIGNUM *p, *g;
2072
2073 if (dh == NULL)
2074 return NULL;
2075 p = BN_bin2bn(dhp_2048, sizeof(dhp_2048), NULL);
2076 g = BN_bin2bn(dhg_2048, sizeof(dhg_2048), NULL);
2077 if (p == NULL || g == NULL || !DH_set0_pqg(dh, p, NULL, g)) {
2078 DH_free(dh);
2079 BN_free(p);
2080 BN_free(g);
2081 return NULL;
2082 }
2083 return dh;
2084 }
2085 #endif /* !OPENSSL_NO_DH */
2086 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */
2087
2088
2089 static int
mod_openssl_ssl_conf_dhparameters(server * srv,plugin_config_socket * s,const buffer * dhparameters)2090 mod_openssl_ssl_conf_dhparameters(server *srv, plugin_config_socket *s, const buffer *dhparameters)
2091 {
2092 #ifndef OPENSSL_NO_DH
2093 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2094 DH *dh;
2095 /* Support for Diffie-Hellman key exchange */
2096 if (dhparameters) {
2097 /* DH parameters from file */
2098 BIO *bio;
2099 bio = BIO_new_file((char *) dhparameters->ptr, "r");
2100 if (bio == NULL) {
2101 log_error(srv->errh, __FILE__, __LINE__,
2102 "SSL: Unable to open file %s", dhparameters->ptr);
2103 return 0;
2104 }
2105 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2106 BIO_free(bio);
2107 if (dh == NULL) {
2108 log_error(srv->errh, __FILE__, __LINE__,
2109 "SSL: PEM_read_bio_DHparams failed %s", dhparameters->ptr);
2110 return 0;
2111 }
2112 SSL_CTX_set_tmp_dh(s->ssl_ctx, dh);
2113 DH_free(dh);
2114 }
2115 else {
2116 dh = get_dh2048();
2117 if (dh == NULL) {
2118 log_error(srv->errh, __FILE__, __LINE__,
2119 "SSL: get_dh2048() failed");
2120 return 0;
2121 }
2122 SSL_CTX_set_tmp_dh(s->ssl_ctx, dh);
2123 DH_free(dh);
2124 }
2125 #else
2126 /* OSSL_STORE_open() available in openssl 1.1.1, but might
2127 * not be present in alt TLS libs (libressl or boringssl) */
2128 EVP_PKEY *dhpkey = NULL;
2129 if (dhparameters) {
2130 OSSL_STORE_CTX *ctx = NULL;
2131 ctx = OSSL_STORE_open(dhparameters->ptr, NULL, NULL, NULL, NULL);
2132 if (NULL != ctx) {
2133 if (OSSL_STORE_expect(ctx, OSSL_STORE_INFO_PARAMS)) {
2134 while (!OSSL_STORE_eof(ctx)) {
2135 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
2136 if (info) {
2137 dhpkey = OSSL_STORE_INFO_get1_PARAMS(info);
2138 OSSL_STORE_INFO_free(info);
2139 }
2140 break;
2141 }
2142 }
2143 OSSL_STORE_close(ctx);
2144 }
2145 if (!dhpkey || !EVP_PKEY_is_a(dhpkey, "DH")
2146 || !SSL_CTX_set0_tmp_dh_pkey(s->ssl_ctx, dhpkey)) {
2147 log_error(srv->errh, __FILE__, __LINE__,
2148 "Unable to load DH params from %s", dhparameters->ptr);
2149 EVP_PKEY_free(dhpkey);
2150 dhpkey = NULL;
2151 } /*(else dhpkey ownership transferred upon success)*/
2152 }
2153 if (NULL == dhpkey)
2154 SSL_CTX_set_dh_auto(s->ssl_ctx, 1);
2155 #endif
2156 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_SINGLE_DH_USE);
2157 #else
2158 if (dhparameters) {
2159 log_error(srv->errh, __FILE__, __LINE__,
2160 "SSL: openssl compiled without DH support, "
2161 "can't load parameters from %s", dhparameters->ptr);
2162 }
2163 #endif
2164
2165 return 1;
2166 }
2167
2168
2169 #if defined(BORINGSSL_API_VERSION) \
2170 || defined(LIBRESSL_VERSION_NUMBER)
2171 static int
mod_openssl_ssl_conf_curves(server * srv,plugin_config_socket * s,const buffer * ssl_ec_curve)2172 mod_openssl_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *ssl_ec_curve)
2173 {
2174 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2175 #ifndef OPENSSL_NO_ECDH
2176 /* Support for Elliptic-Curve Diffie-Hellman key exchange */
2177 /* OpenSSL only supports the "named curves" from RFC 4492, section 5.1.1. */
2178 const char *curve = ssl_ec_curve ? ssl_ec_curve->ptr : "prime256v1";
2179 int nid = 0;
2180 if (ssl_ec_curve) {
2181 /* OpenSSL only supports the "named curves"
2182 * from RFC 4492, section 5.1.1. */
2183 nid = OBJ_sn2nid((char *) curve);
2184 if (nid == 0) {
2185 log_error(srv->errh, __FILE__, __LINE__,
2186 "SSL: Unknown curve name %s", curve);
2187 return 0;
2188 }
2189 }
2190 else {
2191 #if OPENSSL_VERSION_NUMBER < 0x10002000
2192 /* Default curve */
2193 nid = OBJ_sn2nid("prime256v1");
2194 #elif OPENSSL_VERSION_NUMBER < 0x10100000L \
2195 || defined(LIBRESSL_VERSION_NUMBER)
2196 if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) {
2197 log_error(srv->errh, __FILE__, __LINE__,
2198 "SSL: SSL_CTX_set_ecdh_auto() failed");
2199 }
2200 #endif
2201 }
2202 if (nid) {
2203 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2204 EC_KEY *ecdh;
2205 ecdh = EC_KEY_new_by_curve_name(nid);
2206 if (ecdh == NULL) {
2207 log_error(srv->errh, __FILE__, __LINE__,
2208 "SSL: Unable to create curve %s", curve);
2209 return 0;
2210 }
2211 SSL_CTX_set_tmp_ecdh(s->ssl_ctx, ecdh);
2212 EC_KEY_free(ecdh);
2213 #else
2214 /* SSL_CTX_set1_groups() available in openssl 1.1.1, but might
2215 * not be present in alt TLS libs (libressl or boringssl) */
2216 if (1 != SSL_CTX_set1_groups(s->ssl_ctx, &nid, 1)) {
2217 log_error(srv->errh, __FILE__, __LINE__,
2218 "SSL: Unable to config curve %s", curve);
2219 return 0;
2220 }
2221 #endif
2222 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
2223 }
2224 #endif
2225 #endif
2226 UNUSED(srv);
2227 UNUSED(s);
2228 UNUSED(ssl_ec_curve);
2229
2230 return 1;
2231 }
2232 #endif /* BORINGSSL_API_VERSION || LIBRESSL_VERSION_NUMBER */
2233
2234
2235 static int
network_init_ssl(server * srv,plugin_config_socket * s,plugin_data * p)2236 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p)
2237 {
2238 /* load SSL certificates */
2239
2240 #ifndef SSL_OP_NO_COMPRESSION
2241 #define SSL_OP_NO_COMPRESSION 0
2242 #endif
2243 #ifndef SSL_MODE_RELEASE_BUFFERS /* OpenSSL >= 1.0.0 */
2244 #define SSL_MODE_RELEASE_BUFFERS 0
2245 #endif
2246 long ssloptions = SSL_OP_ALL
2247 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2248 | SSL_OP_NO_COMPRESSION;
2249
2250 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2251 s->ssl_ctx = SSL_CTX_new(TLS_server_method());
2252 #else
2253 s->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
2254 #endif
2255 if (NULL == s->ssl_ctx) {
2256 log_error(srv->errh, __FILE__, __LINE__,
2257 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2258 return -1;
2259 }
2260
2261 #ifdef SSL_OP_NO_RENEGOTIATION /* openssl 1.1.0 */
2262 ssloptions |= SSL_OP_NO_RENEGOTIATION;
2263 #endif
2264 #ifdef SSL_OP_ENABLE_KTLS /* openssl 3.0.0 */
2265 ssloptions |= SSL_OP_ENABLE_KTLS;
2266 #endif
2267
2268 /* completely useless identifier;
2269 * required for client cert verification to work with sessions */
2270 if (0 == SSL_CTX_set_session_id_context(
2271 s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){
2272 log_error(srv->errh, __FILE__, __LINE__,
2273 "SSL: failed to set session context: %s",
2274 ERR_error_string(ERR_get_error(), NULL));
2275 return -1;
2276 }
2277
2278 const int disable_sess_cache =
2279 !config_feature_bool(srv, "ssl.session-cache", 0);
2280 if (disable_sess_cache)
2281 /* disable session cache; session tickets are preferred */
2282 SSL_CTX_set_session_cache_mode(s->ssl_ctx,
2283 SSL_SESS_CACHE_OFF
2284 | SSL_SESS_CACHE_NO_AUTO_CLEAR
2285 | SSL_SESS_CACHE_NO_INTERNAL);
2286
2287 SSL_CTX_set_options(s->ssl_ctx, ssloptions);
2288 SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback);
2289
2290 if (0 != SSL_OP_NO_SSLv2) {
2291 /* disable SSLv2 */
2292 if ((SSL_OP_NO_SSLv2
2293 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2))
2294 != SSL_OP_NO_SSLv2) {
2295 log_error(srv->errh, __FILE__, __LINE__,
2296 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2297 return -1;
2298 }
2299 }
2300
2301 if (0 != SSL_OP_NO_SSLv3) {
2302 /* disable SSLv3 */
2303 if ((SSL_OP_NO_SSLv3
2304 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3))
2305 != SSL_OP_NO_SSLv3) {
2306 log_error(srv->errh, __FILE__, __LINE__,
2307 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2308 return -1;
2309 }
2310 }
2311
2312 if (s->ssl_cipher_list) {
2313 /* Disable support for low encryption ciphers */
2314 if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){
2315 log_error(srv->errh, __FILE__, __LINE__,
2316 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2317 return -1;
2318 }
2319
2320 if (s->ssl_honor_cipher_order) {
2321 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE);
2322 }
2323 }
2324
2325 #ifdef SSL_OP_PRIORITIZE_CHACHA /*(openssl 1.1.1)*/
2326 if (s->ssl_honor_cipher_order)
2327 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_PRIORITIZE_CHACHA);
2328 #endif
2329
2330 if (!mod_openssl_ssl_conf_dhparameters(srv, s, NULL))
2331 return -1;
2332
2333 #ifdef TLSEXT_TYPE_session_ticket
2334 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2335 SSL_CTX_set_tlsext_ticket_key_cb(s->ssl_ctx, ssl_tlsext_ticket_key_cb);
2336 #else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
2337 SSL_CTX_set_tlsext_ticket_key_evp_cb(s->ssl_ctx,
2338 ssl_tlsext_ticket_key_cb);
2339 #endif
2340 #endif
2341
2342 #ifndef OPENSSL_NO_OCSP
2343 #ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
2344 SSL_CTX_set_tlsext_status_cb(s->ssl_ctx, ssl_tlsext_status_cb);
2345 #endif
2346 #endif
2347
2348 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
2349 && !defined(LIBRESSL_VERSION_NUMBER)
2350
2351 SSL_CTX_set_cert_cb(s->ssl_ctx, mod_openssl_cert_cb, NULL);
2352 UNUSED(p);
2353
2354 #if defined(BORINGSSL_API_VERSION) /* BoringSSL limitation */
2355 /* set cert store for auto-chaining
2356 * BoringSSL does not support SSL_set1_chain_cert_store() in cert_cb */
2357 if (s->ssl_ca_file && s->ssl_ca_file->certs) {
2358 if (!X509_STORE_up_ref(s->ssl_ca_file->certs))
2359 return -1;
2360 SSL_CTX_set_cert_store(s->ssl_ctx, s->ssl_ca_file->certs);
2361 }
2362 #endif
2363
2364 #else /* OPENSSL_VERSION_NUMBER < 0x10002000 */
2365
2366 /* load all ssl.ca-files specified in the config into each SSL_CTX
2367 * XXX: This might be a bit excessive, but are all trusted CAs
2368 * TODO: prefer to load on-demand in mod_openssl_cert_cb()
2369 * for openssl >= 1.0.2 */
2370 if (!mod_openssl_load_ca_files(s->ssl_ctx, p, srv))
2371 return -1;
2372
2373 if (s->ssl_verifyclient) {
2374 if (NULL == s->ssl_ca_file) {
2375 log_error(srv->errh, __FILE__, __LINE__,
2376 "SSL: You specified ssl.verifyclient.activate "
2377 "but no ssl.verifyclient.ca-file");
2378 return -1;
2379 }
2380 /* WTH openssl? SSL_CTX_set_client_CA_list() calls set0_CA_list(),
2381 * but there is no set1_CA_list() to simply up the reference count
2382 * (without needing to duplicate the list) */
2383 /* WTH wolfssl? wolfSSL_dup_CA_list() is a stub which returns NULL
2384 * and so DN names in cert request are not set here.
2385 * (A patch has been submitted to WolfSSL to correct this)*/
2386 STACK_OF(X509_NAME) * const cert_names = s->ssl_ca_dn_file
2387 ? s->ssl_ca_dn_file
2388 : s->ssl_ca_file->names;
2389 SSL_CTX_set_client_CA_list(s->ssl_ctx, SSL_dup_CA_list(cert_names));
2390 int mode = SSL_VERIFY_PEER;
2391 if (s->ssl_verifyclient_enforce) {
2392 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2393 }
2394 SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback);
2395 SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1);
2396 if (s->ssl_ca_crl_file && !buffer_is_blank(s->ssl_ca_crl_file)) {
2397 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx);
2398 if (!mod_openssl_load_cacrls(store, s->ssl_ca_crl_file, srv))
2399 return -1;
2400 }
2401 }
2402
2403 if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx,
2404 s->pc->ssl_pemfile->ptr)) {
2405 log_error(srv->errh, __FILE__, __LINE__,
2406 "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
2407 s->pc->ssl_pemfile->ptr);
2408 return -1;
2409 }
2410
2411 if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->pc->ssl_pemfile_pkey)) {
2412 log_error(srv->errh, __FILE__, __LINE__,
2413 "SSL: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
2414 s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
2415 return -1;
2416 }
2417
2418 if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) {
2419 log_error(srv->errh, __FILE__, __LINE__,
2420 "SSL: Private key does not match the certificate public key, "
2421 "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
2422 s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
2423 return -1;
2424 }
2425
2426 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000 */
2427
2428 #if defined(BORINGSSL_API_VERSION)
2429 #define SSL_CTX_set_default_read_ahead(ctx,m) \
2430 SSL_CTX_set_read_ahead(ctx,m)
2431 #endif
2432 SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead);
2433 SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx)
2434 | SSL_MODE_ENABLE_PARTIAL_WRITE
2435 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
2436 | SSL_MODE_RELEASE_BUFFERS);
2437
2438 #ifndef OPENSSL_NO_TLSEXT
2439 #ifdef SSL_CLIENT_HELLO_SUCCESS
2440 SSL_CTX_set_client_hello_cb(s->ssl_ctx,mod_openssl_client_hello_cb,srv);
2441 #else
2442 if (!SSL_CTX_set_tlsext_servername_callback(
2443 s->ssl_ctx, network_ssl_servername_callback) ||
2444 !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) {
2445 log_error(srv->errh, __FILE__, __LINE__,
2446 "SSL: failed to initialize TLS servername callback, "
2447 "openssl library does not support TLS servername extension");
2448 return -1;
2449 }
2450 #endif
2451
2452 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2453 SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL);
2454 #endif
2455 #endif
2456
2457 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
2458 || defined(BORINGSSL_API_VERSION) \
2459 || defined(LIBRESSL_VERSION_NUMBER)
2460 if (!SSL_CTX_set_min_proto_version(s->ssl_ctx, TLS1_2_VERSION))
2461 return -1;
2462 #endif
2463
2464 if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) {
2465 if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1;
2466 /* (force compression disabled, the default, if HTTP/2 enabled) */
2467 if (srv->srvconf.h2proto)
2468 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_COMPRESSION);
2469 }
2470
2471 return 0;
2472 }
2473
2474
2475 #define LIGHTTPD_DEFAULT_CIPHER_LIST \
2476 "EECDH+AESGCM:AES256+EECDH:CHACHA20:!SHA1:!SHA256:!SHA384"
2477
2478
2479 static int
mod_openssl_set_defaults_sockets(server * srv,plugin_data * p)2480 mod_openssl_set_defaults_sockets(server *srv, plugin_data *p)
2481 {
2482 static const config_plugin_keys_t cpk[] = {
2483 { CONST_STR_LEN("ssl.engine"),
2484 T_CONFIG_BOOL,
2485 T_CONFIG_SCOPE_SOCKET }
2486 ,{ CONST_STR_LEN("ssl.cipher-list"),
2487 T_CONFIG_STRING,
2488 T_CONFIG_SCOPE_SOCKET }
2489 ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"),
2490 T_CONFIG_ARRAY_KVSTRING,
2491 T_CONFIG_SCOPE_SOCKET }
2492 ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */
2493 T_CONFIG_STRING,
2494 T_CONFIG_SCOPE_CONNECTION }
2495 ,{ CONST_STR_LEN("ssl.stek-file"),
2496 T_CONFIG_STRING,
2497 T_CONFIG_SCOPE_SERVER }
2498 ,{ NULL, 0,
2499 T_CONFIG_UNSET,
2500 T_CONFIG_SCOPE_UNSET }
2501 };
2502 static const buffer default_ssl_cipher_list =
2503 { CONST_STR_LEN(LIGHTTPD_DEFAULT_CIPHER_LIST), 0 };
2504
2505 p->ssl_ctxs = ck_calloc(srv->config_context->used, sizeof(plugin_ssl_ctx));
2506
2507 int rc = HANDLER_GO_ON;
2508 plugin_data_base srvplug;
2509 memset(&srvplug, 0, sizeof(srvplug));
2510 plugin_data_base * const ps = &srvplug;
2511 if (!config_plugin_values_init(srv, ps, cpk, "mod_openssl"))
2512 return HANDLER_ERROR;
2513
2514 plugin_config_socket defaults;
2515 memset(&defaults, 0, sizeof(defaults));
2516 defaults.ssl_cipher_list = &default_ssl_cipher_list;
2517
2518 /* process and validate config directives for global and $SERVER["socket"]
2519 * (init i to 0 if global context; to 1 to skip empty global context) */
2520 for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) {
2521 config_cond_info cfginfo;
2522 config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id);
2523 int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET);
2524 int count_not_engine = 0;
2525
2526 plugin_config_socket conf;
2527 memcpy(&conf, &defaults, sizeof(conf));
2528 config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0];
2529 for (; -1 != cpv->k_id; ++cpv) {
2530 /* ignore ssl.pemfile (k_id=3); included to process global scope */
2531 if (!is_socket_scope && cpv->k_id != 3) {
2532 log_error(srv->errh, __FILE__, __LINE__,
2533 "%s is valid only in global scope or "
2534 "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k);
2535 continue;
2536 }
2537 ++count_not_engine;
2538 switch (cpv->k_id) {
2539 case 0: /* ssl.engine */
2540 conf.ssl_enabled = (0 != cpv->v.u);
2541 --count_not_engine;
2542 break;
2543 case 1: /* ssl.cipher-list */
2544 if (!buffer_is_blank(cpv->v.b)) {
2545 conf.ssl_cipher_list = cpv->v.b;
2546 /*(historical use might list non-PFS ciphers)*/
2547 conf.ssl_honor_cipher_order = 1;
2548 log_error(srv->errh, __FILE__, __LINE__,
2549 "%s is deprecated. "
2550 "Please prefer lighttpd secure TLS defaults, or use "
2551 "ssl.openssl.ssl-conf-cmd \"CipherString\" to set custom "
2552 "cipher list.", cpk[cpv->k_id].k);
2553 }
2554 break;
2555 case 2: /* ssl.openssl.ssl-conf-cmd */
2556 *(const array **)&conf.ssl_conf_cmd = cpv->v.a;
2557 break;
2558 case 3: /* ssl.pemfile */
2559 /* ignore here; included to process global scope when
2560 * ssl.pemfile is set, but ssl.engine is not "enable" */
2561 break;
2562 case 4: /* ssl.stek-file */
2563 if (!buffer_is_blank(cpv->v.b))
2564 p->ssl_stek_file = cpv->v.b->ptr;
2565 break;
2566 default:/* should not happen */
2567 break;
2568 }
2569 }
2570 if (HANDLER_GO_ON != rc) break;
2571 if (0 == i) memcpy(&defaults, &conf, sizeof(conf));
2572
2573 if (0 != i && !conf.ssl_enabled) continue;
2574
2575 /* fill plugin_config_socket with global context then $SERVER["socket"]
2576 * only for directives directly in current $SERVER["socket"] condition*/
2577
2578 /*conf.pc = p->defaults.pc;*/
2579 conf.ssl_ca_file = p->defaults.ssl_ca_file;
2580 conf.ssl_ca_dn_file = p->defaults.ssl_ca_dn_file;
2581 conf.ssl_ca_crl_file = p->defaults.ssl_ca_crl_file;
2582 conf.ssl_verifyclient = p->defaults.ssl_verifyclient;
2583 conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce;
2584 conf.ssl_verifyclient_depth = p->defaults.ssl_verifyclient_depth;
2585 conf.ssl_read_ahead = p->defaults.ssl_read_ahead;
2586
2587 int sidx = ps->cvlist[i].k_id;
2588 for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) {
2589 if (p->cvlist[j].k_id != sidx) continue;
2590 /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/
2591 cpv = p->cvlist + p->cvlist[j].v.u2[0];
2592 for (; -1 != cpv->k_id; ++cpv) {
2593 ++count_not_engine;
2594 switch (cpv->k_id) {
2595 case 0: /* ssl.pemfile */
2596 if (cpv->vtype == T_CONFIG_LOCAL)
2597 conf.pc = cpv->v.v;
2598 break;
2599 case 2: /* ssl.ca-file */
2600 if (cpv->vtype == T_CONFIG_LOCAL)
2601 conf.ssl_ca_file = cpv->v.v;
2602 break;
2603 case 3: /* ssl.ca-dn-file */
2604 if (cpv->vtype == T_CONFIG_LOCAL)
2605 conf.ssl_ca_dn_file = cpv->v.v;
2606 break;
2607 case 4: /* ssl.ca-crl-file */
2608 conf.ssl_ca_crl_file = cpv->v.b;
2609 break;
2610 case 5: /* ssl.read-ahead */
2611 conf.ssl_read_ahead = (0 != cpv->v.u);
2612 break;
2613 case 6: /* ssl.disable-client-renegotiation */
2614 /*(ignored; unsafe renegotiation disabled by default)*/
2615 break;
2616 case 7: /* ssl.verifyclient.activate */
2617 conf.ssl_verifyclient = (0 != cpv->v.u);
2618 break;
2619 case 8: /* ssl.verifyclient.enforce */
2620 conf.ssl_verifyclient_enforce = (0 != cpv->v.u);
2621 break;
2622 case 9: /* ssl.verifyclient.depth */
2623 conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
2624 break;
2625 #if 0 /*(cpk->k_id remapped in mod_openssl_set_defaults())*/
2626 case 15:/* ssl.verifyclient.ca-file */
2627 case 16:/* ssl.verifyclient.ca-dn-file */
2628 case 17:/* ssl.verifyclient.ca-crl-file */
2629 #endif
2630 default:
2631 break;
2632 }
2633 }
2634 break;
2635 }
2636
2637 if (NULL == conf.pc) {
2638 if (0 == i && !conf.ssl_enabled) continue;
2639 if (0 != i) {
2640 /* inherit ssl settings from global scope
2641 * (if only ssl.engine = "enable" and no other ssl.* settings)
2642 * (This is for convenience when defining both IPv4 and IPv6
2643 * and desiring to inherit the ssl config from global context
2644 * without having to duplicate the directives)*/
2645 if (count_not_engine
2646 || (conf.ssl_enabled && NULL == p->ssl_ctxs[0].ssl_ctx)) {
2647 log_error(srv->errh, __FILE__, __LINE__,
2648 "ssl.pemfile has to be set in same $SERVER[\"socket\"] scope "
2649 "as other ssl.* directives, unless only ssl.engine is set, "
2650 "inheriting ssl.* from global scope");
2651 rc = HANDLER_ERROR;
2652 continue;
2653 }
2654 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
2655 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/
2656 continue;
2657 }
2658 /* PEM file is required */
2659 log_error(srv->errh, __FILE__, __LINE__,
2660 "ssl.pemfile has to be set when ssl.engine = \"enable\"");
2661 rc = HANDLER_ERROR;
2662 continue;
2663 }
2664
2665 /* configure ssl_ctx for socket */
2666
2667 /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/
2668 if (0 == network_init_ssl(srv, &conf, p)) {
2669 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
2670 s->ssl_ctx = conf.ssl_ctx;
2671 }
2672 else {
2673 SSL_CTX_free(conf.ssl_ctx);
2674 rc = HANDLER_ERROR;
2675 }
2676 }
2677
2678 #ifdef TLSEXT_TYPE_session_ticket
2679 if (rc == HANDLER_GO_ON && ssl_is_init)
2680 mod_openssl_session_ticket_key_check(p, log_epoch_secs);
2681 #endif
2682
2683 free(srvplug.cvlist);
2684 return rc;
2685 }
2686
2687
SETDEFAULTS_FUNC(mod_openssl_set_defaults)2688 SETDEFAULTS_FUNC(mod_openssl_set_defaults)
2689 {
2690 static const config_plugin_keys_t cpk[] = {
2691 { CONST_STR_LEN("ssl.pemfile"),
2692 T_CONFIG_STRING,
2693 T_CONFIG_SCOPE_CONNECTION }
2694 ,{ CONST_STR_LEN("ssl.privkey"),
2695 T_CONFIG_STRING,
2696 T_CONFIG_SCOPE_CONNECTION }
2697 ,{ CONST_STR_LEN("ssl.ca-file"),
2698 T_CONFIG_STRING,
2699 T_CONFIG_SCOPE_CONNECTION }
2700 ,{ CONST_STR_LEN("ssl.ca-dn-file"),
2701 T_CONFIG_STRING,
2702 T_CONFIG_SCOPE_CONNECTION }
2703 ,{ CONST_STR_LEN("ssl.ca-crl-file"),
2704 T_CONFIG_STRING,
2705 T_CONFIG_SCOPE_CONNECTION }
2706 ,{ CONST_STR_LEN("ssl.read-ahead"),
2707 T_CONFIG_BOOL,
2708 T_CONFIG_SCOPE_CONNECTION }
2709 ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"),
2710 T_CONFIG_BOOL, /*(directive ignored)*/
2711 T_CONFIG_SCOPE_CONNECTION }
2712 ,{ CONST_STR_LEN("ssl.verifyclient.activate"),
2713 T_CONFIG_BOOL,
2714 T_CONFIG_SCOPE_CONNECTION }
2715 ,{ CONST_STR_LEN("ssl.verifyclient.enforce"),
2716 T_CONFIG_BOOL,
2717 T_CONFIG_SCOPE_CONNECTION }
2718 ,{ CONST_STR_LEN("ssl.verifyclient.depth"),
2719 T_CONFIG_SHORT,
2720 T_CONFIG_SCOPE_CONNECTION }
2721 ,{ CONST_STR_LEN("ssl.verifyclient.username"),
2722 T_CONFIG_STRING,
2723 T_CONFIG_SCOPE_CONNECTION }
2724 ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"),
2725 T_CONFIG_BOOL,
2726 T_CONFIG_SCOPE_CONNECTION }
2727 ,{ CONST_STR_LEN("ssl.acme-tls-1"),
2728 T_CONFIG_STRING,
2729 T_CONFIG_SCOPE_CONNECTION }
2730 ,{ CONST_STR_LEN("ssl.stapling-file"),
2731 T_CONFIG_STRING,
2732 T_CONFIG_SCOPE_CONNECTION }
2733 ,{ CONST_STR_LEN("debug.log-ssl-noise"),
2734 T_CONFIG_BOOL,
2735 T_CONFIG_SCOPE_CONNECTION }
2736 ,{ CONST_STR_LEN("ssl.verifyclient.ca-file"),
2737 T_CONFIG_STRING,
2738 T_CONFIG_SCOPE_CONNECTION }
2739 ,{ CONST_STR_LEN("ssl.verifyclient.ca-dn-file"),
2740 T_CONFIG_STRING,
2741 T_CONFIG_SCOPE_CONNECTION }
2742 ,{ CONST_STR_LEN("ssl.verifyclient.ca-crl-file"),
2743 T_CONFIG_STRING,
2744 T_CONFIG_SCOPE_CONNECTION }
2745 ,{ NULL, 0,
2746 T_CONFIG_UNSET,
2747 T_CONFIG_SCOPE_UNSET }
2748 };
2749
2750 plugin_data * const p = p_d;
2751 p->srv = srv;
2752 p->cafiles = array_init(0);
2753 if (!config_plugin_values_init(srv, p, cpk, "mod_openssl"))
2754 return HANDLER_ERROR;
2755
2756 const buffer *default_ssl_ca_crl_file = NULL;
2757
2758 /* process and validate config directives
2759 * (init i to 0 if global context; to 1 to skip empty global context) */
2760 for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
2761 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
2762 config_plugin_value_t *pemfile = NULL;
2763 config_plugin_value_t *privkey = NULL;
2764 const buffer *ssl_stapling_file = NULL;
2765 const buffer *ssl_ca_file = NULL;
2766 const buffer *ssl_ca_dn_file = NULL;
2767 const buffer *ssl_ca_crl_file = NULL;
2768 X509_STORE *ca_store = NULL;
2769 for (; -1 != cpv->k_id; ++cpv) {
2770 switch (cpv->k_id) {
2771 case 0: /* ssl.pemfile */
2772 if (!buffer_is_blank(cpv->v.b)) pemfile = cpv;
2773 break;
2774 case 1: /* ssl.privkey */
2775 if (!buffer_is_blank(cpv->v.b)) privkey = cpv;
2776 break;
2777 case 15:/* ssl.verifyclient.ca-file */
2778 cpv->k_id = 2;
2779 __attribute_fallthrough__
2780 case 2: /* ssl.ca-file */
2781 if (buffer_is_blank(cpv->v.b)) break;
2782 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
2783 ssl_ca_file = cpv->v.b;
2784 cpv->v.v = mod_openssl_load_cacerts(ssl_ca_file, srv->errh);
2785 if (NULL != cpv->v.v) {
2786 cpv->vtype = T_CONFIG_LOCAL;
2787 ca_store = ((plugin_cacerts *)cpv->v.v)->certs;
2788 }
2789 else {
2790 log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2791 ERR_error_string(ERR_get_error(), NULL),
2792 ssl_ca_file->ptr);
2793 return HANDLER_ERROR;
2794 }
2795 break;
2796 case 16:/* ssl.verifyclient.ca-dn-file */
2797 cpv->k_id = 3;
2798 __attribute_fallthrough__
2799 case 3: /* ssl.ca-dn-file */
2800 if (buffer_is_blank(cpv->v.b)) break;
2801 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
2802 ssl_ca_dn_file = cpv->v.b;
2803 cpv->v.v = SSL_load_client_CA_file(ssl_ca_dn_file->ptr);
2804 if (NULL != cpv->v.v) {
2805 cpv->vtype = T_CONFIG_LOCAL;
2806 }
2807 else {
2808 log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2809 ERR_error_string(ERR_get_error(), NULL),
2810 ssl_ca_dn_file->ptr);
2811 return HANDLER_ERROR;
2812 }
2813 break;
2814 case 17:/* ssl.verifyclient.ca-crl-file */
2815 cpv->k_id = 4;
2816 __attribute_fallthrough__
2817 case 4: /* ssl.ca-crl-file */
2818 if (buffer_is_blank(cpv->v.b)) break;
2819 ssl_ca_crl_file = cpv->v.b;
2820 if (0 == i) default_ssl_ca_crl_file = cpv->v.b;
2821 break;
2822 case 5: /* ssl.read-ahead */
2823 case 6: /* ssl.disable-client-renegotiation */
2824 /*(ignored; unsafe renegotiation disabled by default)*/
2825 case 7: /* ssl.verifyclient.activate */
2826 case 8: /* ssl.verifyclient.enforce */
2827 break;
2828 case 9: /* ssl.verifyclient.depth */
2829 if (cpv->v.shrt > 255) {
2830 log_error(srv->errh, __FILE__, __LINE__,
2831 "%s is absurdly large (%hu); limiting to 255",
2832 cpk[cpv->k_id].k, cpv->v.shrt);
2833 cpv->v.shrt = 255;
2834 }
2835 break;
2836 case 10:/* ssl.verifyclient.username */
2837 if (buffer_is_blank(cpv->v.b))
2838 cpv->v.b = NULL;
2839 break;
2840 case 11:/* ssl.verifyclient.exportcert */
2841 break;
2842 case 12:/* ssl.acme-tls-1 */
2843 if (buffer_is_blank(cpv->v.b))
2844 cpv->v.b = NULL;
2845 break;
2846 case 13:/* ssl.stapling-file */
2847 if (!buffer_is_blank(cpv->v.b))
2848 ssl_stapling_file = cpv->v.b;
2849 break;
2850 case 14:/* debug.log-ssl-noise */
2851 #if 0 /*(handled further above)*/
2852 case 15:/* ssl.verifyclient.ca-file */
2853 case 16:/* ssl.verifyclient.ca-dn-file */
2854 case 17:/* ssl.verifyclient.ca-crl-file */
2855 #endif
2856 break;
2857 default:/* should not happen */
2858 break;
2859 }
2860 }
2861
2862 #if OPENSSL_VERSION_NUMBER < 0x10002000 /* p->cafiles for legacy only */ \
2863 || defined(LIBRESSL_VERSION_NUMBER)
2864 /* load all ssl.ca-files into a single chain */
2865 /*(certificate load order might matter)*/
2866 if (ssl_ca_dn_file)
2867 array_insert_value(p->cafiles, BUF_PTR_LEN(ssl_ca_dn_file));
2868 if (ssl_ca_file)
2869 array_insert_value(p->cafiles, BUF_PTR_LEN(ssl_ca_file));
2870 UNUSED(ca_store);
2871 UNUSED(ssl_ca_crl_file);
2872 UNUSED(default_ssl_ca_crl_file);
2873 #else
2874 if (NULL == ca_store && ssl_ca_crl_file && i != 0) {
2875 log_error(srv->errh, __FILE__, __LINE__,
2876 "ssl.verifyclient.ca-crl-file (%s) ignored unless issued with "
2877 "ssl.verifyclient.ca-file", ssl_ca_crl_file->ptr);
2878 }
2879 else if (ca_store && (ssl_ca_crl_file || default_ssl_ca_crl_file)) {
2880 /* prior behavior in lighttpd allowed ssl.ca-crl-file only in global
2881 * scope or $SERVER["socket"], so this inheritance from global scope
2882 * is reasonable. This code does not implement inheritance of
2883 * ssl.ca-crl-file from $SERVER["socket"] into nested $HTTP["host"],
2884 * but the solution is to repeat ssl.ca-crl-file where ssl.ca-file
2885 * is issued (and to not unnecessarily repeat ssl.ca-file)
2886 * Alternative: write code to load ssl.ca-crl-file into (X509_CRL *)
2887 * using PEM_read_bio_X509_CRL() and in mod_openssl_cert_cb(),
2888 * create a new (X509_STORE *) which merges with CA (X509_STORE *)
2889 * using X509_STORE_add_cert() and X509_STORE_add_crl(), and keeps
2890 * the result in our (plugin_cert *) for reuse */
2891 if (NULL == ssl_ca_crl_file)
2892 ssl_ca_crl_file = default_ssl_ca_crl_file;
2893 if (!mod_openssl_load_cacrls(ca_store, ssl_ca_crl_file, srv))
2894 return HANDLER_ERROR;
2895 }
2896 #endif
2897
2898 if (pemfile) {
2899 #ifdef OPENSSL_NO_TLSEXT
2900 config_cond_info cfginfo;
2901 uint32_t j = (uint32_t)p->cvlist[i].k_id;
2902 config_get_config_cond_info(&cfginfo, j);
2903 if (j > 0 && (COMP_SERVER_SOCKET != cfginfo.comp
2904 || cfginfo.cond != CONFIG_COND_EQ)) {
2905 if (COMP_HTTP_HOST == cfginfo.comp)
2906 log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2907 "can't use ssl.pemfile with $HTTP[\"host\"], "
2908 "as openssl version does not support TLS extensions");
2909 else
2910 log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2911 "ssl.pemfile only works in SSL socket binding context "
2912 "as openssl version does not support TLS extensions");
2913 return HANDLER_ERROR;
2914 }
2915 #endif
2916 if (NULL == privkey) privkey = pemfile;
2917 pemfile->v.v =
2918 network_openssl_load_pemfile(srv, pemfile->v.b, privkey->v.b,
2919 ssl_stapling_file);
2920 if (pemfile->v.v)
2921 pemfile->vtype = T_CONFIG_LOCAL;
2922 else
2923 return HANDLER_ERROR;
2924 }
2925 }
2926
2927 p->defaults.ssl_verifyclient = 0;
2928 p->defaults.ssl_verifyclient_enforce = 1;
2929 p->defaults.ssl_verifyclient_depth = 9;
2930 p->defaults.ssl_verifyclient_export_cert = 0;
2931 p->defaults.ssl_read_ahead = 0;
2932
2933 /* initialize p->defaults from global config context */
2934 if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
2935 const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
2936 if (-1 != cpv->k_id)
2937 mod_openssl_merge_config(&p->defaults, cpv);
2938 }
2939
2940 #if OPENSSL_VERSION_NUMBER < 0x10101000L \
2941 && !defined(LIBRESSL_VERSION_NUMBER)
2942 log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2943 "openssl library version is outdated and has reached end-of-life. "
2944 "As of 1 Jan 2020, only openssl 1.1.1 and later continue to receive "
2945 "security patches from openssl.org");
2946 #endif
2947
2948 return mod_openssl_set_defaults_sockets(srv, p);
2949 }
2950
2951
2952 __attribute_cold__
2953 static int
mod_openssl_write_err(SSL * const ssl,int wr,connection * const con,log_error_st * const errh)2954 mod_openssl_write_err (SSL * const ssl, int wr, connection * const con,
2955 log_error_st * const errh)
2956 {
2957 int ssl_r;
2958 unsigned long err;
2959
2960 switch ((ssl_r = SSL_get_error(ssl, wr))) {
2961 case SSL_ERROR_WANT_READ:
2962 con->is_readable = -1;
2963 return 0; /* try again later */
2964 case SSL_ERROR_WANT_WRITE:
2965 con->is_writable = -1;
2966 return 0; /* try again later */
2967 case SSL_ERROR_SYSCALL:
2968 /* perhaps we have error waiting in our error-queue */
2969 if (0 != (err = ERR_get_error())) {
2970 do {
2971 log_error(errh, __FILE__, __LINE__,
2972 "SSL: %d %d %s",ssl_r,wr,ERR_error_string(err,NULL));
2973 } while ((err = ERR_get_error()));
2974 }
2975 else if (wr == -1) {
2976 /* no, but we have errno */
2977 switch (errno) {
2978 case EPIPE:
2979 case ECONNRESET:
2980 return -2;
2981 default:
2982 log_perror(errh, __FILE__, __LINE__,
2983 "SSL: %d %d", ssl_r, wr);
2984 break;
2985 }
2986 }
2987 else {
2988 /* neither error-queue nor errno ? */
2989 log_perror(errh, __FILE__, __LINE__,
2990 "SSL (error): %d %d", ssl_r, wr);
2991 }
2992 break;
2993
2994 case SSL_ERROR_ZERO_RETURN:
2995 /* clean shutdown on the remote side */
2996 if (wr == 0) return -2;
2997
2998 __attribute_fallthrough__
2999 default:
3000 while ((err = ERR_get_error()))
3001 log_error(errh, __FILE__, __LINE__,
3002 "SSL: %d %d %s", ssl_r, wr, ERR_error_string(err, NULL));
3003 break;
3004 }
3005
3006 return -1;
3007 }
3008
3009
3010 /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
3011 *
3012 * it has to stay at the same location all the time to satisfy the needs
3013 * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE
3014 *
3015 * buffer is allocated once, is NOT realloced (note: not thread-safe)
3016 *
3017 * (Note: above restriction no longer true since SSL_CTX_set_mode() is
3018 * called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
3019 * */
3020
3021 /* copy small mem chunks into single large buffer before SSL_write()
3022 * to reduce number times write() called underneath SSL_write() and
3023 * potentially reduce number of packets generated if TCP_NODELAY */
3024
3025
3026 static int
3027 mod_openssl_close_notify(handler_ctx *hctx);
3028
3029
3030 static int
connection_write_cq_ssl(connection * const con,chunkqueue * const cq,off_t max_bytes)3031 connection_write_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes)
3032 {
3033 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id];
3034 SSL * const ssl = hctx->ssl;
3035 log_error_st * const errh = hctx->errh;
3036
3037 if (__builtin_expect( (0 != hctx->close_notify), 0))
3038 return mod_openssl_close_notify(hctx);
3039
3040 while (max_bytes > 0 && !chunkqueue_is_empty(cq)) {
3041 char *data = local_send_buffer;
3042 uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes
3043 ? LOCAL_SEND_BUFSIZE
3044 : (uint32_t)max_bytes;
3045 int wr;
3046
3047 if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1;
3048 if (__builtin_expect( (0 == data_len), 0)) {
3049 chunkqueue_remove_finished_chunks(cq);
3050 continue;
3051 }
3052
3053 /**
3054 * SSL_write man-page
3055 *
3056 * WARNING
3057 * When an SSL_write() operation has to be repeated because of
3058 * SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be
3059 * repeated with the same arguments.
3060 */
3061
3062 ERR_clear_error();
3063 wr = SSL_write(ssl, data, data_len);
3064
3065 if (__builtin_expect( (hctx->renegotiations > 1), 0)) {
3066 log_error(errh, __FILE__, __LINE__,
3067 "SSL: renegotiation initiated by client, killing connection");
3068 return -1;
3069 }
3070
3071 if (wr <= 0)
3072 return mod_openssl_write_err(ssl, wr, con, errh);
3073
3074 chunkqueue_mark_written(cq, wr);
3075 max_bytes -= wr;
3076
3077 if ((size_t) wr < data_len) break; /* try again later */
3078 }
3079
3080 return 0;
3081 }
3082
3083
3084 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3085 static int
connection_write_cq_ssl_ktls(connection * const con,chunkqueue * const cq,off_t max_bytes)3086 connection_write_cq_ssl_ktls (connection * const con, chunkqueue * const cq, off_t max_bytes)
3087 {
3088 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id];
3089
3090 if (__builtin_expect( (0 != hctx->close_notify), 0))
3091 return mod_openssl_close_notify(hctx);
3092
3093 /* not done: scan cq for FILE_CHUNK within first max_bytes rather than
3094 * only using SSL_sendfile() if the first chunk is FILE_CHUNK.
3095 * Checking first chunk for FILE_CHUNK means that initial response headers
3096 * and beginning of file will be read into memory before subsequent writes
3097 * use SSL_sendfile(). TBD: possible to be further optimized? */
3098
3099 for (chunk *c; (c = cq->first) && c->type == FILE_CHUNK; ) {
3100 off_t len = c->file.length - c->offset;
3101 if (len > max_bytes) len = max_bytes;
3102 if (0 == len) break; /*(FILE_CHUNK or max_bytes should not be 0)*/
3103 if (-1 == c->file.fd && 0 != chunkqueue_open_file_chunk(cq, hctx->errh))
3104 return -1;
3105
3106 ossl_ssize_t wr =
3107 SSL_sendfile(hctx->ssl, c->file.fd, c->offset, (size_t)len, 0);
3108 if (wr < 0)
3109 return mod_openssl_write_err(hctx->ssl, (int)wr, con, hctx->errh);
3110
3111 chunkqueue_mark_written(cq, wr);
3112 max_bytes -= wr;
3113
3114 if (wr < len) return 0; /* try again later */
3115 }
3116
3117 return connection_write_cq_ssl(con, cq, max_bytes);
3118 }
3119 #endif
3120
3121
3122 static int
connection_read_cq_ssl(connection * const con,chunkqueue * const cq,off_t max_bytes)3123 connection_read_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes)
3124 {
3125 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id];
3126 int len;
3127 char *mem = NULL;
3128 size_t mem_len = 0;
3129
3130 UNUSED(max_bytes);
3131
3132 if (__builtin_expect( (0 != hctx->close_notify), 0))
3133 return mod_openssl_close_notify(hctx);
3134
3135 ERR_clear_error();
3136 do {
3137 len = SSL_pending(hctx->ssl);
3138 mem_len = len < 2048 ? 2048 : (size_t)len;
3139 chunk * const ckpt = cq->last;
3140 mem = chunkqueue_get_memory(cq, &mem_len);
3141
3142 len = SSL_read(hctx->ssl, mem, mem_len);
3143 chunkqueue_use_memory(cq, ckpt, len > 0 ? len : 0);
3144
3145 if (hctx->renegotiations > 1) {
3146 log_error(hctx->errh, __FILE__, __LINE__,
3147 "SSL: renegotiation initiated by client, killing connection (%s)",
3148 con->dst_addr_buf.ptr);
3149 return -1;
3150 }
3151
3152 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3153 /* ideally should be done only once, after handshake completes,
3154 * so check each time for HTTP/2 so that we do not re-enable */
3155 if (hctx->r->http_version < HTTP_VERSION_2
3156 && BIO_get_ktls_send(SSL_get_wbio(hctx->ssl)) > 0)
3157 con->network_write = connection_write_cq_ssl_ktls;
3158 #endif
3159 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
3160 if (hctx->alpn) {
3161 if (hctx->alpn == MOD_OPENSSL_ALPN_H2) {
3162 if (0 != mod_openssl_alpn_h2_policy(hctx))
3163 return -1;
3164 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
3165 /*(not expecting FILE_CHUNKs in write_queue with h2,
3166 * so skip ktls and SSL_sendfile; reset to default)*/
3167 con->network_write = connection_write_cq_ssl;
3168 #endif
3169 }
3170 else if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) {
3171 chunkqueue_reset(cq);
3172 /* initiate handshake in order to send ServerHello.
3173 * Once TLS handshake is complete, return -1 to result in
3174 * CON_STATE_ERROR so that socket connection is quickly closed*/
3175 if (1 == SSL_do_handshake(hctx->ssl)) return -1;
3176 len = -1;
3177 break;
3178 }
3179 hctx->alpn = 0;
3180 }
3181 #endif
3182 } while (len > 0
3183 && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0));
3184
3185 if (len < 0) {
3186 int oerrno = errno;
3187 int rc, ssl_err;
3188 switch ((rc = SSL_get_error(hctx->ssl, len))) {
3189 case SSL_ERROR_WANT_WRITE:
3190 con->is_writable = -1;
3191 __attribute_fallthrough__
3192 case SSL_ERROR_WANT_READ:
3193 con->is_readable = 0;
3194
3195 /* the manual says we have to call SSL_read with the same arguments
3196 * next time. we ignore this restriction; no one has complained
3197 * about it in 1.5 yet, so it probably works anyway.
3198 */
3199
3200 return 0;
3201 case SSL_ERROR_SYSCALL:
3202 /**
3203 * man SSL_get_error()
3204 *
3205 * SSL_ERROR_SYSCALL
3206 * Some I/O error occurred. The OpenSSL error queue may contain
3207 * more information on the error. If the error queue is empty
3208 * (i.e. ERR_get_error() returns 0), ret can be used to find out
3209 * more about the error: If ret == 0, an EOF was observed that
3210 * violates the protocol. If ret == -1, the underlying BIO
3211 * reported an I/O error (for socket I/O on Unix systems, consult
3212 * errno for details).
3213 *
3214 */
3215 while((ssl_err = ERR_get_error())) {
3216 /* get all errors from the error-queue */
3217 log_error(hctx->errh, __FILE__, __LINE__,
3218 "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL));
3219 }
3220
3221 switch(oerrno) {
3222 case ECONNRESET:
3223 if (!hctx->conf.ssl_log_noise) break;
3224 __attribute_fallthrough__
3225 default:
3226 /* (oerrno should be something like ECONNABORTED not 0
3227 * if client disconnected before anything was sent
3228 * (e.g. TCP connection probe), but it does not appear
3229 * that openssl provides such notification, not even
3230 * something like SSL_R_SSL_HANDSHAKE_FAILURE) */
3231 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise)
3232 break;
3233
3234 errno = oerrno; /*(for log_perror())*/
3235 log_perror(hctx->errh, __FILE__, __LINE__,
3236 "SSL: %d %d %d", len, rc, oerrno);
3237 break;
3238 }
3239
3240 break;
3241 case SSL_ERROR_ZERO_RETURN:
3242 /* clean shutdown on the remote side */
3243
3244 /* future: might set flag to record that we received CLOSE_NOTIFY
3245 * TLS alert from peer, then have future calls to this func return
3246 * the equivalent of EOF, but we also want to remove read interest
3247 * on fd, perhaps by setting RDHUP. If setting is_readable, ensure
3248 * that callers avoid spinning if we return EOF while is_readable.
3249 *
3250 * Should we treat this like len == 0 below and return -2 ? */
3251
3252 /*__attribute_fallthrough__*/
3253 default:
3254 while((ssl_err = ERR_get_error())) {
3255 switch (ERR_GET_REASON(ssl_err)) {
3256 case SSL_R_SSL_HANDSHAKE_FAILURE:
3257 #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
3258 case SSL_R_UNEXPECTED_EOF_WHILE_READING:
3259 #endif
3260 #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA
3261 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
3262 #endif
3263 #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN
3264 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
3265 #endif
3266 #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
3267 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
3268 #endif
3269 if (!hctx->conf.ssl_log_noise) continue;
3270 break;
3271 default:
3272 break;
3273 }
3274 /* get all errors from the error-queue */
3275 log_error(hctx->errh, __FILE__, __LINE__,
3276 "SSL: %d %s (%s)", rc, ERR_error_string(ssl_err, NULL),
3277 con->dst_addr_buf.ptr);
3278 }
3279 break;
3280 }
3281 return -1;
3282 } else if (len == 0) {
3283 con->is_readable = 0;
3284 /* the other end close the connection -> KEEP-ALIVE */
3285
3286 return -2;
3287 } else {
3288 return 0;
3289 }
3290 }
3291
3292
CONNECTION_FUNC(mod_openssl_handle_con_accept)3293 CONNECTION_FUNC(mod_openssl_handle_con_accept)
3294 {
3295 const server_socket *srv_sock = con->srv_socket;
3296 if (!srv_sock->is_ssl) return HANDLER_GO_ON;
3297
3298 plugin_data *p = p_d;
3299 handler_ctx * const hctx = handler_ctx_init();
3300 request_st * const r = &con->request;
3301 hctx->r = r;
3302 hctx->con = con;
3303 hctx->tmp_buf = con->srv->tmp_buf;
3304 hctx->errh = r->conf.errh;
3305 con->plugin_ctx[p->id] = hctx;
3306 buffer_blank(&r->uri.authority);
3307
3308 plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx;
3309 hctx->ssl = SSL_new(s->ssl_ctx);
3310 if (NULL != hctx->ssl
3311 && SSL_set_app_data(hctx->ssl, hctx)
3312 && SSL_set_fd(hctx->ssl, con->fd)) {
3313 SSL_set_accept_state(hctx->ssl);
3314 con->network_read = connection_read_cq_ssl;
3315 con->network_write = connection_write_cq_ssl;
3316 con->proto_default_port = 443; /* "https" */
3317 mod_openssl_patch_config(r, &hctx->conf);
3318 return HANDLER_GO_ON;
3319 }
3320 else {
3321 log_error(r->conf.errh, __FILE__, __LINE__,
3322 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
3323 return HANDLER_ERROR;
3324 }
3325 }
3326
3327
3328 static void
mod_openssl_detach(handler_ctx * hctx)3329 mod_openssl_detach(handler_ctx *hctx)
3330 {
3331 /* step aside from further SSL processing
3332 * (used after handle_connection_shut_wr hook) */
3333 /* future: might restore prior network_read and network_write fn ptrs */
3334 hctx->con->is_ssl_sock = 0;
3335 /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
3336 if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
3337 hctx->close_notify = 1;
3338 }
3339
3340
CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)3341 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)
3342 {
3343 plugin_data *p = p_d;
3344 handler_ctx *hctx = con->plugin_ctx[p->id];
3345 if (NULL == hctx) return HANDLER_GO_ON;
3346
3347 hctx->close_notify = -2;
3348 if (SSL_is_init_finished(hctx->ssl)) {
3349 mod_openssl_close_notify(hctx);
3350 }
3351 else {
3352 mod_openssl_detach(hctx);
3353 }
3354
3355 return HANDLER_GO_ON;
3356 }
3357
3358
3359 static int
mod_openssl_close_notify(handler_ctx * hctx)3360 mod_openssl_close_notify(handler_ctx *hctx)
3361 {
3362 int ret, ssl_r;
3363 unsigned long err;
3364 log_error_st *errh;
3365
3366 if (1 == hctx->close_notify) return -2;
3367
3368 ERR_clear_error();
3369 switch ((ret = SSL_shutdown(hctx->ssl))) {
3370 case 1:
3371 mod_openssl_detach(hctx);
3372 return -2;
3373 case 0:
3374 /* Drain SSL read buffers in case pending records need processing.
3375 * Limit to reading next record to avoid denial of service when CPU
3376 * processing TLS is slower than arrival speed of TLS data packets.
3377 * (unless hctx->conf.ssl_read_ahead is set)
3378 *
3379 * references:
3380 *
3381 * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection"
3382 * https://github.com/openssl/openssl/issues/6262
3383 *
3384 * The peer is still allowed to send data after receiving the
3385 * "close notify" event. If the peer did send data it need to be
3386 * processed by calling SSL_read() before calling SSL_shutdown() a
3387 * second time. SSL_read() will indicate the end of the peer data by
3388 * returning <= 0 and SSL_get_error() returning
3389 * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read()
3390 * between SSL_shutdown() calls.
3391 *
3392 * Additional discussion in "Auto retry in shutdown"
3393 * https://github.com/openssl/openssl/pull/6340
3394 */
3395 ssl_r = SSL_pending(hctx->ssl);
3396 if (ssl_r) {
3397 do {
3398 char buf[4096];
3399 ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf));
3400 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret)));
3401 }
3402
3403 ERR_clear_error();
3404 switch ((ret = SSL_shutdown(hctx->ssl))) {
3405 case 1:
3406 mod_openssl_detach(hctx);
3407 return -2;
3408 case 0:
3409 hctx->close_notify = -1;
3410 return 0;
3411 default:
3412 break;
3413 }
3414
3415 __attribute_fallthrough__
3416 default:
3417
3418 if (!SSL_is_init_finished(hctx->ssl)) {
3419 mod_openssl_detach(hctx);
3420 return -2;
3421 }
3422
3423 switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) {
3424 case SSL_ERROR_WANT_WRITE:
3425 case SSL_ERROR_WANT_READ:
3426 case SSL_ERROR_ZERO_RETURN: /*(unexpected here)*/
3427 hctx->close_notify = -1;
3428 return 0; /* try again later */
3429 case SSL_ERROR_SYSCALL:
3430 if (0 == ERR_peek_error()) {
3431 switch(errno) {
3432 case 0: /*ssl bug (see lighttpd ticket #2213)*/
3433 case EPIPE:
3434 case ECONNRESET:
3435 mod_openssl_detach(hctx);
3436 return -2;
3437 default:
3438 log_perror(hctx->r->conf.errh, __FILE__, __LINE__,
3439 "SSL (error): %d %d", ssl_r, ret);
3440 break;
3441 }
3442 break;
3443 }
3444 __attribute_fallthrough__
3445 default:
3446 errh = hctx->r->conf.errh;
3447 while((err = ERR_get_error())) {
3448 log_error(errh, __FILE__, __LINE__,
3449 "SSL: %d %d %s", ssl_r, ret, ERR_error_string(err, NULL));
3450 }
3451
3452 break;
3453 }
3454 }
3455 ERR_clear_error();
3456 hctx->close_notify = -1;
3457 return ret;
3458 }
3459
3460
CONNECTION_FUNC(mod_openssl_handle_con_close)3461 CONNECTION_FUNC(mod_openssl_handle_con_close)
3462 {
3463 plugin_data *p = p_d;
3464 handler_ctx *hctx = con->plugin_ctx[p->id];
3465 if (NULL != hctx) {
3466 con->plugin_ctx[p->id] = NULL;
3467 handler_ctx_free(hctx);
3468 }
3469
3470 return HANDLER_GO_ON;
3471 }
3472
3473
3474 static void
https_add_ssl_client_subject(request_st * const r,X509_NAME * xn)3475 https_add_ssl_client_subject (request_st * const r, X509_NAME *xn)
3476 {
3477 const size_t prelen = sizeof("SSL_CLIENT_S_DN_")-1;
3478 char key[64] = "SSL_CLIENT_S_DN_";
3479 for (int i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) {
3480 int xobjnid;
3481 const char * xobjsn;
3482 X509_NAME_ENTRY *xe;
3483
3484 if (!(xe = X509_NAME_get_entry(xn, i))) {
3485 continue;
3486 }
3487 xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe));
3488 xobjsn = OBJ_nid2sn(xobjnid);
3489 if (xobjsn) {
3490 const size_t len = strlen(xobjsn);
3491 if (prelen+len >= sizeof(key)) continue;
3492 memcpy(key+prelen, xobjsn, len); /*(not '\0'-terminated)*/
3493 http_header_env_set(r, key, prelen+len,
3494 (const char*)X509_NAME_ENTRY_get_data(xe)->data,
3495 X509_NAME_ENTRY_get_data(xe)->length);
3496 }
3497 }
3498 }
3499
3500
3501 __attribute_cold__
3502 static void
https_add_ssl_client_verify_err(buffer * const b,long status)3503 https_add_ssl_client_verify_err (buffer * const b, long status)
3504 {
3505 char errstr[256];
3506 ERR_error_string_n(status, errstr, sizeof(errstr));
3507 buffer_append_string(b, errstr);
3508 }
3509
3510
3511 __attribute_noinline__
3512 static void
https_add_ssl_client_entries(request_st * const r,handler_ctx * const hctx)3513 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx)
3514 {
3515 X509 *xs;
3516 X509_NAME *xn;
3517 buffer *vb = http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_VERIFY"));
3518
3519 long vr = SSL_get_verify_result(hctx->ssl);
3520 if (vr != X509_V_OK) {
3521 buffer_copy_string_len(vb, CONST_STR_LEN("FAILED:"));
3522 https_add_ssl_client_verify_err(vb, vr);
3523 return;
3524 } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) {
3525 buffer_copy_string_len(vb, CONST_STR_LEN("NONE"));
3526 return;
3527 } else {
3528 buffer_copy_string_len(vb, CONST_STR_LEN("SUCCESS"));
3529 }
3530
3531 xn = X509_get_subject_name(xs);
3532 {
3533 char buf[256];
3534 int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf));
3535 if (len > 0) {
3536 if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1;
3537 http_header_env_set(r,
3538 CONST_STR_LEN("SSL_CLIENT_S_DN"),
3539 buf, (size_t)len);
3540 }
3541 }
3542
3543 https_add_ssl_client_subject(r, xn);
3544
3545 {
3546 ASN1_INTEGER *xsn = X509_get_serialNumber(xs);
3547 BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL);
3548 char *serialHex = BN_bn2hex(serialBN);
3549 http_header_env_set(r,
3550 CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
3551 serialHex, strlen(serialHex));
3552 OPENSSL_free(serialHex);
3553 BN_free(serialBN);
3554 }
3555
3556 if (hctx->conf.ssl_verifyclient_username) {
3557 /* pick one of the exported values as "REMOTE_USER", for example
3558 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
3559 * or
3560 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
3561 */
3562 const buffer *varname = hctx->conf.ssl_verifyclient_username;
3563 vb = http_header_env_get(r, BUF_PTR_LEN(varname));
3564 if (vb) { /* same as mod_auth_api.c:http_auth_setenv() */
3565 http_header_env_set(r,
3566 CONST_STR_LEN("REMOTE_USER"),
3567 BUF_PTR_LEN(vb));
3568 http_header_env_set(r,
3569 CONST_STR_LEN("AUTH_TYPE"),
3570 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
3571 }
3572 }
3573
3574 if (hctx->conf.ssl_verifyclient_export_cert) {
3575 BIO *bio;
3576 if (NULL != (bio = BIO_new(BIO_s_mem()))) {
3577 PEM_write_bio_X509(bio, xs);
3578 const int n = BIO_pending(bio);
3579
3580 vb = http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_CERT"));
3581 buffer_extend(vb, (uint32_t)n);
3582 BIO_read(bio, vb->ptr, n);
3583 BIO_free(bio);
3584 }
3585 }
3586 X509_free(xs);
3587 }
3588
3589
3590 static void
http_cgi_ssl_env(request_st * const r,handler_ctx * const hctx)3591 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx)
3592 {
3593 const char *s;
3594 const SSL_CIPHER *cipher;
3595
3596 s = SSL_get_version(hctx->ssl);
3597 http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s));
3598
3599 if ((cipher = SSL_get_current_cipher(hctx->ssl))) {
3600 int usekeysize, algkeysize = 0;
3601 char buf[LI_ITOSTRING_LENGTH];
3602 s = SSL_CIPHER_get_name(cipher);
3603 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s));
3604 usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize);
3605 if (0 == algkeysize) algkeysize = usekeysize;
3606 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
3607 buf, li_itostrn(buf, sizeof(buf), usekeysize));
3608 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
3609 buf, li_itostrn(buf, sizeof(buf), algkeysize));
3610 }
3611 }
3612
3613
REQUEST_FUNC(mod_openssl_handle_request_env)3614 REQUEST_FUNC(mod_openssl_handle_request_env)
3615 {
3616 plugin_data *p = p_d;
3617 /* simple flag for request_env_patched */
3618 if (r->plugin_ctx[p->id]) return HANDLER_GO_ON;
3619 handler_ctx *hctx = r->con->plugin_ctx[p->id];
3620 if (NULL == hctx) return HANDLER_GO_ON;
3621 r->plugin_ctx[p->id] = (void *)(uintptr_t)1u;
3622
3623 http_cgi_ssl_env(r, hctx);
3624 if (hctx->conf.ssl_verifyclient) {
3625 https_add_ssl_client_entries(r, hctx);
3626 }
3627
3628 return HANDLER_GO_ON;
3629 }
3630
3631
REQUEST_FUNC(mod_openssl_handle_uri_raw)3632 REQUEST_FUNC(mod_openssl_handle_uri_raw)
3633 {
3634 /* mod_openssl must be loaded prior to mod_auth
3635 * if mod_openssl is configured to set REMOTE_USER based on client cert */
3636 /* mod_openssl must be loaded after mod_extforward
3637 * if mod_openssl config is based on lighttpd.conf remote IP conditional
3638 * using remote IP address set by mod_extforward, *unless* PROXY protocol
3639 * is enabled with extforward.hap-PROXY = "enable", in which case the
3640 * reverse is true: mod_extforward must be loaded after mod_openssl */
3641 plugin_data *p = p_d;
3642 handler_ctx *hctx = r->con->plugin_ctx[p->id];
3643 if (NULL == hctx) return HANDLER_GO_ON;
3644
3645 mod_openssl_patch_config(r, &hctx->conf);
3646 if (hctx->conf.ssl_verifyclient) {
3647 mod_openssl_handle_request_env(r, p);
3648 }
3649
3650 return HANDLER_GO_ON;
3651 }
3652
3653
REQUEST_FUNC(mod_openssl_handle_request_reset)3654 REQUEST_FUNC(mod_openssl_handle_request_reset)
3655 {
3656 plugin_data *p = p_d;
3657 r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */
3658 return HANDLER_GO_ON;
3659 }
3660
3661
TRIGGER_FUNC(mod_openssl_handle_trigger)3662 TRIGGER_FUNC(mod_openssl_handle_trigger) {
3663 const plugin_data * const p = p_d;
3664 const unix_time64_t cur_ts = log_epoch_secs;
3665 if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/
3666 UNUSED(srv);
3667 UNUSED(p);
3668
3669 #ifdef TLSEXT_TYPE_session_ticket
3670 mod_openssl_session_ticket_key_check(p, cur_ts);
3671 #endif
3672
3673 #ifndef OPENSSL_NO_OCSP
3674 mod_openssl_refresh_stapling_files(srv, p, cur_ts);
3675 #endif
3676
3677 return HANDLER_GO_ON;
3678 }
3679
3680
3681 __attribute_cold__
3682 int mod_openssl_plugin_init (plugin *p);
mod_openssl_plugin_init(plugin * p)3683 int mod_openssl_plugin_init (plugin *p)
3684 {
3685 p->version = LIGHTTPD_VERSION_ID;
3686 p->name = "openssl";
3687 p->init = mod_openssl_init;
3688 p->cleanup = mod_openssl_free;
3689 p->priv_defaults= mod_openssl_set_defaults;
3690
3691 p->handle_connection_accept = mod_openssl_handle_con_accept;
3692 p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr;
3693 p->handle_connection_close = mod_openssl_handle_con_close;
3694 p->handle_uri_raw = mod_openssl_handle_uri_raw;
3695 p->handle_request_env = mod_openssl_handle_request_env;
3696 p->handle_request_reset = mod_openssl_handle_request_reset;
3697 p->handle_trigger = mod_openssl_handle_trigger;
3698
3699 return 0;
3700 }
3701
3702
3703 #if defined(BORINGSSL_API_VERSION) \
3704 || defined(LIBRESSL_VERSION_NUMBER)
3705
3706 static int
mod_openssl_ssl_conf_proto_val(server * srv,const buffer * b,int max)3707 mod_openssl_ssl_conf_proto_val (server *srv, const buffer *b, int max)
3708 {
3709 if (NULL == b) /* default: min TLSv1.2, max TLSv1.3 */
3710 #ifdef TLS1_3_VERSION
3711 return max ? TLS1_3_VERSION : TLS1_2_VERSION;
3712 #else
3713 return TLS1_2_VERSION;
3714 #endif
3715 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("None"))) /*"disable" limit*/
3716 return max
3717 ?
3718 #ifdef TLS1_3_VERSION
3719 TLS1_3_VERSION
3720 #else
3721 TLS1_2_VERSION
3722 #endif
3723 : TLS1_VERSION;
3724 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.0")))
3725 return TLS1_VERSION;
3726 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.1")))
3727 return TLS1_1_VERSION;
3728 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.2")))
3729 return TLS1_2_VERSION;
3730 #ifdef TLS1_3_VERSION
3731 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3")))
3732 return TLS1_3_VERSION;
3733 #endif
3734 else {
3735 if (buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1"))
3736 || buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1.2")))
3737 log_error(srv->errh, __FILE__, __LINE__,
3738 "SSL: ssl.openssl.ssl-conf-cmd %s %s ignored",
3739 max ? "MaxProtocol" : "MinProtocol", b->ptr);
3740 else
3741 log_error(srv->errh, __FILE__, __LINE__,
3742 "SSL: ssl.openssl.ssl-conf-cmd %s %s invalid; ignored",
3743 max ? "MaxProtocol" : "MinProtocol", b->ptr);
3744 }
3745 #ifdef TLS1_3_VERSION
3746 return max ? TLS1_3_VERSION : TLS1_2_VERSION;
3747 #else
3748 return TLS1_2_VERSION;
3749 #endif
3750 }
3751
3752
3753 static int
mod_openssl_ssl_conf_cmd(server * srv,plugin_config_socket * s)3754 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s)
3755 {
3756 /* reference:
3757 * https://www.openssl.org/docs/manmaster/man3/SSL_CONF_cmd.html */
3758 int rc = 0;
3759 buffer *cipherstring = NULL;
3760 buffer *ciphersuites = NULL;
3761 buffer *minb = NULL;
3762 buffer *maxb = NULL;
3763 buffer *curves = NULL;
3764
3765 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
3766 data_string *ds = (data_string *)s->ssl_conf_cmd->data[i];
3767 if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString")))
3768 cipherstring = &ds->value;
3769 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites")))
3770 ciphersuites = &ds->value;
3771 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves"))
3772 || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups")))
3773 curves = &ds->value;
3774 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("DHParameters"))){
3775 if (!buffer_is_blank(&ds->value)) {
3776 if (!mod_openssl_ssl_conf_dhparameters(srv, s, &ds->value))
3777 rc = -1;
3778 }
3779 }
3780 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol")))
3781 maxb = &ds->value;
3782 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol")))
3783 minb = &ds->value;
3784 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) {
3785 /* openssl config for Protocol=... is complex and deprecated */
3786 log_error(srv->errh, __FILE__, __LINE__,
3787 "SSL: ssl.openssl.ssl-conf-cmd %s ignored; "
3788 "use MinProtocol=... and MaxProtocol=... instead",
3789 ds->key.ptr);
3790 }
3791 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) {
3792 for (char *v = ds->value.ptr, *e; *v; v = e) {
3793 while (*v == ' ' || *v == '\t' || *v == ',') ++v;
3794 int flag = 1;
3795 if (*v == '-') {
3796 flag = 0;
3797 ++v;
3798 }
3799 else if (*v == '+')
3800 ++v;
3801 for (e = v; light_isalpha(*e); ++e) ;
3802 switch ((int)(e-v)) {
3803 #ifdef SSL_OP_ENABLE_KTLS
3804 case 4:
3805 if (buffer_eq_icase_ssn(v, "KTLS", 4)) {
3806 if (flag)
3807 SSL_CTX_set_options(s->ssl_ctx,
3808 SSL_OP_ENABLE_KTLS);
3809 else
3810 SSL_CTX_clear_options(s->ssl_ctx,
3811 SSL_OP_ENABLE_KTLS);
3812 continue;
3813 }
3814 break;
3815 #endif
3816 case 11:
3817 if (buffer_eq_icase_ssn(v, "Compression", 11)) {
3818 /* (force disabled, the default, if HTTP/2 enabled) */
3819 if (srv->srvconf.h2proto)
3820 flag = 0;
3821 if (flag)
3822 SSL_CTX_clear_options(s->ssl_ctx,
3823 SSL_OP_NO_COMPRESSION);
3824 else
3825 SSL_CTX_set_options(s->ssl_ctx,
3826 SSL_OP_NO_COMPRESSION);
3827 continue;
3828 }
3829 break;
3830 case 13:
3831 if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) {
3832 if (flag)
3833 SSL_CTX_clear_options(s->ssl_ctx,
3834 SSL_OP_NO_TICKET);
3835 else
3836 SSL_CTX_set_options(s->ssl_ctx,
3837 SSL_OP_NO_TICKET);
3838 continue;
3839 }
3840 break;
3841 case 16:
3842 if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) {
3843 if (flag)
3844 SSL_CTX_set_options(s->ssl_ctx,
3845 SSL_OP_CIPHER_SERVER_PREFERENCE);
3846 else
3847 SSL_CTX_clear_options(s->ssl_ctx,
3848 SSL_OP_CIPHER_SERVER_PREFERENCE);
3849 s->ssl_honor_cipher_order = flag;
3850 continue;
3851 }
3852 break;
3853 default:
3854 break;
3855 }
3856 /* warn if not explicitly handled or ignored above */
3857 if (!flag) --v;
3858 log_error(srv->errh, __FILE__, __LINE__,
3859 "SSL: ssl.openssl.ssl-conf-cmd Options %.*s "
3860 "ignored", (int)(e-v), v);
3861 }
3862 }
3863 #if 0
3864 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) {
3865 }
3866 #endif
3867 else {
3868 /* warn if not explicitly handled or ignored above */
3869 log_error(srv->errh, __FILE__, __LINE__,
3870 "SSL: ssl.openssl.ssl-conf-cmd %s ignored",
3871 ds->key.ptr);
3872 }
3873
3874 }
3875
3876 if (minb) {
3877 int n = mod_openssl_ssl_conf_proto_val(srv, minb, 0);
3878 if (!SSL_CTX_set_min_proto_version(s->ssl_ctx, n))
3879 rc = -1;
3880 }
3881
3882 if (maxb) {
3883 int x = mod_openssl_ssl_conf_proto_val(srv, maxb, 1);
3884 if (!SSL_CTX_set_max_proto_version(s->ssl_ctx, x))
3885 rc = -1;
3886 }
3887
3888 if (ciphersuites && !buffer_is_blank(ciphersuites)) {
3889 #if defined(LIBRESSL_VERSION_NUMBER) && defined(LIBRESSL_HAS_TLS1_3)
3890 if (SSL_CTX_set_ciphersuites(s->ssl_ctx, ciphersuites->ptr) != 1) {
3891 log_error(srv->errh, __FILE__, __LINE__,
3892 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
3893 rc = -1;
3894 }
3895 #endif
3896 }
3897
3898 if (cipherstring && !buffer_is_blank(cipherstring)) {
3899 /* Disable support for low encryption ciphers */
3900 buffer_append_string_len(cipherstring,
3901 CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
3902 if (SSL_CTX_set_cipher_list(s->ssl_ctx, cipherstring->ptr) != 1) {
3903 log_error(srv->errh, __FILE__, __LINE__,
3904 "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
3905 rc = -1;
3906 }
3907
3908 if (s->ssl_honor_cipher_order)
3909 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
3910 }
3911
3912 if (curves && !buffer_is_blank(curves)) {
3913 if (!mod_openssl_ssl_conf_curves(srv, s, curves))
3914 rc = -1;
3915 }
3916
3917 return rc;
3918 }
3919
3920 #endif /* BORINGSSL_API_VERSION || LIBRESSL_VERSION_NUMBER */
3921