xref: /lighttpd1.4/src/mod_mbedtls.c (revision d5e899e2)
1 /*
2  * mod_mbedtls - mbedTLS support for lighttpd
3  *
4  * Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
5  * License: BSD 3-clause (same as lighttpd)
6  */
7 /*
8  * reference:
9  * https://tls.mbed.org/high-level-design
10  * https://tls.mbed.org/tech-updates/blog/mbedtls-2.0-defaults-best-practices
11  * mbedTLS header files (mbedtls/ssl.h and others) are extremely well-documented
12  * https://tls.mbed.org/api/  (generated from mbedTLS headers and code)
13  *
14  * mbedTLS limitations:
15  * - mbedTLS does not currently support TLSv1.3
16  * - mbedTLS does not currently support OCSP
17  *   https://tls.mbed.org/discussions/feature-request/ocsp-stapling
18  *   TLS/DTLS: OCSP Stapling support #880
19  *   https://github.com/ARMmbed/mbedtls/issues/880
20  *   Add support for writing OCSP requests and parsing OCSP responses #1197
21  *   https://github.com/ARMmbed/mbedtls/issues/1197
22  *
23  * future possible enhancements to lighttpd mod_mbedtls:
24  * - session cache (though session tickets are implemented)
25  *     sample code in mbedtls:programs/ssl/ssl_server2.c
26  *     (and do not enable unless server.feature-flags ssl.session-cache enabled)
27  *
28  * Note: If session tickets are -not- disabled with
29  *     ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
30  *   mbedtls rotates the session ticket key according to 2x timeout set with
31  *   mbedtls_ssl_ticket_setup() (currently 43200 s, so 24 hour ticket lifetime)
32  *   This is fine for use with a single lighttpd instance, but with multiple
33  *   lighttpd workers, no coordinated STEK (server ticket encryption key)
34  *   rotation occurs unless ssl.stek-file is defined and maintained (preferred),
35  *   or if some external job restarts lighttpd.  Restarting lighttpd generates a
36  *   new key that is shared by lighttpd workers for the lifetime of the new key.
37  *   If the rotation period expires and lighttpd has not been restarted, and if
38  *   ssl.stek-file is not in use, then lighttpd workers will generate new
39  *   independent keys, making session tickets less effective for session
40  *   resumption, since clients have a lower chance for future connections to
41  *   reach the same lighttpd worker.  However, things will still work, and a new
42  *   session will be created if session resumption fails.  Admins should plan to
43  *   restart lighttpd at least every 12 hours if session tickets are enabled and
44  *   multiple lighttpd workers are configured.  Since that is likely disruptive,
45  *   if multiple lighttpd workers are configured, ssl.stek-file should be
46  *   defined and the file maintained externally.
47  */
48 #include "first.h"
49 
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <stdarg.h>
55 #include <stdlib.h>
56 #include <stdio.h>      /* vsnprintf() */
57 #include <string.h>
58 
59 #include <mbedtls/config.h>
60 #include <mbedtls/ctr_drbg.h>
61 #include <mbedtls/dhm.h>
62 #include <mbedtls/error.h>
63 #include <mbedtls/entropy.h>
64 #include <mbedtls/oid.h>
65 #include <mbedtls/pem.h>
66 #include <mbedtls/ssl.h>
67 #include <mbedtls/ssl_internal.h> /* struct mbedtls_ssl_transform */
68 #include <mbedtls/x509.h>
69 #include <mbedtls/x509_crt.h>
70 #include <mbedtls/version.h>
71 
72 #if MBEDTLS_VERSION_NUMBER >= 0x02040000 /* mbedtls 2.04.0 */
73 #include <mbedtls/net_sockets.h>
74 #else
75 #include <mbedtls/net.h>
76 #endif
77 
78 #if defined(MBEDTLS_SSL_TICKET_C)
79 #include <mbedtls/ssl_ticket.h>
80 #endif
81 
82 #ifndef MBEDTLS_X509_CRT_PARSE_C
83 #error "lighttpd requires that mbedtls be built with MBEDTLS_X509_CRT_PARSE_C"
84 #endif
85 
86 #include "base.h"
87 #include "fdevent.h"
88 #include "http_header.h"
89 #include "http_kv.h"
90 #include "log.h"
91 #include "plugin.h"
92 #include "safe_memclear.h"
93 
94 typedef struct {
95     /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
96     mbedtls_pk_context ssl_pemfile_pkey;/* parsed private key structure */
97     mbedtls_x509_crt ssl_pemfile_x509;  /* parsed public key structure */
98     const buffer *ssl_pemfile;
99     const buffer *ssl_privkey;
100     int8_t need_chain;
101 } plugin_cert;
102 
103 typedef struct {
104     mbedtls_ssl_config *ssl_ctx;        /* context shared between mbedtls_ssl_CONTEXT structures */
105     int *ciphersuites;
106     mbedtls_ecp_group_id *curves;
107 } plugin_ssl_ctx;
108 
109 typedef struct {
110     mbedtls_ssl_config *ssl_ctx;        /* output from network_init_ssl() */
111     int *ciphersuites;                  /* output from network_init_ssl() */
112     mbedtls_ecp_group_id *curves;       /* output from network_init_ssl() */
113 
114     /*(used only during startup; not patched)*/
115     unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
116     unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
117     unsigned char ssl_empty_fragments;
118     unsigned char ssl_use_sslv2;
119     unsigned char ssl_use_sslv3;
120     const buffer *ssl_cipher_list;
121     const buffer *ssl_dh_file;
122     const buffer *ssl_ec_curve;
123     const buffer *ssl_acme_tls_1;
124     array *ssl_conf_cmd;
125 
126     /*(copied from plugin_data for socket ssl_ctx config)*/
127     plugin_cert *pc;
128     mbedtls_pk_context *ssl_pemfile_pkey; /* parsed private key structure */
129     mbedtls_x509_crt *ssl_pemfile_x509;   /* parsed public key structure */
130     mbedtls_x509_crt *ssl_ca_file;
131     const buffer *ssl_pemfile;
132     const buffer *ssl_privkey;
133     unsigned char ssl_session_ticket;
134     unsigned char ssl_verifyclient;
135     unsigned char ssl_verifyclient_enforce;
136     unsigned char ssl_verifyclient_depth;
137 } plugin_config_socket; /*(used at startup during configuration)*/
138 
139 typedef struct {
140     /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
141     plugin_cert *pc;
142     mbedtls_pk_context *ssl_pemfile_pkey; /* parsed private key structure */
143     mbedtls_x509_crt *ssl_pemfile_x509;   /* parsed public key structure */
144     const buffer *ssl_pemfile;
145     mbedtls_x509_crt *ssl_ca_file;
146     mbedtls_x509_crt *ssl_ca_dn_file;
147     mbedtls_x509_crl *ssl_ca_crl_file;
148 
149     unsigned char ssl_verifyclient;
150     unsigned char ssl_verifyclient_enforce;
151     unsigned char ssl_verifyclient_depth;
152     unsigned char ssl_verifyclient_export_cert;
153     unsigned char ssl_read_ahead;
154     unsigned char ssl_log_noise;
155     unsigned char ssl_disable_client_renegotiation;
156     const buffer *ssl_verifyclient_username;
157     const buffer *ssl_acme_tls_1;
158 } plugin_config;
159 
160 typedef struct {
161     PLUGIN_DATA;
162     plugin_ssl_ctx *ssl_ctxs;
163     plugin_config defaults;
164     server *srv;
165     /* NIST counter-mode deterministic random byte generator */
166     mbedtls_ctr_drbg_context ctr_drbg;
167     /* entropy collection and state management */
168     mbedtls_entropy_context entropy;
169   #if defined(MBEDTLS_SSL_SESSION_TICKETS)
170     mbedtls_ssl_ticket_context ticket_ctx;
171     const char *ssl_stek_file;
172   #endif
173 } plugin_data;
174 
175 static int ssl_is_init;
176 /* need assigned p->id for deep access of module handler_ctx for connection
177  *   i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
178 static plugin_data *plugin_data_singleton;
179 #define LOCAL_SEND_BUFSIZE MBEDTLS_SSL_MAX_CONTENT_LEN
180 static char *local_send_buffer;
181 
182 typedef struct {
183     mbedtls_ssl_context ssl;      /* mbedtls request/connection context */
184     request_st *r;
185     connection *con;
186     int8_t close_notify;
187     unsigned short alpn;
188     int handshake_done;
189     size_t pending_write;
190     plugin_config conf;
191     buffer *tmp_buf;
192     log_error_st *errh;
193     mbedtls_pk_context *acme_tls_1_pkey;
194     mbedtls_x509_crt *acme_tls_1_x509;
195 } handler_ctx;
196 
197 
198 static handler_ctx *
199 handler_ctx_init (void)
200 {
201     handler_ctx *hctx = calloc(1, sizeof(*hctx));
202     force_assert(hctx);
203     return hctx;
204 }
205 
206 
207 static void
208 handler_ctx_free (handler_ctx *hctx)
209 {
210     mbedtls_ssl_free(&hctx->ssl);
211     if (hctx->acme_tls_1_pkey) {
212         mbedtls_pk_free(hctx->acme_tls_1_pkey);
213         free(hctx->acme_tls_1_pkey);
214     }
215     if (hctx->acme_tls_1_x509) {
216         mbedtls_x509_crt_free(hctx->acme_tls_1_x509);
217         free(hctx->acme_tls_1_x509);
218     }
219     free(hctx);
220 }
221 
222 
223 #ifdef MBEDTLS_ERROR_C
224 __attribute_cold__
225 static void elog(log_error_st * const errh,
226                  const char * const file, const int line,
227                  const int rc, const char * const msg)
228 {
229     /* error logging convenience function that decodes mbedtls result codes */
230     char buf[256];
231     mbedtls_strerror(rc, buf, sizeof(buf));
232     log_error(errh, file, line, "MTLS: %s: %s (-0x%04x)", msg, buf, -rc);
233 }
234 #else
235 #define elog(errh, file, line, rc, msg) \
236     log_error((errh), (file), (line), "MTLS: %s: (-0x%04x)", (msg), -(rc))
237 #endif
238 
239 
240 __attribute_cold__
241 __attribute_format__((__printf__, 5, 6))
242 static void elogf(log_error_st * const errh,
243                   const char * const file, const int line,
244                   const int rc, const char * const fmt, ...)
245 {
246     char msg[1024];
247     va_list ap;
248     va_start(ap, fmt);
249     vsnprintf(msg, sizeof(msg), fmt, ap);
250     va_end(ap);
251     elog(errh, file, line, rc, msg);
252 }
253 
254 
255 #ifdef MBEDTLS_SSL_SESSION_TICKETS
256 
257 #define TLSEXT_KEYNAME_LENGTH  16
258 #define TLSEXT_TICK_KEY_LENGTH 32
259 
260 /* construct our own session ticket encryption key structure
261  * to store keys that are not yet active
262  * (mirror from mod_openssl, even though not all bits are used here) */
263 typedef struct tlsext_ticket_key_st {
264     time_t active_ts; /* tickets not issued w/ key until activation timestamp */
265     time_t expire_ts; /* key not valid after expiration timestamp */
266     unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
267     unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
268     unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
269 } tlsext_ticket_key_t;
270 
271 static tlsext_ticket_key_t session_ticket_keys[1]; /* temp store until active */
272 static time_t stek_rotate_ts;
273 
274 
275 static int
276 mod_mbedtls_session_ticket_key_file (const char *fn)
277 {
278     /* session ticket encryption key (STEK)
279      *
280      * STEK file should be stored in non-persistent storage,
281      *   e.g. /dev/shm/lighttpd/stek-file  (in memory)
282      * with appropriate permissions set to keep stek-file from being
283      * read by other users.  Where possible, systems should also be
284      * configured without swap.
285      *
286      * admin should schedule an independent job to periodically
287      *   generate new STEK up to 3 times during key lifetime
288      *   (lighttpd stores up to 3 keys)
289      *
290      * format of binary file is:
291      *    4-byte - format version (always 0; for use if format changes)
292      *    4-byte - activation timestamp
293      *    4-byte - expiration timestamp
294      *   16-byte - session ticket key name
295      *   32-byte - session ticket HMAC encrpytion key
296      *   32-byte - session ticket AES encrpytion key
297      *
298      * STEK file can be created with a command such as:
299      *   dd if=/dev/random bs=1 count=80 status=none | \
300      *     perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
301      *     > STEK-file.$$ && mv STEK-file.$$ STEK-file
302      *
303      * The above delays activation time by 5 mins (+300 sec) to allow file to
304      * be propagated to other machines.  (admin must handle this independently)
305      * If STEK generation is performed immediately prior to starting lighttpd,
306      * admin should activate keys immediately (without +300).
307      */
308     int buf[23]; /* 92 bytes */
309     int rc = 0; /*(will retry on next check interval upon any error)*/
310     if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
311         return rc;
312     if (buf[0] == 0) { /*(format version 0)*/
313         session_ticket_keys[0].active_ts = buf[1];
314         session_ticket_keys[0].expire_ts = buf[2];
315         memcpy(&session_ticket_keys[0].tick_key_name, buf+3, 80);
316         rc = 1;
317     }
318 
319     mbedtls_platform_zeroize(buf, sizeof(buf));
320     return rc;
321 }
322 
323 
324 static void
325 mod_mbedtls_session_ticket_key_check (plugin_data *p, const time_t cur_ts)
326 {
327     if (NULL == p->ssl_stek_file) return;
328 
329     struct stat st;
330     if (0 == stat(p->ssl_stek_file, &st) && st.st_mtime > stek_rotate_ts
331         && mod_mbedtls_session_ticket_key_file(p->ssl_stek_file)) {
332         stek_rotate_ts = cur_ts;
333     }
334 
335     tlsext_ticket_key_t *stek = session_ticket_keys;
336     if (stek->active_ts != 0 && stek->active_ts - 63 <= cur_ts) {
337         /* expect to get newer ssl.stek-file prior to mbedtls detecting
338          * expiration and internally generating a new key.  If not, then
339          * lifetime may be up to 2x specified lifetime until overwritten
340          * by mbedtls, but original key will be overwritten and discarded */
341         mbedtls_ssl_ticket_context *ctx = &p->ticket_ctx;
342         ctx->ticket_lifetime = stek->expire_ts - stek->active_ts;
343         ctx->active = 1 - ctx->active;
344         mbedtls_ssl_ticket_key *key = ctx->keys + ctx->active;
345         /* set generation_time to cur_ts instead of stek->active_ts
346          * since ctx->active was updated */
347         key->generation_time = cur_ts;
348         memcpy(key->name, stek->tick_key_name, sizeof(key->name));
349         /* With GCM and CCM, same context can encrypt & decrypt */
350         int rc = mbedtls_cipher_setkey(&key->ctx, stek->tick_aes_key,
351                                        mbedtls_cipher_get_key_bitlen(&key->ctx),
352                                        MBEDTLS_ENCRYPT);
353         if (0 != rc) { /* expire key immediately if error occurs */
354             key->generation_time = cur_ts - ctx->ticket_lifetime - 1;
355             ctx->active = 1 - ctx->active;
356         }
357         mbedtls_platform_zeroize(stek, sizeof(tlsext_ticket_key_t));
358     }
359 }
360 
361 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
362 
363 
364 INIT_FUNC(mod_mbedtls_init)
365 {
366     plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
367   #if defined(MBEDTLS_SSL_SESSION_TICKETS)
368     mbedtls_ssl_ticket_init(&plugin_data_singleton->ticket_ctx);
369   #endif
370     return plugin_data_singleton;
371 }
372 
373 
374 static int mod_mbedtls_init_once_mbedtls (server *srv)
375 {
376     if (ssl_is_init) return 1;
377     ssl_is_init = 1;
378 
379     plugin_data * const p = plugin_data_singleton;
380     mbedtls_ctr_drbg_init(&p->ctr_drbg); /* init empty NSIT random num gen */
381     mbedtls_entropy_init(&p->entropy);   /* init empty entropy collection struct
382                                                .. could add sources here too */
383 
384     int rc =                                      /* init RNG */
385       mbedtls_ctr_drbg_seed(&p->ctr_drbg,         /* random number generator */
386                             mbedtls_entropy_func, /* default entropy func */
387                             &p->entropy,          /* entropy context */
388                             NULL, 0);             /* no personalization data */
389     if (0 != rc) {
390         elog(srv->errh, __FILE__,__LINE__, rc,
391              "Init of random number generator failed");
392         return 0;
393     }
394 
395     local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
396     force_assert(NULL != local_send_buffer);
397 
398     return 1;
399 }
400 
401 
402 static void mod_mbedtls_free_mbedtls (void)
403 {
404     if (!ssl_is_init) return;
405 
406   #ifdef MBEDTLS_SSL_SESSION_TICKETS
407     mbedtls_platform_zeroize(session_ticket_keys, sizeof(session_ticket_keys));
408     stek_rotate_ts = 0;
409   #endif
410 
411     plugin_data * const p = plugin_data_singleton;
412     mbedtls_ctr_drbg_free(&p->ctr_drbg);
413     mbedtls_entropy_free(&p->entropy);
414   #if defined(MBEDTLS_SSL_SESSION_TICKETS)
415     mbedtls_ssl_ticket_free(&p->ticket_ctx);
416   #endif
417 
418     free(local_send_buffer);
419     ssl_is_init = 0;
420 }
421 
422 
423 static void
424 mod_mbedtls_free_config (server *srv, plugin_data * const p)
425 {
426     if (NULL != p->ssl_ctxs) {
427         mbedtls_ssl_config * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
428         /* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
429         for (uint32_t i = 1; i < srv->config_context->used; ++i) {
430             plugin_ssl_ctx * const s = p->ssl_ctxs + i;
431             if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope) {
432                 mbedtls_ssl_config_free(s->ssl_ctx);
433                 free(s->ciphersuites);
434                 free(s->curves);
435             }
436         }
437         /* free ssl_ctx from global scope */
438         if (ssl_ctx_global_scope) {
439             mbedtls_ssl_config_free(ssl_ctx_global_scope);
440             free(p->ssl_ctxs[0].ciphersuites);
441             free(p->ssl_ctxs[0].curves);
442         }
443         free(p->ssl_ctxs);
444     }
445 
446     if (NULL == p->cvlist) return;
447     /* (init i to 0 if global context; to 1 to skip empty global context) */
448     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
449         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
450         for (; -1 != cpv->k_id; ++cpv) {
451             switch (cpv->k_id) {
452               case 0: /* ssl.pemfile */
453                 if (cpv->vtype == T_CONFIG_LOCAL) {
454                     plugin_cert *pc = cpv->v.v;
455                     mbedtls_pk_free(&pc->ssl_pemfile_pkey);
456                     mbedtls_x509_crt_free(&pc->ssl_pemfile_x509);
457                     free(pc);
458                 }
459                 break;
460               case 2: /* ssl.ca-file */
461               case 3: /* ssl.ca-dn-file */
462                 if (cpv->vtype == T_CONFIG_LOCAL) {
463                     mbedtls_x509_crt *cacert = cpv->v.v;
464                     mbedtls_x509_crt_free(cacert);
465                     free(cacert);
466                 }
467                 break;
468               case 4: /* ssl.ca-dn-file */
469                 if (cpv->vtype == T_CONFIG_LOCAL) {
470                     mbedtls_x509_crl *crl = cpv->v.v;
471                     mbedtls_x509_crl_free(crl);
472                     free(crl);
473                 }
474                 break;
475               default:
476                 break;
477             }
478         }
479     }
480 }
481 
482 
483 FREE_FUNC(mod_mbedtls_free)
484 {
485     plugin_data *p = p_d;
486     if (NULL == p->srv) return;
487     mod_mbedtls_free_config(p->srv, p);
488     mod_mbedtls_free_mbedtls();
489 }
490 
491 
492 static void
493 mod_mbedtls_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
494 {
495     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
496       case 0: /* ssl.pemfile */
497         if (cpv->vtype == T_CONFIG_LOCAL)
498             pconf->pc = cpv->v.v;
499         break;
500       case 1: /* ssl.privkey */
501         break;
502       case 2: /* ssl.ca-file */
503         if (cpv->vtype == T_CONFIG_LOCAL)
504             pconf->ssl_ca_file = cpv->v.v;
505         break;
506       case 3: /* ssl.ca-dn-file */
507         if (cpv->vtype == T_CONFIG_LOCAL)
508             pconf->ssl_ca_dn_file = cpv->v.v;
509         break;
510       case 4: /* ssl.ca-crl-file */
511         if (cpv->vtype == T_CONFIG_LOCAL)
512             pconf->ssl_ca_dn_file = cpv->v.v;
513         break;
514       case 5: /* ssl.read-ahead */
515         pconf->ssl_read_ahead = (0 != cpv->v.u);
516         break;
517       case 6: /* ssl.disable-client-renegotiation */
518         pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
519         break;
520       case 7: /* ssl.verifyclient.activate */
521         pconf->ssl_verifyclient = (0 != cpv->v.u);
522         break;
523       case 8: /* ssl.verifyclient.enforce */
524         pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
525         break;
526       case 9: /* ssl.verifyclient.depth */
527         pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
528         break;
529       case 10:/* ssl.verifyclient.username */
530         pconf->ssl_verifyclient_username = cpv->v.b;
531         break;
532       case 11:/* ssl.verifyclient.exportcert */
533         pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
534         break;
535       case 12:/* ssl.acme-tls-1 */
536         pconf->ssl_acme_tls_1 = cpv->v.b;
537         break;
538       case 13:/* debug.log-ssl-noise */
539         pconf->ssl_log_noise = (unsigned char)cpv->v.shrt;
540         break;
541       default:/* should not happen */
542         return;
543     }
544 }
545 
546 
547 static void
548 mod_mbedtls_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
549 {
550     do {
551         mod_mbedtls_merge_config_cpv(pconf, cpv);
552     } while ((++cpv)->k_id != -1);
553 }
554 
555 
556 static void
557 mod_mbedtls_patch_config (request_st * const r, plugin_config * const pconf)
558 {
559     plugin_data * const p = plugin_data_singleton;
560     memcpy(pconf, &p->defaults, sizeof(plugin_config));
561     for (int i = 1, used = p->nconfig; i < used; ++i) {
562         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
563             mod_mbedtls_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
564     }
565 }
566 
567 
568 __attribute_pure__
569 static int
570 mod_mbedtls_crt_is_self_issued (const mbedtls_x509_crt * const crt)
571 {
572     const mbedtls_x509_buf * const issuer  = &crt->issuer_raw;
573     const mbedtls_x509_buf * const subject = &crt->subject_raw;
574     return subject->len == issuer->len
575         && 0 == memcmp(issuer->p, subject->p, subject->len);
576 }
577 
578 
579 static int
580 mod_mbedtls_construct_crt_chain (mbedtls_x509_crt *leaf, mbedtls_x509_crt *store, log_error_st *errh)
581 {
582     /* Historically, openssl will use the cert chain in (SSL_CTX *) if a cert
583      * does not have a chain configured in (SSL *).  While similar behavior
584      * could be achieved with mbedtls_x509_crt_parse_file(crt, ssl_ca_file->ptr)
585      * instead attempt to do better and build a proper, ordered cert chain. */
586 
587     if (leaf->next) return 0; /*(presume chain has already been provided)*/
588     if (store == NULL) return 0;/*(unable to proceed; chain may be incomplete)*/
589 
590     /* attempt to construct certificate chain from certificate store */
591     for (mbedtls_x509_crt *crt = leaf; crt; ) {
592         const mbedtls_x509_buf * const issuer = &crt->issuer_raw;
593 
594         /*(walk entire store in case certs are not properly sorted)*/
595         for (crt = store; crt; crt = crt->next) {
596             /* The raw issuer/subject data (DER) is used for quick comparison */
597             /* (see comments in mod_mbedtls_verify_cb())*/
598             const mbedtls_x509_buf * const subject = &crt->subject_raw;
599             if (issuer->len != subject->len
600                 || 0 != memcmp(subject->p, issuer->p, issuer->len)) continue;
601 
602             /* root cert is end condition; omit from chain of intermediates */
603             if (mod_mbedtls_crt_is_self_issued(crt))
604                 return 0;
605 
606             int rc =
607           #if MBEDTLS_VERSION_NUMBER >= 0x02110000 /* mbedtls 2.17.0 */
608               /* save memory by eliding copy of already-loaded raw DER */
609               mbedtls_x509_crt_parse_der_nocopy(leaf, crt->raw.p, crt->raw.len);
610           #else
611               mbedtls_x509_crt_parse_der(leaf, crt->raw.p, crt->raw.len);
612           #endif
613             if (0 != rc) { /*(failure not unexpected since already parsed)*/
614                 elog(errh, __FILE__, __LINE__, rc, "cert copy failed");
615                 return rc;
616             }
617             break;
618         }
619     }
620 
621     return 0; /*(no error, though cert chain may or may not be complete)*/
622 }
623 
624 
625 static int
626 mod_mbedtls_verify_cb (void *arg, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
627 {
628     handler_ctx * const hctx = (handler_ctx *)arg;
629 
630     if (depth > hctx->conf.ssl_verifyclient_depth) {
631         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
632                   "MTLS: client cert chain too long");
633         *flags |= MBEDTLS_X509_BADCERT_OTHER; /* cert chain too long */
634     }
635     else if (0 == depth && NULL != hctx->conf.ssl_ca_dn_file) {
636         /* verify that client cert is issued by CA in ssl.ca-dn-file
637          * if both ssl.ca-dn-file and ssl.ca-file were configured */
638         /* The raw issuer/subject data (DER) is used for quick comparison. */
639         const size_t len = crt->issuer_raw.len;
640         mbedtls_x509_crt *chain = hctx->conf.ssl_ca_dn_file;
641         do {
642           #if 0 /* x509_name_cmp() is not a public func in mbedtls */
643             if (0 == x509_name_cmp(&crt->issuer, &chain->subject))
644                 break;
645           #else
646             if (len == chain->subject_raw.len
647                 && 0 == memcmp(chain->subject_raw.p, crt->issuer_raw.p, len))
648                 break;
649           #endif
650         } while ((chain = chain->next));
651 
652         if (NULL == chain)
653             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
654     }
655     if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
656         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
657                   "MTLS: client cert not trusted");
658     }
659 
660     return 0;
661 }
662 
663 
664 #ifdef MBEDTLS_SSL_SERVER_NAME_INDICATION
665 static int
666 mod_mbedtls_SNI (void *arg, mbedtls_ssl_context *ssl, const unsigned char *servername, size_t len)
667 {
668     handler_ctx * const hctx = (handler_ctx *) arg;
669     buffer_copy_string(&hctx->r->uri.scheme, "https");
670 
671     request_st * const r = hctx->r;
672     if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
673         log_error(r->conf.errh, __FILE__, __LINE__,
674                   "MTLS: SNI name too long %.*s", (int)len, servername);
675         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
676     }
677 
678     /* use SNI to patch mod_mbedtls config and then reset COMP_HTTP_HOST */
679     buffer_copy_string_len(&r->uri.authority, (const char *)servername, len);
680     buffer_to_lower(&r->uri.authority);
681   #if 0
682     /*(r->uri.authority used below for configuration before request read;
683      * revisit for h2)*/
684     if (0 != http_request_host_policy(&r->uri.authority,
685                                       r->conf.http_parseopts, 443))
686         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
687   #endif
688 
689     const buffer * const ssl_pemfile = hctx->conf.pc->ssl_pemfile;
690 
691     r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
692                             |  (1 << COMP_HTTP_HOST);
693 
694     mod_mbedtls_patch_config(r, &hctx->conf);
695     /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
696     /*(done in configfile-glue.c:config_cond_cache_reset() after request hdrs read)*/
697     /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
698     /*buffer_clear(&r->uri.authority);*/
699 
700     /*(compare strings as ssl.pemfile might repeat same file in lighttpd.conf
701      * and mod_mbedtls does not attempt to de-dup)*/
702     if (!buffer_is_equal(hctx->conf.pc->ssl_pemfile, ssl_pemfile)) {
703         /* if needed, attempt to construct certificate chain for server cert */
704         if (hctx->conf.pc->need_chain) {
705             hctx->conf.pc->need_chain = 0; /*(attempt once to complete chain)*/
706             mbedtls_x509_crt *ssl_cred = &hctx->conf.pc->ssl_pemfile_x509;
707             mbedtls_x509_crt *store = hctx->conf.ssl_ca_file;
708             if (!mod_mbedtls_construct_crt_chain(ssl_cred, store, r->conf.errh))
709                 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
710         }
711         /* reconfigure to use SNI-specific cert */
712         int rc =
713           mbedtls_ssl_set_hs_own_cert(ssl,
714                                       &hctx->conf.pc->ssl_pemfile_x509,
715                                       &hctx->conf.pc->ssl_pemfile_pkey);
716         if (0 != rc) {
717             elogf(r->conf.errh, __FILE__, __LINE__, rc,
718                   "failed to set SNI certificate for TLS server name %s",
719                   r->uri.authority.ptr);
720             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
721         }
722     }
723 
724     return 0;
725 }
726 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
727 
728 
729 static int
730 mod_mbedtls_conf_verify (handler_ctx *hctx, mbedtls_ssl_config *ssl_ctx)
731 {
732     if (NULL == hctx->conf.ssl_ca_file) {
733         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
734           "MTLS: can't verify client without ssl.ca-file "
735           "for TLS server name %s",
736           hctx->r->uri.authority.ptr);
737         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
738     }
739 
740     /* send ssl_ca_dn_file (if set) in client certificate request
741      * (later changed to ssl_ca_file before client certificate verification) */
742     mbedtls_x509_crt *ca_certs = hctx->conf.ssl_ca_dn_file
743                                ? hctx->conf.ssl_ca_dn_file
744                                : hctx->conf.ssl_ca_file;
745 
746     mbedtls_ssl_context * const ssl = &hctx->ssl;
747     mbedtls_ssl_set_hs_ca_chain(ssl, ca_certs, hctx->conf.ssl_ca_crl_file);
748   #if MBEDTLS_VERSION_NUMBER >= 0x02120000 /* mbedtls 2.18.0 */
749     UNUSED(ssl_ctx);
750     mbedtls_ssl_set_verify(ssl, mod_mbedtls_verify_cb, hctx);
751   #else
752     mbedtls_ssl_conf_verify(ssl_ctx, mod_mbedtls_verify_cb, hctx);
753   #endif
754     return 0;
755 }
756 
757 
758 /* mbedTLS interfaces are generally excellent.  mbedTLS convenience interfaces
759  * to read CRLs, X509 certs, and private keys are uniformly paranoid about
760  * clearing memory.  At the moment, stdio routines fopen(), fread(), fclose()
761  * are used for portability, but without setvbuf(stream, NULL, _IOLBF, 0),
762  * again for portability, since setvbuf() is not necessarily available.  Since
763  * stdio buffers by default, use our own funcs to read files without buffering.
764  * mbedtls_pk_load_file() includes trailing '\0' in size when contents in PEM
765  * format, so do the same with the value returned from fdevent_load_file().
766  */
767 
768 
769 static int
770 mod_mbedtls_x509_crl_parse_file (mbedtls_x509_crl *chain, const char *fn)
771 {
772     int rc = MBEDTLS_ERR_X509_FILE_IO_ERROR;
773     off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
774     char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
775     if (NULL == data) return rc;
776 
777     rc = mbedtls_x509_crl_parse(chain, (unsigned char *)data, (size_t)dlen+1);
778 
779     if (dlen) safe_memclear(data, (size_t)dlen);
780     free(data);
781 
782     return rc;
783 }
784 
785 
786 static int
787 mod_mbedtls_x509_crt_parse_file (mbedtls_x509_crt *chain, const char *fn)
788 {
789     int rc = MBEDTLS_ERR_X509_FILE_IO_ERROR;
790     off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
791     char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
792     if (NULL == data) return rc;
793 
794     rc = mbedtls_x509_crt_parse(chain, (unsigned char *)data, (size_t)dlen+1);
795 
796     if (dlen) safe_memclear(data, (size_t)dlen);
797     free(data);
798 
799     return rc;
800 }
801 
802 
803 static int
804 mod_mbedtls_pk_parse_keyfile (mbedtls_pk_context *ctx, const char *fn, const char *pwd)
805 {
806     int rc = MBEDTLS_ERR_PK_FILE_IO_ERROR;
807     off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
808     char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
809     if (NULL == data) return rc;
810 
811     rc = mbedtls_pk_parse_key(ctx, (unsigned char *)data, (size_t)dlen+1,
812                               (const unsigned char *)pwd,
813                               pwd ? strlen(pwd) : 0);
814 
815     if (dlen) safe_memclear(data, (size_t)dlen);
816     free(data);
817 
818     return rc;
819 }
820 
821 
822 static void *
823 network_mbedtls_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey)
824 {
825     mbedtls_x509_crt ssl_pemfile_x509;   /* parsed public key structure */
826     mbedtls_pk_context ssl_pemfile_pkey; /* parsed private key structure */
827     int rc;
828 
829     mbedtls_x509_crt_init(&ssl_pemfile_x509); /* init cert structure */
830     rc = mod_mbedtls_x509_crt_parse_file(&ssl_pemfile_x509, pemfile->ptr);
831     if (0 != rc) {
832         elogf(srv->errh, __FILE__, __LINE__, rc,
833               "PEM file cert read failed (%s)", pemfile->ptr);
834         return NULL;
835     }
836 
837     mbedtls_pk_init(&ssl_pemfile_pkey);  /* init private key context */
838     rc = mod_mbedtls_pk_parse_keyfile(&ssl_pemfile_pkey, privkey->ptr, NULL);
839     if (0 != rc) {
840         elogf(srv->errh, __FILE__, __LINE__, rc,
841               "PEM file private key read failed %s", privkey->ptr);
842         mbedtls_x509_crt_free(&ssl_pemfile_x509);
843         return NULL;
844     }
845 
846     rc = mbedtls_pk_check_pair(&ssl_pemfile_x509.pk, &ssl_pemfile_pkey);
847     if (0 != rc) {
848         elogf(srv->errh, __FILE__, __LINE__, rc,
849               "PEM cert and private key did not verify (%s) (%s)",
850               pemfile->ptr, privkey->ptr);
851         mbedtls_pk_free(&ssl_pemfile_pkey);
852         mbedtls_x509_crt_free(&ssl_pemfile_x509);
853         return NULL;
854     }
855 
856     plugin_cert *pc = malloc(sizeof(plugin_cert));
857     force_assert(pc);
858     pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
859     pc->ssl_pemfile_x509 = ssl_pemfile_x509;
860     pc->ssl_pemfile = pemfile;
861     pc->ssl_privkey = privkey;
862     pc->need_chain = (ssl_pemfile_x509.next == NULL
863                       && !mod_mbedtls_crt_is_self_issued(&ssl_pemfile_x509));
864     mbedtls_platform_zeroize(&ssl_pemfile_pkey, sizeof(ssl_pemfile_pkey));
865     return pc;
866 }
867 
868 
869 #ifdef MBEDTLS_SSL_ALPN
870 
871 static int
872 mod_mbedtls_acme_tls_1 (handler_ctx *hctx)
873 {
874     buffer * const b = hctx->tmp_buf;
875     const buffer * const name = &hctx->r->uri.authority;
876     log_error_st * const errh = hctx->r->conf.errh;
877     mbedtls_x509_crt *ssl_pemfile_x509 = NULL;
878     mbedtls_pk_context *ssl_pemfile_pkey = NULL;
879     size_t len;
880     int rc = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
881 
882     /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
883     if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
884         return 0; /*(should not happen)*/
885     buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
886     buffer_append_slash(b);
887 
888     /* check if SNI set server name (required for acme-tls/1 protocol)
889      * and perform simple path checks for no '/'
890      * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
891     if (buffer_string_is_empty(name))   return rc;
892     if (NULL != strchr(name->ptr, '/')) return rc;
893     if (name->ptr[0] == '.')            return rc;
894   #if 0
895     if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443))
896         return rc;
897   #endif
898     buffer_append_string_buffer(b, name);
899     len = buffer_string_length(b);
900 
901     do {
902         buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
903         ssl_pemfile_x509 = malloc(sizeof(*ssl_pemfile_x509));
904         force_assert(ssl_pemfile_x509);
905         mbedtls_x509_crt_init(ssl_pemfile_x509); /* init cert structure */
906         rc = mod_mbedtls_x509_crt_parse_file(ssl_pemfile_x509, b->ptr);
907         if (0 != rc) {
908             elogf(errh, __FILE__, __LINE__, rc,
909                   "Failed to load acme-tls/1 pemfile: %s", b->ptr);
910             break;
911         }
912 
913         buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
914         buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
915         ssl_pemfile_pkey = malloc(sizeof(*ssl_pemfile_pkey));
916         force_assert(ssl_pemfile_pkey);
917         mbedtls_pk_init(ssl_pemfile_pkey);  /* init private key context */
918         rc = mod_mbedtls_pk_parse_keyfile(ssl_pemfile_pkey, b->ptr, NULL);
919         if (0 != rc) {
920             elogf(errh, __FILE__, __LINE__, rc,
921                   "Failed to load acme-tls/1 pemfile: %s", b->ptr);
922             break;
923         }
924 
925         rc = mbedtls_ssl_set_hs_own_cert(&hctx->ssl,
926                                          ssl_pemfile_x509, ssl_pemfile_pkey);
927         if (0 != rc) {
928             elogf(errh, __FILE__, __LINE__, rc,
929                   "failed to set acme-tls/1 certificate for TLS server "
930                   "name %s", name->ptr);
931             break;
932         }
933 
934         hctx->acme_tls_1_pkey = ssl_pemfile_pkey; /* save ptr and free later */
935         hctx->acme_tls_1_x509 = ssl_pemfile_x509; /* save ptr and free later */
936         return 0;
937 
938     } while (0);
939 
940     if (ssl_pemfile_pkey) {
941         mbedtls_pk_free(ssl_pemfile_pkey);
942         free(ssl_pemfile_pkey);
943     }
944     if (ssl_pemfile_x509) {
945         mbedtls_x509_crt_free(ssl_pemfile_x509);
946         free(ssl_pemfile_x509);
947     }
948 
949     return rc;
950 }
951 
952 
953 enum {
954   MOD_MBEDTLS_ALPN_HTTP11      = 1
955  ,MOD_MBEDTLS_ALPN_HTTP10      = 2
956  ,MOD_MBEDTLS_ALPN_H2          = 3
957  ,MOD_MBEDTLS_ALPN_ACME_TLS_1  = 4
958 };
959 
960 
961 static int
962 mod_mbedtls_alpn_select_cb (handler_ctx *hctx, const char *in)
963 {
964     const int n = (int)strlen(in);
965     const int i = 0;
966     unsigned short proto;
967 
968     switch (n) {
969       case 2:  /* "h2" */
970         if (in[i] == 'h' && in[i+1] == '2') {
971             proto = MOD_MBEDTLS_ALPN_H2;
972             hctx->r->http_version = HTTP_VERSION_2;
973             break;
974         }
975         return 0;
976       case 8:  /* "http/1.1" "http/1.0" */
977         if (0 == memcmp(in+i, "http/1.", 7)) {
978             if (in[i+7] == '1') {
979                 proto = MOD_MBEDTLS_ALPN_HTTP11;
980                 break;
981             }
982             if (in[i+7] == '0') {
983                 proto = MOD_MBEDTLS_ALPN_HTTP10;
984                 break;
985             }
986         }
987         return 0;
988       case 10: /* "acme-tls/1" */
989         if (0 == memcmp(in+i, "acme-tls/1", 10)) {
990             int rc = mod_mbedtls_acme_tls_1(hctx);
991             if (0 == rc) {
992                 proto = MOD_MBEDTLS_ALPN_ACME_TLS_1;
993                 break;
994             }
995             return rc;
996         }
997         return 0;
998       default:
999         return 0;
1000     }
1001 
1002     hctx->alpn = proto;
1003     return 0;
1004 }
1005 
1006 #endif /* MBEDTLS_SSL_ALPN */
1007 
1008 
1009 static int
1010 mod_mbedtls_ssl_conf_ciphersuites (server *srv, plugin_config_socket *s, buffer *ciphersuites, const buffer *cipherstring);
1011 
1012 
1013 static int
1014 mod_mbedtls_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *curvelist);
1015 
1016 
1017 static void
1018 mod_mbedtls_ssl_conf_proto (server *srv, plugin_config_socket *s, const buffer *b, int max);
1019 
1020 
1021 static int
1022 mod_mbedtls_ssl_conf_cmd (server *srv, plugin_config_socket *s)
1023 {
1024     /* reference:
1025      * https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html */
1026     int rc = 0;
1027     buffer *cipherstring = NULL;
1028     buffer *ciphersuites = NULL;
1029 
1030     for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
1031         data_string *ds = (data_string *)s->ssl_conf_cmd->data[i];
1032         if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString")))
1033             cipherstring = &ds->value;
1034         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites")))
1035             ciphersuites = &ds->value;
1036         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves"))
1037               || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups"))) {
1038             if (!mod_mbedtls_ssl_conf_curves(srv, s, &ds->value))
1039                 rc = -1;
1040         }
1041         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol")))
1042             mod_mbedtls_ssl_conf_proto(srv, s, &ds->value, 1); /* max */
1043         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol")))
1044             mod_mbedtls_ssl_conf_proto(srv, s, &ds->value, 0); /* min */
1045         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) {
1046             /* openssl config for Protocol=... is complex and deprecated */
1047             log_error(srv->errh, __FILE__, __LINE__,
1048                       "MTLS: ssl.openssl.ssl-conf-cmd %s ignored; "
1049                       "use MinProtocol=... and MaxProtocol=... instead",
1050                       ds->key.ptr);
1051         }
1052         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) {
1053             for (char *v = ds->value.ptr, *e; *v; v = e) {
1054                 while (*v == ' ' || *v == '\t' || *v == ',') ++v;
1055                 int flag = 1;
1056                 if (*v == '-') {
1057                     flag = 0;
1058                     ++v;
1059                 }
1060                 for (e = v; light_isalpha(*e); ++e) ;
1061                 switch ((int)(e-v)) {
1062                   case 11:
1063                     if (buffer_eq_icase_ssn(v, "Compression", 11)) {
1064                         /* mbedtls defaults to no record compression unless
1065                          * mbedtls is built with MBEDTLS_ZLIB_SUPPORT, which
1066                          * is deprecated and slated for removal*/
1067                         if (!flag) continue;
1068                     }
1069                     break;
1070                   case 13:
1071                     if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) {
1072                         s->ssl_session_ticket = flag;
1073                         continue;
1074                     }
1075                     break;
1076                   case 16:
1077                     if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) {
1078                         /* Note: The server uses its own preferences
1079                          * over the preference of the client unless
1080                          * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE defined! */
1081                         s->ssl_honor_cipher_order = flag;
1082                         continue;
1083                     }
1084                     break;
1085                   default:
1086                     break;
1087                 }
1088                 /* warn if not explicitly handled or ignored above */
1089                 if (!flag) --v;
1090                 log_error(srv->errh, __FILE__, __LINE__,
1091                           "MTLS: ssl.openssl.ssl-conf-cmd Options %.*s ignored",
1092                           (int)(e-v), v);
1093             }
1094         }
1095       #if 0
1096         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) {
1097         }
1098       #endif
1099         else {
1100             /* warn if not explicitly handled or ignored above */
1101             log_error(srv->errh, __FILE__, __LINE__,
1102                       "MTLS: ssl.openssl.ssl-conf-cmd %s ignored",
1103                       ds->key.ptr);
1104         }
1105     }
1106 
1107     if (!mod_mbedtls_ssl_conf_ciphersuites(srv, s, ciphersuites, cipherstring))
1108         rc = -1;
1109 
1110     return rc;
1111 }
1112 
1113 
1114 static int
1115 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p)
1116 {
1117     int rc;
1118 
1119     s->ssl_ctx = malloc(sizeof(mbedtls_ssl_config));
1120     force_assert(s->ssl_ctx);
1121     mbedtls_ssl_config_init(s->ssl_ctx);
1122 
1123     /* set the RNG in the ssl config context, using the default random func */
1124     mbedtls_ssl_conf_rng(s->ssl_ctx, mbedtls_ctr_drbg_random, &p->ctr_drbg);
1125 
1126     /* mbedtls defaults to disable client renegotiation
1127      * mbedtls defaults to no record compression unless mbedtls is built
1128      *   with MBEDTLS_ZLIB_SUPPORT, which is deprecated and slated for removal
1129      * MBEDTLS_SSL_PRESET_SUITEB is stricter than MBEDTLS_SSL_PRESET_DEFAULT
1130      * (and is attempted to be supported in mod_mbedtls_ssl_conf_ciphersuites())
1131      * explanation: https://github.com/ARMmbed/mbedtls/issues/1591
1132      * reference: RFC 6460 */
1133     rc = mbedtls_ssl_config_defaults(s->ssl_ctx,
1134                                      MBEDTLS_SSL_IS_SERVER,
1135                                      MBEDTLS_SSL_TRANSPORT_STREAM,
1136                                      MBEDTLS_SSL_PRESET_DEFAULT);
1137     if (0 != rc) {
1138         elog(srv->errh, __FILE__,__LINE__, rc,
1139              "Init of ssl config context defaults failed");
1140         return -1;
1141     }
1142 
1143     /* mbedtls defaults minimum accepted SSL/TLS protocol version TLS v1.0
1144      * use of SSL v3 should be avoided, and SSL v2 is not supported */
1145     if (s->ssl_use_sslv3)
1146         mbedtls_ssl_conf_min_version(s->ssl_ctx, MBEDTLS_SSL_MAJOR_VERSION_3,
1147                                                  MBEDTLS_SSL_MINOR_VERSION_0);
1148 
1149     if (!buffer_string_is_empty(s->ssl_cipher_list)) {
1150         if (!mod_mbedtls_ssl_conf_ciphersuites(srv,s,NULL,s->ssl_cipher_list))
1151             return -1;
1152     }
1153 
1154     if (!buffer_string_is_empty(s->ssl_dh_file)) {
1155         mbedtls_dhm_context dhm;
1156         mbedtls_dhm_init(&dhm);
1157         rc = mbedtls_dhm_parse_dhmfile(&dhm, s->ssl_dh_file->ptr);
1158         if (0 != rc)
1159             elogf(srv->errh, __FILE__,__LINE__, rc,
1160                  "mbedtls_dhm_parse_dhmfile() %s", s->ssl_dh_file->ptr);
1161         else {
1162             rc = mbedtls_ssl_conf_dh_param_ctx(s->ssl_ctx, &dhm);
1163             if (0 != rc)
1164                 elogf(srv->errh, __FILE__,__LINE__, rc,
1165                      "mbedtls_ssl_conf_dh_param_ctx() %s", s->ssl_dh_file->ptr);
1166         }
1167         mbedtls_dhm_free(&dhm);
1168         if (0 != rc)
1169             return -1;
1170     }
1171 
1172     if (!buffer_string_is_empty(s->ssl_ec_curve)) {
1173         if (!mod_mbedtls_ssl_conf_curves(srv, s, s->ssl_ec_curve))
1174             return -1;
1175     }
1176 
1177     /* if needed, attempt to construct certificate chain for server cert */
1178     if (s->pc->need_chain) {
1179         s->pc->need_chain = 0; /*(attempt once to complete chain)*/
1180         if (!mod_mbedtls_construct_crt_chain(s->ssl_pemfile_x509,
1181                                              s->ssl_ca_file, srv->errh))
1182             return -1;
1183     }
1184 
1185     rc = mbedtls_ssl_conf_own_cert(s->ssl_ctx,
1186                                    s->ssl_pemfile_x509, s->ssl_pemfile_pkey);
1187     if (0 != rc) {
1188         elogf(srv->errh, __FILE__, __LINE__, rc,
1189               "PEM cert and private key did not verify (%s) (%s)",
1190               s->ssl_pemfile->ptr, s->ssl_privkey->ptr);
1191         return -1;
1192     }
1193 
1194   #ifdef MBEDTLS_SSL_ALPN
1195     /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
1196     static const char *alpn_protos_http_acme[] = {
1197       "h2"
1198      ,"http/1.1"
1199      ,"http/1.0"
1200      ,"acme-tls/1"
1201      ,NULL
1202     };
1203     static const char *alpn_protos_http[] = {
1204       "h2"
1205      ,"http/1.1"
1206      ,"http/1.0"
1207      ,NULL
1208     };
1209     const char **alpn_protos = (!buffer_string_is_empty(s->ssl_acme_tls_1))
1210       ? alpn_protos_http_acme
1211       : alpn_protos_http;
1212     if (!srv->srvconf.h2proto) ++alpn_protos;
1213     rc = mbedtls_ssl_conf_alpn_protocols(s->ssl_ctx, alpn_protos);
1214     if (0 != rc) {
1215         elog(srv->errh, __FILE__, __LINE__, rc, "error setting ALPN protocols");
1216         return -1;
1217     }
1218   #endif
1219 
1220     if (!s->ssl_use_sslv3 && !s->ssl_use_sslv2)
1221         mod_mbedtls_ssl_conf_proto(srv, s, NULL, 0); /* min */
1222 
1223     if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) {
1224         if (0 != mod_mbedtls_ssl_conf_cmd(srv, s)) return -1;
1225     }
1226 
1227     /* server preference is used (default) unless mbedtls is built with
1228      * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE defined (not default) */
1229   #ifndef MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE
1230     if (!s->ssl_honor_cipher_order)
1231         log_error(srv->errh, __FILE__, __LINE__,
1232           "MTLS: "
1233           "ignoring ssl.honor-cipher-order; mbedtls uses server preference "
1234           "unless mbedtls built MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE");
1235   #else
1236     if (s->ssl_honor_cipher_order)
1237         log_error(srv->errh, __FILE__, __LINE__,
1238           "MTLS: "
1239           "ignoring ssl.honor-cipher-order; mbedtls uses client preference "
1240           "since mbedtls built MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE");
1241   #endif
1242 
1243   #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1244     if (s->ssl_session_ticket && !p->ticket_ctx.ticket_lifetime) { /*init once*/
1245         rc = mbedtls_ssl_ticket_setup(&p->ticket_ctx, mbedtls_ctr_drbg_random,
1246                                       &p->ctr_drbg, MBEDTLS_CIPHER_AES_256_GCM,
1247                                       43200); /* ticket timeout: 12 hours */
1248         if (0 != rc) {
1249             elog(srv->errh, __FILE__,__LINE__, rc,
1250                  "mbedtls_ssl_ticket_setup()");
1251             return -1;
1252         }
1253     }
1254 
1255    #if defined(MBEDTLS_SSL_TICKET_C)
1256     if (s->ssl_session_ticket)
1257         mbedtls_ssl_conf_session_tickets_cb(s->ssl_ctx,
1258                                             mbedtls_ssl_ticket_write,
1259                                             mbedtls_ssl_ticket_parse,
1260                                             &p->ticket_ctx);
1261    #endif
1262   #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1263 
1264     return 0;
1265 }
1266 
1267 
1268 static int
1269 mod_mbedtls_set_defaults_sockets(server *srv, plugin_data *p)
1270 {
1271     static const config_plugin_keys_t cpk[] = {
1272       { CONST_STR_LEN("ssl.engine"),
1273         T_CONFIG_BOOL,
1274         T_CONFIG_SCOPE_CONNECTION }
1275      ,{ CONST_STR_LEN("ssl.cipher-list"),
1276         T_CONFIG_STRING,
1277         T_CONFIG_SCOPE_CONNECTION }
1278      ,{ CONST_STR_LEN("ssl.honor-cipher-order"),
1279         T_CONFIG_BOOL,
1280         T_CONFIG_SCOPE_CONNECTION }
1281      ,{ CONST_STR_LEN("ssl.dh-file"),
1282         T_CONFIG_STRING,
1283         T_CONFIG_SCOPE_CONNECTION }
1284      ,{ CONST_STR_LEN("ssl.ec-curve"),
1285         T_CONFIG_STRING,
1286         T_CONFIG_SCOPE_CONNECTION }
1287      ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"),
1288         T_CONFIG_ARRAY_KVSTRING,
1289         T_CONFIG_SCOPE_CONNECTION }
1290      ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */
1291         T_CONFIG_STRING,
1292         T_CONFIG_SCOPE_CONNECTION }
1293      ,{ CONST_STR_LEN("ssl.empty-fragments"),
1294         T_CONFIG_BOOL,
1295         T_CONFIG_SCOPE_CONNECTION }
1296      ,{ CONST_STR_LEN("ssl.use-sslv2"),
1297         T_CONFIG_BOOL,
1298         T_CONFIG_SCOPE_CONNECTION }
1299      ,{ CONST_STR_LEN("ssl.use-sslv3"),
1300         T_CONFIG_BOOL,
1301         T_CONFIG_SCOPE_CONNECTION }
1302      ,{ CONST_STR_LEN("ssl.stek-file"),
1303         T_CONFIG_STRING,
1304         T_CONFIG_SCOPE_SERVER }
1305      ,{ NULL, 0,
1306         T_CONFIG_UNSET,
1307         T_CONFIG_SCOPE_UNSET }
1308     };
1309     static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 };
1310 
1311     p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx));
1312     force_assert(p->ssl_ctxs);
1313 
1314     int rc = HANDLER_GO_ON;
1315     plugin_data_base srvplug;
1316     memset(&srvplug, 0, sizeof(srvplug));
1317     plugin_data_base * const ps = &srvplug;
1318     if (!config_plugin_values_init(srv, ps, cpk, "mod_mbedtls"))
1319         return HANDLER_ERROR;
1320 
1321     plugin_config_socket defaults;
1322     memset(&defaults, 0, sizeof(defaults));
1323   #ifndef MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE
1324     defaults.ssl_honor_cipher_order = 1;
1325   #endif
1326     defaults.ssl_session_ticket     = 1; /* enabled by default */
1327     defaults.ssl_cipher_list = &default_ssl_cipher_list;
1328 
1329     /* process and validate config directives for global and $SERVER["socket"]
1330      * (init i to 0 if global context; to 1 to skip empty global context) */
1331     for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) {
1332         config_cond_info cfginfo;
1333         config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id);
1334         int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET);
1335         int count_not_engine = 0;
1336 
1337         plugin_config_socket conf;
1338         memcpy(&conf, &defaults, sizeof(conf));
1339 
1340         /*(preserve prior behavior; not inherited)*/
1341         /*(forcing inheritance might break existing configs where SSL is enabled
1342          * by default in the global scope, but not $SERVER["socket"]=="*:80") */
1343         conf.ssl_enabled = 0;
1344 
1345         config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0];
1346         for (; -1 != cpv->k_id; ++cpv) {
1347             /* ignore ssl.pemfile (k_id=10); included to process global scope */
1348             if (!is_socket_scope && cpv->k_id != 10) {
1349                 log_error(srv->errh, __FILE__, __LINE__,
1350                   "MTLS: %s is valid only in global scope or "
1351                   "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k);
1352                 continue;
1353             }
1354             ++count_not_engine;
1355             switch (cpv->k_id) {
1356               case 0: /* ssl.engine */
1357                 conf.ssl_enabled = (0 != cpv->v.u);
1358                 --count_not_engine;
1359                 break;
1360               case 1: /* ssl.cipher-list */
1361                 conf.ssl_cipher_list = cpv->v.b;
1362                 break;
1363               case 2: /* ssl.honor-cipher-order */
1364                 conf.ssl_honor_cipher_order = (0 != cpv->v.u);
1365                 break;
1366               case 3: /* ssl.dh-file */
1367                 conf.ssl_dh_file = cpv->v.b;
1368                 break;
1369               case 4: /* ssl.ec-curve */
1370                 conf.ssl_ec_curve = cpv->v.b;
1371                 break;
1372               case 5: /* ssl.openssl.ssl-conf-cmd */
1373                 *(const array **)&conf.ssl_conf_cmd = cpv->v.a;
1374                 break;
1375               case 6: /* ssl.pemfile */
1376                 /* ignore here; included to process global scope when
1377                  * ssl.pemfile is set, but ssl.engine is not "enable" */
1378                 break;
1379               case 7: /* ssl.empty-fragments */
1380                 conf.ssl_empty_fragments = (0 != cpv->v.u);
1381                 log_error(srv->errh, __FILE__, __LINE__,
1382                   "MTLS: ignoring ssl.empty-fragments; openssl-specific "
1383                   "counter-measure against a SSL 3.0/TLS 1.0 protocol "
1384                   "vulnerability affecting CBC ciphers, which cannot be handled"
1385                   " by some broken (Microsoft) SSL implementations.");
1386                 break;
1387               case 8: /* ssl.use-sslv2 */
1388                 conf.ssl_use_sslv2 = (0 != cpv->v.u);
1389                 log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
1390                   "ssl.use-sslv2 is deprecated and will soon be removed.  "
1391                   "Many modern TLS libraries no longer support SSLv2.");
1392                 break;
1393               case 9: /* ssl.use-sslv3 */
1394                 conf.ssl_use_sslv3 = (0 != cpv->v.u);
1395                 log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
1396                   "ssl.use-sslv3 is deprecated and will soon be removed.  "
1397                   "Many modern TLS libraries no longer support SSLv3.  "
1398                   "If needed, use: "
1399                   "ssl.openssl.ssl-conf-cmd = (\"MinProtocol\" => \"SSLv3\")");
1400                 break;
1401               case 10:/* ssl.stek-file */
1402                #ifdef MBEDTLS_SSL_SESSION_TICKETS
1403                 if (!buffer_is_empty(cpv->v.b))
1404                     p->ssl_stek_file = cpv->v.b->ptr;
1405                #else
1406                 log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
1407                   "ssl.stek-file ignored; mbedtls library not built with "
1408                   "support for SSL session tickets");
1409                #endif
1410                 break;
1411               default:/* should not happen */
1412                 break;
1413             }
1414         }
1415         if (HANDLER_GO_ON != rc) break;
1416         if (0 == i) memcpy(&defaults, &conf, sizeof(conf));
1417 
1418         if (0 != i && !conf.ssl_enabled) continue;
1419 
1420         /* fill plugin_config_socket with global context then $SERVER["socket"]
1421          * only for directives directly in current $SERVER["socket"] condition*/
1422 
1423         /*conf.ssl_pemfile_pkey       = p->defaults.ssl_pemfile_pkey;*/
1424         /*conf.ssl_pemfile_x509       = p->defaults.ssl_pemfile_x509;*/
1425         conf.ssl_verifyclient         = p->defaults.ssl_verifyclient;
1426         conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce;
1427         conf.ssl_verifyclient_depth   = p->defaults.ssl_verifyclient_depth;
1428         conf.ssl_acme_tls_1           = p->defaults.ssl_acme_tls_1;
1429 
1430         int sidx = ps->cvlist[i].k_id;
1431         for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) {
1432             if (p->cvlist[j].k_id != sidx) continue;
1433             /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/
1434             cpv = p->cvlist + p->cvlist[j].v.u2[0];
1435             for (; -1 != cpv->k_id; ++cpv) {
1436                 ++count_not_engine;
1437                 switch (cpv->k_id) {
1438                   case 0: /* ssl.pemfile */
1439                     if (cpv->vtype == T_CONFIG_LOCAL) {
1440                         plugin_cert *pc = cpv->v.v;
1441                         conf.pc               = pc;
1442                         conf.ssl_pemfile_pkey = &pc->ssl_pemfile_pkey;
1443                         conf.ssl_pemfile_x509 = &pc->ssl_pemfile_x509;
1444                         conf.ssl_pemfile      = pc->ssl_pemfile;
1445                         conf.ssl_privkey      = pc->ssl_privkey;
1446                     }
1447                     break;
1448                   case 2: /* ssl.ca-file */
1449                     if (cpv->vtype == T_CONFIG_LOCAL)
1450                         conf.ssl_ca_file = cpv->v.v;
1451                     break;
1452                   case 7: /* ssl.verifyclient.activate */
1453                     conf.ssl_verifyclient = (0 != cpv->v.u);
1454                     break;
1455                   case 8: /* ssl.verifyclient.enforce */
1456                     conf.ssl_verifyclient_enforce = (0 != cpv->v.u);
1457                     break;
1458                   case 9: /* ssl.verifyclient.depth */
1459                     conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
1460                     break;
1461                   case 13:/* ssl.acme-tls-1 */
1462                     conf.ssl_acme_tls_1 = cpv->v.b;
1463                     break;
1464                   default:
1465                     break;
1466                 }
1467             }
1468             break;
1469         }
1470 
1471         if (NULL == conf.ssl_pemfile_x509) {
1472             if (0 == i && !conf.ssl_enabled) continue;
1473             if (0 != i) {
1474                 /* inherit ssl settings from global scope
1475                  * (if only ssl.engine = "enable" and no other ssl.* settings)
1476                  * (This is for convenience when defining both IPv4 and IPv6
1477                  *  and desiring to inherit the ssl config from global context
1478                  *  without having to duplicate the directives)*/
1479                 if (count_not_engine
1480                     || (conf.ssl_enabled && NULL == p->ssl_ctxs[0].ssl_ctx)) {
1481                     log_error(srv->errh, __FILE__, __LINE__,
1482                       "MTLS: ssl.pemfile has to be set in same "
1483                       "$SERVER[\"socket\"] scope as other ssl.* directives, "
1484                       "unless only ssl.engine is set, inheriting ssl.* from "
1485                       "global scope");
1486                     rc = HANDLER_ERROR;
1487                     continue;
1488                 }
1489                 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
1490                 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/
1491                 continue;
1492             }
1493             /* PEM file is required */
1494             log_error(srv->errh, __FILE__, __LINE__,
1495               "MTLS: ssl.pemfile has to be set when ssl.engine = \"enable\"");
1496             rc = HANDLER_ERROR;
1497             continue;
1498         }
1499 
1500         /* (initialize once if module enabled) */
1501         if (!mod_mbedtls_init_once_mbedtls(srv)) {
1502             rc = HANDLER_ERROR;
1503             break;
1504         }
1505 
1506         /* configure ssl_ctx for socket */
1507 
1508         /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/
1509         if (0 == network_init_ssl(srv, &conf, p)) {
1510             plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
1511             s->ssl_ctx            = conf.ssl_ctx;
1512             s->ciphersuites       = conf.ciphersuites;
1513             s->curves             = conf.curves;
1514         }
1515         else {
1516             mbedtls_ssl_config_free(conf.ssl_ctx);
1517             free(conf.ciphersuites);
1518             free(conf.curves);
1519             rc = HANDLER_ERROR;
1520         }
1521     }
1522 
1523   #ifdef MBEDTLS_SSL_SESSION_TICKETS
1524     if (rc == HANDLER_GO_ON && ssl_is_init)
1525         mod_mbedtls_session_ticket_key_check(p, log_epoch_secs);
1526   #endif
1527 
1528     free(srvplug.cvlist);
1529     return rc;
1530 }
1531 
1532 
1533 SETDEFAULTS_FUNC(mod_mbedtls_set_defaults)
1534 {
1535     static const config_plugin_keys_t cpk[] = {
1536       { CONST_STR_LEN("ssl.pemfile"),
1537         T_CONFIG_STRING,
1538         T_CONFIG_SCOPE_CONNECTION }
1539      ,{ CONST_STR_LEN("ssl.privkey"),
1540         T_CONFIG_STRING,
1541         T_CONFIG_SCOPE_CONNECTION }
1542      ,{ CONST_STR_LEN("ssl.ca-file"),
1543         T_CONFIG_STRING,
1544         T_CONFIG_SCOPE_CONNECTION }
1545      ,{ CONST_STR_LEN("ssl.ca-dn-file"),
1546         T_CONFIG_STRING,
1547         T_CONFIG_SCOPE_CONNECTION }
1548      ,{ CONST_STR_LEN("ssl.ca-crl-file"),
1549         T_CONFIG_STRING,
1550         T_CONFIG_SCOPE_CONNECTION }
1551      ,{ CONST_STR_LEN("ssl.read-ahead"),
1552         T_CONFIG_BOOL,
1553         T_CONFIG_SCOPE_CONNECTION }
1554      ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"),
1555         T_CONFIG_BOOL,
1556         T_CONFIG_SCOPE_CONNECTION }
1557      ,{ CONST_STR_LEN("ssl.verifyclient.activate"),
1558         T_CONFIG_BOOL,
1559         T_CONFIG_SCOPE_CONNECTION }
1560      ,{ CONST_STR_LEN("ssl.verifyclient.enforce"),
1561         T_CONFIG_BOOL,
1562         T_CONFIG_SCOPE_CONNECTION }
1563      ,{ CONST_STR_LEN("ssl.verifyclient.depth"),
1564         T_CONFIG_SHORT,
1565         T_CONFIG_SCOPE_CONNECTION }
1566      ,{ CONST_STR_LEN("ssl.verifyclient.username"),
1567         T_CONFIG_STRING,
1568         T_CONFIG_SCOPE_CONNECTION }
1569      ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"),
1570         T_CONFIG_BOOL,
1571         T_CONFIG_SCOPE_CONNECTION }
1572      ,{ CONST_STR_LEN("ssl.acme-tls-1"),
1573         T_CONFIG_STRING,
1574         T_CONFIG_SCOPE_CONNECTION }
1575      ,{ CONST_STR_LEN("debug.log-ssl-noise"),
1576         T_CONFIG_SHORT,
1577         T_CONFIG_SCOPE_CONNECTION }
1578      ,{ NULL, 0,
1579         T_CONFIG_UNSET,
1580         T_CONFIG_SCOPE_UNSET }
1581     };
1582 
1583     plugin_data * const p = p_d;
1584     p->srv = srv;
1585     if (!config_plugin_values_init(srv, p, cpk, "mod_mbedtls"))
1586         return HANDLER_ERROR;
1587 
1588     /* process and validate config directives
1589      * (init i to 0 if global context; to 1 to skip empty global context) */
1590     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
1591         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1592         config_plugin_value_t *pemfile = NULL;
1593         config_plugin_value_t *privkey = NULL;
1594         for (; -1 != cpv->k_id; ++cpv) {
1595             switch (cpv->k_id) {
1596               case 0: /* ssl.pemfile */
1597                 if (!buffer_string_is_empty(cpv->v.b)) pemfile = cpv;
1598                 break;
1599               case 1: /* ssl.privkey */
1600                 if (!buffer_string_is_empty(cpv->v.b)) privkey = cpv;
1601                 break;
1602               case 2: /* ssl.ca-file */
1603               case 3: /* ssl.ca-dn-file */
1604                #if 0 /* defer; not necessary for pemfile parsing */
1605                 if (!mod_mbedtls_init_once_mbedtls(srv)) return HANDLER_ERROR;
1606                #endif
1607                 if (!buffer_string_is_empty(cpv->v.b)) {
1608                     mbedtls_x509_crt *cacert = calloc(1, sizeof(*cacert));
1609                     force_assert(cacert);
1610                     mbedtls_x509_crt_init(cacert);
1611                     int rc =
1612                       mod_mbedtls_x509_crt_parse_file(cacert, cpv->v.b->ptr);
1613                     if (0 == rc) {
1614                         cpv->vtype = T_CONFIG_LOCAL;
1615                         cpv->v.v = cacert;
1616                     }
1617                     else {
1618                         elogf(srv->errh, __FILE__, __LINE__, rc,
1619                               "%s = %s", cpk[cpv->k_id].k, cpv->v.b->ptr);
1620                         mbedtls_x509_crt_free(cacert);
1621                         free(cacert);
1622                         return HANDLER_ERROR;
1623                     }
1624                 }
1625                 break;
1626               case 4: /* ssl.ca-crl-file */
1627                 if (!buffer_string_is_empty(cpv->v.b)) {
1628                     mbedtls_x509_crl *crl = malloc(sizeof(*crl));
1629                     force_assert(crl);
1630                     mbedtls_x509_crl_init(crl);
1631                     int rc =
1632                       mod_mbedtls_x509_crl_parse_file(crl, cpv->v.b->ptr);
1633                     if (0 == rc) {
1634                         cpv->vtype = T_CONFIG_LOCAL;
1635                         cpv->v.v = crl;
1636                     }
1637                     else {
1638                         elogf(srv->errh, __FILE__, __LINE__, rc,
1639                               "CRL file read failed (%s)", cpv->v.b->ptr);
1640                         free(crl);
1641                         return HANDLER_ERROR;
1642                     }
1643                 }
1644                 break;
1645               case 5: /* ssl.read-ahead */
1646               case 6: /* ssl.disable-client-renegotiation */
1647               case 7: /* ssl.verifyclient.activate */
1648               case 8: /* ssl.verifyclient.enforce */
1649                 break;
1650               case 9: /* ssl.verifyclient.depth */
1651                 if (cpv->v.shrt > 255) {
1652                     log_error(srv->errh, __FILE__, __LINE__,
1653                       "MTLS: %s is absurdly large (%hu); limiting to 255",
1654                       cpk[cpv->k_id].k, cpv->v.shrt);
1655                     cpv->v.shrt = 255;
1656                 }
1657                 break;
1658               case 10:/* ssl.verifyclient.username */
1659               case 11:/* ssl.verifyclient.exportcert */
1660               case 12:/* ssl.acme-tls-1 */
1661               case 13:/* debug.log-ssl-noise */
1662                 break;
1663               default:/* should not happen */
1664                 break;
1665             }
1666         }
1667 
1668         if (pemfile) {
1669             if (NULL == privkey) privkey = pemfile;
1670             pemfile->v.v =
1671               network_mbedtls_load_pemfile(srv, pemfile->v.b, privkey->v.b);
1672             if (pemfile->v.v)
1673                 pemfile->vtype = T_CONFIG_LOCAL;
1674             else
1675                 return HANDLER_ERROR;
1676         }
1677     }
1678 
1679     p->defaults.ssl_verifyclient = 0;
1680     p->defaults.ssl_verifyclient_enforce = 1;
1681     p->defaults.ssl_verifyclient_depth = 9;
1682     p->defaults.ssl_verifyclient_export_cert = 0;
1683     p->defaults.ssl_disable_client_renegotiation = 1;
1684     p->defaults.ssl_read_ahead = 0;
1685 
1686     /* initialize p->defaults from global config context */
1687     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
1688         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
1689         if (-1 != cpv->k_id)
1690             mod_mbedtls_merge_config(&p->defaults, cpv);
1691     }
1692 
1693   #ifndef MBEDTLS_ERROR_C
1694     log_error(srv->errh, __FILE__, __LINE__,
1695               "MTLS: No error strings available. "
1696               "Compile mbedtls with MBEDTLS_ERROR_C to enable.");
1697   #endif
1698 
1699     return mod_mbedtls_set_defaults_sockets(srv, p);
1700 }
1701 
1702 
1703     /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
1704      *
1705      * buffer is allocated once, is NOT realloced (note: not thread-safe)
1706      * */
1707 
1708             /* copy small mem chunks into single large buffer
1709              * before mbedtls_ssl_write() to reduce number times
1710              * write() called underneath mbedtls_ssl_write() and
1711              * potentially reduce number of packets generated if TCP_NODELAY */
1712 
1713 
1714 __attribute_cold__
1715 static int
1716 mod_mbedtls_ssl_write_err(connection *con, handler_ctx *hctx, int wr, size_t wr_len)
1717 {
1718     switch (wr) {
1719       case MBEDTLS_ERR_SSL_WANT_READ:
1720         con->is_readable = -1;
1721         break; /* try again later */
1722       case MBEDTLS_ERR_SSL_WANT_WRITE:
1723         con->is_writable = -1;
1724         break; /* try again later */
1725       case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
1726       case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
1727         break; /* try again later */
1728       case MBEDTLS_ERR_NET_CONN_RESET:
1729         if (hctx->conf.ssl_log_noise)
1730             elog(hctx->r->conf.errh, __FILE__, __LINE__, wr,
1731                  "peer closed connection");
1732         return -1;
1733       default:
1734         elog(hctx->r->conf.errh, __FILE__, __LINE__, wr, __func__);
1735         return -1;
1736     }
1737 
1738     if (0 != hctx->ssl.out_left)  /* partial write; save attempted wr_len */
1739         hctx->pending_write = wr_len;
1740 
1741     return 0; /* try again later */
1742 }
1743 
1744 
1745 static int
1746 mod_mbedtls_close_notify(handler_ctx *hctx);
1747 
1748 
1749 static int
1750 connection_write_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
1751 {
1752     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1753     mbedtls_ssl_context * const ssl = &hctx->ssl;
1754 
1755     if (hctx->pending_write) {
1756         int wr = (int)hctx->pending_write;
1757         if (0 != ssl->out_left) {
1758             /*(would prefer mbedtls_ssl_flush_output() from ssl_internal.h)*/
1759             size_t data_len = hctx->pending_write;
1760             wr = mbedtls_ssl_write(ssl, NULL, data_len);
1761             if (wr <= 0)
1762                 return mod_mbedtls_ssl_write_err(con, hctx, wr, data_len);
1763             max_bytes -= wr;
1764         }
1765         hctx->pending_write = 0;
1766         chunkqueue_mark_written(cq, wr);
1767     }
1768 
1769     if (0 != hctx->close_notify) return mod_mbedtls_close_notify(hctx);
1770 
1771     chunkqueue_remove_finished_chunks(cq);
1772 
1773     const int lim = mbedtls_ssl_get_max_out_record_payload(ssl);
1774     if (lim < 0) return mod_mbedtls_ssl_write_err(con, hctx, lim, 0);
1775 
1776     log_error_st * const errh = hctx->errh;
1777     while (max_bytes > 0 && !chunkqueue_is_empty(cq)) {
1778         char *data = local_send_buffer;
1779         uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes
1780           ? LOCAL_SEND_BUFSIZE
1781           : (uint32_t)max_bytes;
1782         int wr;
1783 
1784         if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1;
1785 
1786         /* mbedtls_ssl_write() copies the data, up to max record size, but if
1787          * (temporarily) unable to write the entire record, it is documented
1788          * that the caller must call mbedtls_ssl_write() again, later, with the
1789          * same arguments.  This appears to be because mbedtls_ssl_context does
1790          * not keep track of the original size of the caller data that
1791          * mbedtls_ssl_write() attempted to write (and may have transformed to
1792          * a different size).  The func may return MBEDTLS_ERR_SSL_WANT_READ or
1793          * MBEDTLS_ERR_SSL_WANT_WRITE to indicate that the caller should wait
1794          * for the fd to be readable/writable before calling the func again,
1795          * which is why those (temporary) errors are returned instead of telling
1796          * the caller that the data was successfully copied.  When the record is
1797          * written successfully, the return value is supposed to indicate the
1798          * number of (originally submitted) bytes written, but since that value
1799          * is unknown (not saved), the caller's len parameter is reflected back,
1800          * which is why the caller must call the func again with the same args.
1801          * Additionally, to be accurate, the size must fit into a record which
1802          * is why we restrict ourselves to sending max out record payload each
1803          * iteration.
1804          */
1805 
1806         int wr_total = 0;
1807         do {
1808             size_t wr_len = (data_len > (size_t)lim) ? (size_t)lim : data_len;
1809             wr = mbedtls_ssl_write(ssl, (const unsigned char *)data, wr_len);
1810             if (wr <= 0) {
1811                 if (wr_total) chunkqueue_mark_written(cq, wr_total);
1812                 return mod_mbedtls_ssl_write_err(con, hctx, wr, wr_len);
1813             }
1814             wr_total += wr;
1815             data += wr;
1816         } while ((data_len -= wr));
1817         chunkqueue_mark_written(cq, wr_total);
1818         max_bytes -= wr_total;
1819     }
1820 
1821     return 0;
1822 }
1823 
1824 
1825 static int
1826 mod_mbedtls_ssl_handshake (handler_ctx *hctx)
1827 {
1828     int rc = 0;
1829 
1830     /* overwrite callback with hctx each time we enter here, before handshake
1831      * (Some callbacks are on mbedtls_ssl_config, not mbedtls_ssl_context)
1832      * (Not thread-safe if config (mbedtls_ssl_config *ssl_ctx) is shared)
1833      * (XXX: there is probably a better way to do this...) */
1834     /* (alternative: save ssl_ctx in hctx in mod_mbedtls_handle_con_accept()) */
1835     mbedtls_ssl_config *ssl_ctx;
1836     *(const mbedtls_ssl_config **)&ssl_ctx = hctx->ssl.conf;
1837   #ifdef MBEDTLS_SSL_SERVER_NAME_INDICATION
1838     mbedtls_ssl_conf_sni(ssl_ctx, mod_mbedtls_SNI, hctx);
1839   #endif
1840 
1841     if (hctx->ssl.state < MBEDTLS_SSL_SERVER_HELLO) {
1842         while (hctx->ssl.state != MBEDTLS_SSL_SERVER_HELLO
1843             && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
1844             rc = mbedtls_ssl_handshake_step(&hctx->ssl);
1845             if (0 != rc) break;
1846         }
1847         if (0 == rc && hctx->ssl.state == MBEDTLS_SSL_SERVER_HELLO) {
1848           #ifdef MBEDTLS_SSL_ALPN
1849             const char *alpn = mbedtls_ssl_get_alpn_protocol(&hctx->ssl);
1850             if (NULL != alpn)
1851                 rc = mod_mbedtls_alpn_select_cb(hctx, alpn);
1852           #endif
1853         }
1854     }
1855 
1856     /* overwrite callback with hctx each time we enter here, before handshake
1857      * (Some callbacks are on mbedtls_ssl_config, not mbedtls_ssl_context)
1858      * (Not thread-safe if config (mbedtls_ssl_config *ssl_ctx) is shared)
1859      * (XXX: there is probably a better way to do this...) */
1860     if (0 == rc && hctx->conf.ssl_verifyclient
1861         && hctx->ssl.state >= MBEDTLS_SSL_SERVER_HELLO  /*(after SNI and ALPN)*/
1862         && hctx->ssl.state <= MBEDTLS_SSL_SERVER_HELLO_DONE
1863         && hctx->alpn != MOD_MBEDTLS_ALPN_ACME_TLS_1) { /*(not "acme-tls/1")*/
1864         int mode = (hctx->conf.ssl_verifyclient_enforce)
1865           ? MBEDTLS_SSL_VERIFY_REQUIRED
1866           : MBEDTLS_SSL_VERIFY_OPTIONAL;
1867         mbedtls_ssl_set_hs_authmode(&hctx->ssl, mode);
1868         while (hctx->ssl.state != MBEDTLS_SSL_CERTIFICATE_REQUEST
1869             && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
1870             rc = mbedtls_ssl_handshake_step(&hctx->ssl);
1871             if (0 != rc) break;
1872         }
1873         if (0 == rc && hctx->ssl.state == MBEDTLS_SSL_CERTIFICATE_REQUEST) {
1874             rc = mod_mbedtls_conf_verify(hctx, ssl_ctx);
1875             if (0 == rc)
1876                 rc = mbedtls_ssl_handshake_step(&hctx->ssl);
1877             /* reconfigure CA trust chain after sending client certificate
1878              * request (if ssl_ca_dn_file is set), before client certificate
1879              * verification (MBEDTLS_SSL_CERTIFICATE_VERIFY) */
1880             if (0 == rc && hctx->conf.ssl_ca_dn_file
1881                 && hctx->ssl.state == MBEDTLS_SSL_SERVER_HELLO_DONE) {
1882                 mbedtls_ssl_context * const ssl = &hctx->ssl;
1883                 mbedtls_x509_crt *ca_certs = hctx->conf.ssl_ca_file;
1884                 mbedtls_x509_crl *ca_crl = hctx->conf.ssl_ca_crl_file;
1885                 mbedtls_ssl_set_hs_ca_chain(ssl, ca_certs, ca_crl);
1886             }
1887         }
1888     }
1889 
1890     if (0 == rc && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
1891         rc = mbedtls_ssl_handshake(&hctx->ssl);
1892     }
1893 
1894     switch (rc) {
1895       case 0:
1896         hctx->handshake_done = 1;
1897        #ifdef MBEDTLS_SSL_ALPN
1898         if (hctx->alpn == MOD_MBEDTLS_ALPN_ACME_TLS_1) {
1899             /* Once TLS handshake is complete, return -1 to result in
1900              * CON_STATE_ERROR so that socket connection is quickly closed */
1901             return -1;
1902         }
1903         hctx->alpn = 0;
1904        #endif
1905         return 1; /* continue reading */
1906       case MBEDTLS_ERR_SSL_WANT_WRITE:
1907         hctx->con->is_writable = -1;
1908         __attribute_fallthrough__
1909       case MBEDTLS_ERR_SSL_WANT_READ:
1910         hctx->con->is_readable = 0;
1911         return 0;
1912       case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
1913       case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
1914         return 0;
1915       case MBEDTLS_ERR_SSL_CLIENT_RECONNECT:
1916         return -1;
1917       case MBEDTLS_ERR_NET_CONN_RESET:
1918       case MBEDTLS_ERR_SSL_CONN_EOF:
1919         if (!hctx->conf.ssl_log_noise) return -1;
1920         __attribute_fallthrough__
1921       default:
1922         elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, __func__);
1923         return -1;
1924     }
1925 }
1926 
1927 
1928 static int
1929 connection_read_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
1930 {
1931     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1932     int len;
1933     char *mem = NULL;
1934     size_t mem_len = 0;
1935 
1936     UNUSED(max_bytes);
1937 
1938     if (0 != hctx->close_notify) return mod_mbedtls_close_notify(hctx);
1939 
1940     if (!hctx->handshake_done) {
1941         int rc = mod_mbedtls_ssl_handshake(hctx);
1942         if (1 != rc) return rc; /* !hctx->handshake_done; not done, or error */
1943     }
1944 
1945     do {
1946         len = mbedtls_ssl_get_bytes_avail(&hctx->ssl);
1947         mem_len = len < 2048 ? 2048 : (size_t)len;
1948         chunk * const ckpt = cq->last;
1949         mem = chunkqueue_get_memory(cq, &mem_len);
1950 
1951         len = mbedtls_ssl_read(&hctx->ssl, (unsigned char *)mem, mem_len);
1952         if (len > 0) {
1953             chunkqueue_use_memory(cq, ckpt, len);
1954             con->bytes_read += len;
1955         } else {
1956             chunkqueue_use_memory(cq, ckpt, 0);
1957         }
1958     } while (len > 0
1959              && mbedtls_ssl_check_pending(&hctx->ssl));
1960 
1961     if (len < 0) {
1962         int rc = len;
1963         request_st * const r = &con->request;
1964         switch (rc) {
1965           case MBEDTLS_ERR_SSL_WANT_WRITE:
1966             con->is_writable = -1;
1967             __attribute_fallthrough__
1968           case MBEDTLS_ERR_SSL_WANT_READ:
1969             con->is_readable = 0;
1970             return 0;
1971           case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1972           case MBEDTLS_ERR_SSL_CONN_EOF:
1973             /* XXX: future: save state to avoid future read after response? */
1974             con->is_readable = 0;
1975             r->keep_alive = 0;
1976             return -2;
1977           case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
1978           case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
1979             return 0;
1980           case MBEDTLS_ERR_SSL_CLIENT_RECONNECT:
1981             return -1;
1982           case MBEDTLS_ERR_NET_CONN_RESET:
1983             if (!hctx->conf.ssl_log_noise) return -1;
1984             __attribute_fallthrough__
1985           default:
1986             elog(hctx->errh, __FILE__, __LINE__, rc, "Reading mbedtls");
1987             return -1;
1988         }
1989     } else if (len == 0) {
1990         con->is_readable = 0;
1991         /* the other end closed the connection -> KEEP-ALIVE */
1992 
1993         return -2;
1994     } else {
1995         return 0;
1996     }
1997 }
1998 
1999 
2000 static void
2001 mod_mbedtls_debug_cb(void *ctx, int level,
2002                      const char *file, int line,
2003                      const char *str)
2004 {
2005     if (level < (intptr_t)ctx) /* level */
2006         log_error(plugin_data_singleton->srv->errh,file,line,"MTLS: %s",str);
2007 }
2008 
2009 
2010 CONNECTION_FUNC(mod_mbedtls_handle_con_accept)
2011 {
2012     server_socket *srv_sock = con->srv_socket;
2013     if (!srv_sock->is_ssl) return HANDLER_GO_ON;
2014 
2015     plugin_data *p = p_d;
2016     handler_ctx * const hctx = handler_ctx_init();
2017     request_st * const r = &con->request;
2018     hctx->r = r;
2019     hctx->con = con;
2020     hctx->tmp_buf = con->srv->tmp_buf;
2021     hctx->errh = r->conf.errh;
2022     con->plugin_ctx[p->id] = hctx;
2023 
2024     plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx;
2025     mbedtls_ssl_init(&hctx->ssl);
2026     int rc = mbedtls_ssl_setup(&hctx->ssl, s->ssl_ctx);
2027     if (0 == rc) {
2028         con->network_read = connection_read_cq_ssl;
2029         con->network_write = connection_write_cq_ssl;
2030         con->proto_default_port = 443; /* "https" */
2031         mod_mbedtls_patch_config(r, &hctx->conf);
2032     }
2033     else {
2034         elog(r->conf.errh, __FILE__, __LINE__, rc, "ssl_setup() failed");
2035         return HANDLER_ERROR;
2036     }
2037 
2038     mbedtls_ssl_set_bio(&hctx->ssl, (mbedtls_net_context *)&con->fd,
2039                         mbedtls_net_send, mbedtls_net_recv, NULL);
2040 
2041     /* (mbedtls_ssl_config *) is shared across multiple connections, which may
2042      * overlap, and so this debug setting is not reset upon connection close.
2043      * Once enabled, debug hook will remain so for this mbedtls_ssl_config */
2044     if (hctx->conf.ssl_log_noise)  /* volume level for debug message callback */
2045         mbedtls_ssl_conf_dbg(s->ssl_ctx, mod_mbedtls_debug_cb,
2046                              (void *)(intptr_t)hctx->conf.ssl_log_noise);
2047 
2048     /* (mbedtls_ssl_config *) is shared across multiple connections, which may
2049      * overlap, and so renegotiation setting is not reset upon connection close.
2050      * Once enabled, renegotiation will remain so for this mbedtls_ssl_config.
2051      * mbedtls defaults to disable client renegotiation
2052      *   (MBEDTLS_LEGACY_SSL_RENEGOTIATION_DISABLED)
2053      * and it is recommended to leave it disabled (lighttpd mbedtls default) */
2054   #ifdef MBEDTLS_LEGACY_SSL_RENEGOTIATION_ENABLED
2055     if (!hctx->conf.ssl_disable_client_renegotiation)
2056         mbedtls_legacy_ssl_conf_renegotiation(s->ssl_ctx,
2057                                       MBEDTLS_LEGACY_SSL_RENEGOTIATION_ENABLED);
2058   #endif
2059 
2060     return HANDLER_GO_ON;
2061 }
2062 
2063 
2064 static void
2065 mod_mbedtls_detach(handler_ctx *hctx)
2066 {
2067     /* step aside from further SSL processing
2068      * (used after handle_connection_shut_wr hook) */
2069     /* future: might restore prior network_read and network_write fn ptrs */
2070     hctx->con->is_ssl_sock = 0;
2071     /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
2072     if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
2073     hctx->close_notify = 1;
2074 }
2075 
2076 
2077 CONNECTION_FUNC(mod_mbedtls_handle_con_shut_wr)
2078 {
2079     plugin_data *p = p_d;
2080     handler_ctx *hctx = con->plugin_ctx[p->id];
2081     if (NULL == hctx) return HANDLER_GO_ON;
2082 
2083     hctx->close_notify = -2;
2084     if (hctx->handshake_done) {
2085         mod_mbedtls_close_notify(hctx);
2086     }
2087     else {
2088         mod_mbedtls_detach(hctx);
2089     }
2090 
2091     return HANDLER_GO_ON;
2092 }
2093 
2094 
2095 static int
2096 mod_mbedtls_close_notify (handler_ctx *hctx)
2097 {
2098     if (1 == hctx->close_notify) return -2;
2099 
2100     int rc = mbedtls_ssl_close_notify(&hctx->ssl);
2101     switch (rc) {
2102       case 0:
2103         mod_mbedtls_detach(hctx);
2104         return -2;
2105       case MBEDTLS_ERR_SSL_WANT_READ:
2106       case MBEDTLS_ERR_SSL_WANT_WRITE:
2107         return 0;
2108       default:
2109         elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
2110              "mbedtls_ssl_close_notify()");
2111         __attribute_fallthrough__
2112       case MBEDTLS_ERR_NET_CONN_RESET:
2113         mbedtls_ssl_session_reset(&hctx->ssl);
2114         mod_mbedtls_detach(hctx);
2115         return -1;
2116     }
2117 }
2118 
2119 
2120 CONNECTION_FUNC(mod_mbedtls_handle_con_close)
2121 {
2122     plugin_data *p = p_d;
2123     handler_ctx *hctx = con->plugin_ctx[p->id];
2124     if (NULL != hctx) {
2125         con->plugin_ctx[p->id] = NULL;
2126         if (1 != hctx->close_notify)
2127             mod_mbedtls_close_notify(hctx); /*(one final try)*/
2128         handler_ctx_free(hctx);
2129     }
2130 
2131     return HANDLER_GO_ON;
2132 }
2133 
2134 
2135 #if defined(MBEDTLS_PEM_WRITE_C)
2136 __attribute_noinline__
2137 static void
2138 https_add_ssl_client_cert (request_st * const r, const mbedtls_x509_crt * const peer)
2139 {
2140     #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
2141     #define PEM_END_CRT   "-----END CERTIFICATE-----\n"
2142     unsigned char buf[4096];
2143     size_t olen;
2144     if (0 == mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2145                                       peer->raw.p, peer->raw.len,
2146                                       buf, sizeof(buf), &olen))
2147         http_header_env_set(r,
2148                             CONST_STR_LEN("SSL_CLIENT_CERT"),
2149                             (char *)buf, olen);
2150 }
2151 #endif
2152 
2153 
2154 static void
2155 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx)
2156 {
2157     /* Note: starting with mbedtls-2.17.0, peer cert is not available here if
2158      * MBEDTLS_SSL_KEEP_PEER_CERTIFICATE *is not* defined at compile time,
2159      * though default behavior is to have it defined.  However, since earlier
2160      * versions do keep the cert, but not set this define, attempt to retrieve
2161      * the peer cert and check for NULL before using it. */
2162     const mbedtls_x509_crt *crt = mbedtls_ssl_get_peer_cert(&hctx->ssl);
2163     buffer * const tb = r->tmp_buf;
2164     char buf[512];
2165     int n;
2166 
2167     uint32_t rc = (NULL != crt)
2168       ? mbedtls_ssl_get_verify_result(&hctx->ssl)
2169       : 0xFFFFFFFF;
2170     if (0xFFFFFFFF == rc) { /*(e.g. no cert, or verify result not available)*/
2171         http_header_env_set(r,
2172                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2173                             CONST_STR_LEN("NONE"));
2174         return;
2175     }
2176     else if (0 != rc) {
2177         /* get failure string and translate newline to ':', removing last one */
2178         n = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", rc);
2179         buffer_copy_string_len(tb, CONST_STR_LEN("FAILED:"));
2180         if (n > 0) {
2181             for (char *nl = buf; NULL != (nl = strchr(nl, '\n')); ++nl)
2182                 nl[0] = ('\0' == nl[1] ? (--n, '\0') : ':');
2183             buffer_append_string_len(tb, buf, n);
2184         }
2185         http_header_env_set(r,
2186                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2187                             CONST_BUF_LEN(tb));
2188         return;
2189     }
2190     else {
2191         http_header_env_set(r,
2192                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2193                             CONST_STR_LEN("SUCCESS"));
2194     }
2195 
2196     n = mbedtls_x509_dn_gets(buf, sizeof(buf), &crt->subject);
2197     if (n > 0 && n < (int)sizeof(buf)) {
2198         http_header_env_set(r,
2199                             CONST_STR_LEN("SSL_CLIENT_S_DN"),
2200                             buf, n);
2201     }
2202 
2203     /* add components of client Subject DN */
2204     /* code block is similar to mbedtls_x509_dn_gets() */
2205     /*(reuse buf; sizeof(buf) > MBEDTLS_X509_MAX_DN_NAME_SIZE, which is 256)*/
2206     buffer_copy_string_len(tb, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
2207     const mbedtls_x509_name *name = &crt->subject;
2208     while (name != NULL) {
2209         if (!name->oid.p) {
2210             name = name->next;
2211             continue;
2212         }
2213 
2214         const char *short_name = NULL;
2215         if (0 != mbedtls_oid_get_attr_short_name(&name->oid, &short_name))
2216             continue;
2217         buffer_string_set_length(tb, sizeof("SSL_CLIENT_S_DN_")-1);
2218         buffer_append_string(tb, short_name);
2219 
2220         const mbedtls_x509_name *nm = name;
2221         n = 0;
2222         do {
2223             if (nm != name && n < (int)sizeof(buf)-1)
2224                 buf[n++] = ',';
2225             for (size_t i = 0; i < nm->val.len && n < (int)sizeof(buf)-1; ++n) {
2226                 unsigned char c = nm->val.p[i];
2227                 buf[n] = (c < 32 || c == 127 || (c > 128 && c < 160)) ? '?' : c;
2228             }
2229             buf[n] = '\0';
2230         } while (nm->next_merged && nm->next && (nm = nm->next));
2231         if (n == sizeof(buf)-1)
2232             while (nm->next_merged && nm->next) nm = nm->next;
2233         name = nm->next;
2234 
2235         http_header_env_set(r,
2236                             CONST_BUF_LEN(tb),
2237                             buf, n);
2238     }
2239 
2240     n = mbedtls_x509_serial_gets(buf, sizeof(buf), &crt->serial);
2241     if (n > 0 && n < (int)sizeof(buf)) {
2242         http_header_env_set(r,
2243                             CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
2244                             buf, n);
2245     }
2246 
2247     if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
2248         /* pick one of the exported values as "REMOTE_USER", for example
2249          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
2250          * or
2251          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
2252          */
2253         const buffer *varname = hctx->conf.ssl_verifyclient_username;
2254         const buffer *vb = http_header_env_get(r, CONST_BUF_LEN(varname));
2255         if (vb) { /* same as http_auth.c:http_auth_setenv() */
2256             http_header_env_set(r,
2257                                 CONST_STR_LEN("REMOTE_USER"),
2258                                 CONST_BUF_LEN(vb));
2259             http_header_env_set(r,
2260                                 CONST_STR_LEN("AUTH_TYPE"),
2261                                 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
2262         }
2263     }
2264 
2265   #if defined(MBEDTLS_PEM_WRITE_C)
2266     /* if (NULL != crt) (e.g. not PSK-based ciphersuite) */
2267     if (hctx->conf.ssl_verifyclient_export_cert && NULL != crt)
2268         https_add_ssl_client_cert(r, crt);
2269   #endif
2270 }
2271 
2272 
2273 static void
2274 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx)
2275 {
2276   #if 1
2277     /* XXX: reaching into ssl_internal.h here for mbedtls_ssl_transform */
2278     const mbedtls_cipher_info_t *cipher_info =
2279       hctx->ssl.transform->cipher_ctx_enc.cipher_info;
2280   #else
2281     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2282       mbedtls_ssl_ciphersuite_from_id(hctx->ssl.session->ciphersuite);
2283     const mbedtls_cipher_info_t *cipher_info =
2284       mbedtls_cipher_info_from_type(ciphersuite_info->cipher);
2285   #endif
2286     const char *s;
2287 
2288     s = mbedtls_ssl_get_version(&hctx->ssl);
2289     http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s));
2290 
2291     /*s = ciphersuite_info->name;*/ /*mbedtls_ssl_get_ciphersuite(&hctx->ssl);*/
2292     s = cipher_info->name;
2293     http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s));
2294 
2295     if (cipher_info != NULL) {
2296         /* SSL_CIPHER_ALGKEYSIZE - Number of cipher bits (possible) */
2297         /* SSL_CIPHER_USEKEYSIZE - Number of cipher bits (actually used) */
2298         /* XXX: is usekeysize correct? XXX: reaching into ssl_internal.h here */
2299         int usekeysize = hctx->ssl.transform->cipher_ctx_enc.key_bitlen;
2300         unsigned int algkeysize = cipher_info->key_bitlen;
2301         char buf[LI_ITOSTRING_LENGTH];
2302         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
2303                             buf, li_itostrn(buf, sizeof(buf), usekeysize));
2304         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
2305                             buf, li_utostrn(buf, sizeof(buf), algkeysize));
2306     }
2307 }
2308 
2309 
2310 REQUEST_FUNC(mod_mbedtls_handle_request_env)
2311 {
2312     plugin_data *p = p_d;
2313     /* simple flag for request_env_patched */
2314     if (r->plugin_ctx[p->id]) return HANDLER_GO_ON;
2315     handler_ctx *hctx = r->con->plugin_ctx[p->id];
2316     if (NULL == hctx) return HANDLER_GO_ON;
2317     r->plugin_ctx[p->id] = (void *)(uintptr_t)1u;
2318 
2319     http_cgi_ssl_env(r, hctx);
2320     if (hctx->conf.ssl_verifyclient) {
2321         https_add_ssl_client_entries(r, hctx);
2322     }
2323 
2324     return HANDLER_GO_ON;
2325 }
2326 
2327 
2328 REQUEST_FUNC(mod_mbedtls_handle_uri_raw)
2329 {
2330     /* mod_mbedtls must be loaded prior to mod_auth
2331      * if mod_mbedtls is configured to set REMOTE_USER based on client cert */
2332     /* mod_mbedtls must be loaded after mod_extforward
2333      * if mod_mbedtls config is based on lighttpd.conf remote IP conditional
2334      * using remote IP address set by mod_extforward, *unless* PROXY protocol
2335      * is enabled with extforward.hap-PROXY = "enable", in which case the
2336      * reverse is true: mod_extforward must be loaded after mod_mbedtls */
2337     plugin_data *p = p_d;
2338     handler_ctx *hctx = r->con->plugin_ctx[p->id];
2339     if (NULL == hctx) return HANDLER_GO_ON;
2340 
2341     mod_mbedtls_patch_config(r, &hctx->conf);
2342     if (hctx->conf.ssl_verifyclient) {
2343         mod_mbedtls_handle_request_env(r, p);
2344     }
2345 
2346     return HANDLER_GO_ON;
2347 }
2348 
2349 
2350 REQUEST_FUNC(mod_mbedtls_handle_request_reset)
2351 {
2352     plugin_data *p = p_d;
2353     r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */
2354     return HANDLER_GO_ON;
2355 }
2356 
2357 
2358 TRIGGER_FUNC(mod_mbedtls_handle_trigger) {
2359     plugin_data * const p = p_d;
2360     const time_t cur_ts = log_epoch_secs;
2361     if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/
2362     UNUSED(srv);
2363     UNUSED(p);
2364 
2365   #ifdef MBEDTLS_SSL_SESSION_TICKETS
2366     mod_mbedtls_session_ticket_key_check(p, cur_ts);
2367   #endif
2368 
2369     return HANDLER_GO_ON;
2370 }
2371 
2372 
2373 int mod_mbedtls_plugin_init (plugin *p);
2374 int mod_mbedtls_plugin_init (plugin *p)
2375 {
2376     p->version      = LIGHTTPD_VERSION_ID;
2377     p->name         = "mbedtls";
2378     p->init         = mod_mbedtls_init;
2379     p->cleanup      = mod_mbedtls_free;
2380     p->priv_defaults= mod_mbedtls_set_defaults;
2381 
2382     p->handle_connection_accept  = mod_mbedtls_handle_con_accept;
2383     p->handle_connection_shut_wr = mod_mbedtls_handle_con_shut_wr;
2384     p->handle_connection_close   = mod_mbedtls_handle_con_close;
2385     p->handle_uri_raw            = mod_mbedtls_handle_uri_raw;
2386     p->handle_request_env        = mod_mbedtls_handle_request_env;
2387     p->handle_request_reset      = mod_mbedtls_handle_request_reset;
2388     p->handle_trigger            = mod_mbedtls_handle_trigger;
2389 
2390     return 0;
2391 }
2392 
2393 
2394 /* cipher suites (taken from mbedtls/ssl_ciphersuites.[ch]) */
2395 
2396 static const int suite_CHACHAPOLY_ephemeral[] = {
2397     /* Chacha-Poly ephemeral suites */
2398     MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
2399     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
2400     MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
2401 };
2402 
2403 static const int suite_AES_256_ephemeral[] = {
2404     /* All AES-256 ephemeral suites */
2405     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
2406     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
2407     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
2408     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
2409     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM,
2410     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
2411     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
2412     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
2413     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
2414     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
2415     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
2416     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
2417     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8
2418 };
2419 
2420 static const int suite_CAMELLIA_256_ephemeral[] = {
2421     /* All CAMELLIA-256 ephemeral suites */
2422     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
2423     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2424     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2425     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
2426     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
2427     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2428     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
2429 };
2430 
2431 static const int suite_ARIA_256_ephemeral[] = {
2432     /* All ARIA-256 ephemeral suites */
2433     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,
2434     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
2435     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,
2436     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
2437     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
2438     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384
2439 };
2440 
2441 static const int suite_AES_128_ephemeral[] = {
2442     /* All AES-128 ephemeral suites */
2443     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
2444     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
2445     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
2446     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
2447     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM,
2448     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
2449     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
2450     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
2451     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
2452     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
2453     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
2454     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
2455     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8
2456 };
2457 
2458 static const int suite_CAMELLIA_128_ephemeral[] = {
2459     /* All CAMELLIA-128 ephemeral suites */
2460     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
2461     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2462     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2463     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
2464     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2465     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2466     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
2467 };
2468 
2469 static const int suite_ARIA_128_ephemeral[] = {
2470     /* All ARIA-128 ephemeral suites */
2471     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,
2472     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
2473     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,
2474     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
2475     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
2476     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256
2477 };
2478 
2479 static const int suite_PSK_ephemeral[] = {
2480     /* The PSK ephemeral suites */
2481     MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2482     MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2483     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,
2484     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM,
2485     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
2486     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
2487     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
2488     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
2489     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2490     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2491     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2492     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8,
2493     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,
2494     MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
2495     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
2496 
2497     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
2498     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM,
2499     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
2500     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
2501     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
2502     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
2503     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2504     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2505     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2506     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8,
2507     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,
2508     MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
2509     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256
2510 };
2511 
2512 #if 0
2513 static const int suite_ECJPAKE[] = {
2514     /* The ECJPAKE suite */
2515     MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
2516 };
2517 #endif
2518 
2519 static const int suite_AES_256[] = {
2520     /* All AES-256 suites */
2521     MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384,
2522     MBEDTLS_TLS_RSA_WITH_AES_256_CCM,
2523     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256,
2524     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA,
2525     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
2526     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
2527     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
2528     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
2529     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
2530     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
2531     MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8
2532 };
2533 
2534 static const int suite_CAMELLIA_256[] = {
2535     /* All CAMELLIA-256 suites */
2536     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2537     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2538     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
2539     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2540     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
2541     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
2542     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
2543 };
2544 
2545 static const int suite_ARIA_256[] = {
2546     /* All ARIA-256 suites */
2547     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
2548     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
2549     MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
2550     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
2551     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
2552     MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384
2553 };
2554 
2555 static const int suite_AES_128[] = {
2556     /* All AES-128 suites */
2557     MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
2558     MBEDTLS_TLS_RSA_WITH_AES_128_CCM,
2559     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
2560     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
2561     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
2562     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
2563     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
2564     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
2565     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
2566     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
2567     MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8
2568 };
2569 
2570 static const int suite_CAMELLIA_128[] = {
2571     /* All CAMELLIA-128 suites */
2572     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2573     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2574     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
2575     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2576     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2577     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
2578     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
2579 };
2580 
2581 static const int suite_ARIA_128[] = {
2582     /* All ARIA-128 suites */
2583     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
2584     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
2585     MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
2586     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
2587     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
2588     MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256
2589 };
2590 
2591 static const int suite_RSA_PSK[] = {
2592     /* The RSA PSK suites */
2593     MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256,
2594     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
2595     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
2596     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
2597     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2598     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2599     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
2600     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
2601 
2602     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
2603     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
2604     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
2605     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2606     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2607     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
2608     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256
2609 };
2610 
2611 static const int suite_PSK[] = {
2612     /* The PSK suites */
2613     MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,
2614     MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384,
2615     MBEDTLS_TLS_PSK_WITH_AES_256_CCM,
2616     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384,
2617     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA,
2618     MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2619     MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2620     MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8,
2621     MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
2622     MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
2623 
2624     MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256,
2625     MBEDTLS_TLS_PSK_WITH_AES_128_CCM,
2626     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256,
2627     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA,
2628     MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2629     MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2630     MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8,
2631     MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
2632     MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256
2633 };
2634 
2635 static const int suite_3DES[] = {
2636     /* 3DES suites */
2637     MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
2638     MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
2639     MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
2640     MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
2641     MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
2642     MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
2643     MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
2644     MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
2645     MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
2646     MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
2647 };
2648 
2649 static const int suite_RC4[] = {
2650     /* RC4 suites */
2651     MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
2652     MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
2653     MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
2654     MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA,
2655     MBEDTLS_TLS_RSA_WITH_RC4_128_SHA,
2656     MBEDTLS_TLS_RSA_WITH_RC4_128_MD5,
2657     MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA,
2658     MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
2659     MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA,
2660     MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
2661 };
2662 
2663 static const int suite_weak[] = {
2664     /* Weak suites */
2665     MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA,
2666     MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA
2667 };
2668 
2669 static const int suite_null[] = {
2670     /* NULL suites */
2671     MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
2672     MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA,
2673     MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384,
2674     MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256,
2675     MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA,
2676     MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384,
2677     MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256,
2678     MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA,
2679 
2680     MBEDTLS_TLS_RSA_WITH_NULL_SHA256,
2681     MBEDTLS_TLS_RSA_WITH_NULL_SHA,
2682     MBEDTLS_TLS_RSA_WITH_NULL_MD5,
2683     MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA,
2684     MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA,
2685     MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384,
2686     MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256,
2687     MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA,
2688     MBEDTLS_TLS_PSK_WITH_NULL_SHA384,
2689     MBEDTLS_TLS_PSK_WITH_NULL_SHA256,
2690     MBEDTLS_TLS_PSK_WITH_NULL_SHA
2691 };
2692 
2693 /* TLSv1.2 cipher list (supported in mbedtls)
2694  * marked with minimum version MBEDTLS_SSL_MINOR_VERSION_3 in
2695  *   ciphersuite_definitions[] and then sorted by ciphersuite_preference[]
2696  *   from mbedtls library/ssl_ciphersuites.c */
2697 static const int suite_TLSv12[] = {
2698     MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
2699     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
2700     MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
2701     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
2702     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
2703     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
2704     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
2705     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM,
2706     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
2707     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
2708     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
2709     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
2710     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8,
2711     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
2712     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2713     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2714     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2715     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,
2716     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
2717     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,
2718     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
2719     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
2720     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
2721     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
2722     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
2723     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
2724     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
2725     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM,
2726     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
2727     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
2728     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
2729     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
2730     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8,
2731     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
2732     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2733     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2734     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2735     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,
2736     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
2737     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,
2738     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
2739     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
2740     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
2741     MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2742     MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2743     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,
2744     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM,
2745     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2746     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8,
2747     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,
2748     MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
2749     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
2750     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
2751     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM,
2752     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2753     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8,
2754     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,
2755     MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
2756     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
2757     MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8,
2758     MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384,
2759     MBEDTLS_TLS_RSA_WITH_AES_256_CCM,
2760     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256,
2761     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
2762     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
2763     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
2764     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
2765     MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8,
2766     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2767     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2768     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
2769     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
2770     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
2771     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
2772     MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
2773     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
2774     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
2775     MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
2776     MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
2777     MBEDTLS_TLS_RSA_WITH_AES_128_CCM,
2778     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
2779     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
2780     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
2781     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
2782     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
2783     MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8,
2784     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2785     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2786     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
2787     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
2788     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
2789     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
2790     MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
2791     MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
2792     MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
2793     MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
2794     MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256,
2795     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
2796     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2797     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
2798     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
2799     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
2800     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2801     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
2802     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
2803     MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,
2804     MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384,
2805     MBEDTLS_TLS_PSK_WITH_AES_256_CCM,
2806     MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
2807     MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8,
2808     MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
2809     MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
2810     MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256,
2811     MBEDTLS_TLS_PSK_WITH_AES_128_CCM,
2812     MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
2813     MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8,
2814     MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
2815     MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256
2816 };
2817 
2818 /* TLSv1.0 cipher list (supported in mbedtls)
2819  * marked with minimum version MBEDTLS_SSL_MINOR_VERSION_1 in
2820  *   ciphersuite_definitions[] and then sorted by ciphersuite_preference[]
2821  *   from mbedtls library/ssl_ciphersuites.c */
2822 /* XXX: intentionally not including overlapping eNULL ciphers */
2823 static const int suite_TLSv10[] = {
2824     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
2825     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
2826     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
2827     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
2828     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
2829     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
2830     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
2831     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2832     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
2833     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
2834     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
2835     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2836     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2837     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
2838     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
2839     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
2840     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2841     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2842     MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
2843     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
2844     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
2845     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
2846     MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
2847     MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
2848     MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2849     MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
2850     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
2851     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
2852     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2853     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
2854     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
2855     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2856     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384,
2857     MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2858     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256,
2859     MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2860     MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
2861     MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
2862     MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
2863     MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
2864     MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
2865     MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
2866     MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
2867     MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
2868     MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
2869     MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA,
2870     MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
2871     MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
2872 };
2873 
2874 /* SSLv3 cipher list (supported in mbedtls)
2875  * marked with minimum version MBEDTLS_SSL_MINOR_VERSION_0 in
2876  *   ciphersuite_definitions[] and then sorted by ciphersuite_preference[]
2877  *   from mbedtls library/ssl_ciphersuites.c */
2878 /* XXX: intentionally not including overlapping eNULL ciphers */
2879 static const int suite_SSLv3[] = {
2880     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
2881     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
2882     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
2883     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
2884     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
2885     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
2886     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA,
2887     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
2888     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
2889     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
2890     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA,
2891     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA,
2892     MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
2893     MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
2894     MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
2895     MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
2896     MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA,
2897     MBEDTLS_TLS_RSA_WITH_RC4_128_SHA,
2898     MBEDTLS_TLS_RSA_WITH_RC4_128_MD5,
2899     MBEDTLS_TLS_PSK_WITH_RC4_128_SHA,
2900     MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA,
2901     MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA
2902 };
2903 
2904 /* HIGH cipher list (mapped from openssl list to mbedtls) */
2905 static const int suite_HIGH[] = {
2906     MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
2907     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
2908     MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
2909     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
2910     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
2911     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
2912     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
2913     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM,
2914     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
2915     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
2916     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
2917     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
2918     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
2919     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
2920     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
2921     MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8,
2922     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
2923     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
2924     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2925     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
2926     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,
2927     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
2928     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,
2929     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
2930     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
2931     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
2932     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
2933     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM,
2934     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
2935     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
2936     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
2937     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
2938     MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
2939     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
2940     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
2941     MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8,
2942     MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
2943     MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2944     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2945     MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
2946     MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,
2947     MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
2948     MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,
2949     MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2950     MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
2951     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,
2952     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM,
2953     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
2954     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
2955     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
2956     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
2957     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2958     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2959     MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8,
2960     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,
2961     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
2962     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM,
2963     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
2964     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
2965     MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
2966     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
2967     MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2968     MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2969     MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8,
2970     MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,
2971     MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384,
2972     MBEDTLS_TLS_RSA_WITH_AES_256_CCM,
2973     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256,
2974     MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA,
2975     MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8,
2976     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
2977     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
2978     MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
2979     MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
2980     MBEDTLS_TLS_RSA_WITH_AES_128_CCM,
2981     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
2982     MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
2983     MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8,
2984     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
2985     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
2986     MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
2987     MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256,
2988     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
2989     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
2990     MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
2991     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
2992     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
2993     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
2994     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
2995     MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
2996     MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
2997     MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
2998     MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,
2999     MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384,
3000     MBEDTLS_TLS_PSK_WITH_AES_256_CCM,
3001     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384,
3002     MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA,
3003     MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
3004     MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8,
3005     MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
3006     MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256,
3007     MBEDTLS_TLS_PSK_WITH_AES_128_CCM,
3008     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256,
3009     MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA,
3010     MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
3011     MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8,
3012     MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
3013 };
3014 
3015 
3016 /* true if RC4 or weak or NULL cipher suite
3017  *   (These ciphersuites are excluded from openssl "DEFAULT")
3018  * This is a subset of ciphers excluded for mod_openssl "!aNULL:!eNULL:!EXP" */
3019 static int
3020 mod_mbedtls_ssl_is_weak_ciphersuite (int id)
3021 {
3022     for (uint32_t i = 0; i < sizeof(suite_RC4)/sizeof(suite_RC4[0]); ++i) {
3023         if (id == suite_RC4[i]) return 1;
3024     }
3025     for (uint32_t i = 0; i < sizeof(suite_weak)/sizeof(suite_weak[0]); ++i) {
3026         if (id == suite_weak[i]) return 1;
3027     }
3028     for (uint32_t i = 0; i < sizeof(suite_null)/sizeof(suite_null[0]); ++i) {
3029         if (id == suite_null[i]) return 1;
3030     }
3031     return 0;
3032 }
3033 
3034 
3035 static int
3036 mod_mbedtls_ssl_DEFAULT_ciphersuite (server *srv, int *ids, int nids, int idsz)
3037 {
3038     /* obtain default ciphersuite list and filter out weak or NULL */
3039     const int *dids = mbedtls_ssl_list_ciphersuites();
3040     int i = 0;
3041     while (dids[i] != 0) ++i;
3042 
3043     if (i >= idsz - (nids + 1)) {
3044         log_error(srv->errh, __FILE__, __LINE__,
3045           "MTLS: error: too many ciphersuites during list expand");
3046         return -1;
3047     }
3048 
3049     for (i = 0; dids[i] != 0; ++i) {
3050         if (!mod_mbedtls_ssl_is_weak_ciphersuite(dids[i]))
3051             ids[++nids] = dids[i];
3052     }
3053 
3054     return nids;
3055 }
3056 
3057 
3058 static int
3059 mod_mbedtls_ssl_append_ciphersuite (server *srv, int *ids, int nids, int idsz, const int *x, int xsz)
3060 {
3061     if (xsz >= idsz - (nids + 1)) {
3062         log_error(srv->errh, __FILE__, __LINE__,
3063           "MTLS: error: too many ciphersuites during list expand");
3064         return -1;
3065     }
3066 
3067     for (int i = 0; i < xsz; ++i)
3068         ids[++nids] = x[i];
3069 
3070     return nids;
3071 }
3072 
3073 
3074 static int
3075 mod_mbedtls_ssl_conf_ciphersuites (server *srv, plugin_config_socket *s, buffer *ciphersuites, const buffer *cipherstring)
3076 {
3077     /* reference: https://www.openssl.org/docs/man1.1.1/man1/ciphers.html
3078      * Attempt to parse *some* keywords from Ciphersuites and CipherString
3079      * !!! openssl uses a *different* naming scheme than does mbedTLS !!!
3080      * Since Ciphersuites in openssl takes only TLSv1.3 suites, and mbedTLS
3081      * does not currently support TLSv1.3, mapping of those names is not
3082      * currently provided.  Note that CipherString does allow cipher suites to
3083      * be listed, and this code does not currently attempt to provide mapping */
3084 
3085     char n[128]; /*(most ciphersuite names are about 40 chars)*/
3086     int ids[512];
3087     int nids = -1;
3088     const int idsz = (int)(sizeof(ids)/sizeof(*ids)-1);
3089     int crt_profile_default = 0;
3090 
3091     if (ciphersuites) {
3092         buffer *b = ciphersuites;
3093         buffer_to_upper(b); /*(ciphersuites are all uppercase (currently))*/
3094         for (const char *p, *e = b->ptr-1; e && (e = strchr((p = e+1),':')); ) {
3095             size_t len = e ? (size_t)(e - p) : strlen(p);
3096             if (len >= sizeof(n)) {
3097                 log_error(srv->errh, __FILE__, __LINE__,
3098                   "MTLS: skipped ciphersuite; too long: %.*s",
3099                   (int)len, p);
3100                 continue;
3101             }
3102             memcpy(n, p, len);
3103             n[len] = '\0';
3104 
3105             int id = mbedtls_ssl_get_ciphersuite_id(n);
3106             if (0 == id) {
3107                 log_error(srv->errh, __FILE__, __LINE__,
3108                   "MTLS: skipped ciphersuite; not recognized: %.*s",
3109                   (int)len, n);
3110                 continue;
3111             }
3112 
3113             /* allow any ciphersuite if explicitly listed, even weak or eNULL */
3114           #if 0
3115             if (mod_mbedtls_ssl_is_weak_ciphersuite(id)) {
3116                 log_error(srv->errh, __FILE__, __LINE__,
3117                   "MTLS: skipped ciphersuite; weak or NULL suite: %.*s",
3118                   (int)len, n);
3119                 continue;
3120             }
3121           #endif
3122 
3123             if (nids >= idsz) {
3124                 log_error(srv->errh, __FILE__, __LINE__,
3125                   "MTLS: skipped ciphersuite; too many listed: %.*s",
3126                   (int)len, n);
3127                 continue;
3128             }
3129 
3130             ids[++nids] = id;
3131         }
3132     }
3133 
3134     /* XXX: openssl config for CipherString=... is excessively complex.
3135      * If there is a need to enable specific ciphersuites, then that
3136      * can be accomplished with mod_mbedtls by specifying the list in
3137      * Ciphersuites=... in the ssl.openssl.ssl-conf-cmd directive.
3138      * (Alternatively, build mbedtls with specific set of cipher suites
3139      *  or modify mod_mbedtls code to specify the precise list).
3140      *
3141      * The tokens parsed here are a quick attempt to handle a few cases
3142      *
3143      * XXX: not done: could make a list of ciphers with bitflag of attributes
3144      *      to make future combining easier */
3145     if (!buffer_string_is_empty(cipherstring)) {
3146         const buffer *b = cipherstring;
3147         const char *e = b->ptr;
3148 
3149         /* XXX: not done: no checking for duplication of ciphersuites
3150          * even if tokens overlap or are repeated */
3151 
3152         /* XXX: not done: might walk string and build up exclude list of !xxxxx
3153          * ciphersuites and walk string again, excluding as result list built */
3154 
3155         /* manually handle first token, since one-offs apply */
3156         /* (openssl syntax NOT fully supported) */
3157         int default_suite = 0;
3158         if (0 == strncmp(e, "!ALL", 4) || 0 == strncmp(e, "-ALL", 4)) {
3159             /* "!ALL" excluding all ciphers does not make sense; ignore */
3160             e += sizeof("!ALL")-1; /* same as sizeof("-ALL")-1 */
3161         }
3162         else if (0 == strncmp(e, CONST_STR_LEN("!DEFAULT"))
3163               || 0 == strncmp(e, CONST_STR_LEN("-DEFAULT"))) {
3164             /* "!DEFAULT" excluding default ciphers is empty list; no effect */
3165             e += sizeof("!DEFAULT")-1; /* same as sizeof("-DEFAULT")-1 */
3166         }
3167         else if (0 == strncmp(e, CONST_STR_LEN("DEFAULT"))) {
3168             e += sizeof("DEFAULT")-1;
3169             default_suite = 1;
3170         }
3171         else if (0 == /* effectively the same as "DEFAULT" */
3172                  strncmp(e, CONST_STR_LEN("ALL:!COMPLEMENTOFDEFAULT:!eNULL"))) {
3173             e += sizeof("ALL:!COMPLEMENTOFDEFAULT:!eNULL")-1;
3174             default_suite = 1;
3175         }
3176         else if (0 == strncmp(e, CONST_STR_LEN("SUITEB128"))
3177               || 0 == strncmp(e, CONST_STR_LEN("SUITEB128ONLY"))
3178               || 0 == strncmp(e, CONST_STR_LEN("SUITEB192"))) {
3179             mbedtls_ssl_conf_cert_profile(s->ssl_ctx,
3180                                           &mbedtls_x509_crt_profile_suiteb);
3181             /* re-initialize mbedtls_ssl_config defaults */
3182             mbedtls_mpi_free(&s->ssl_ctx->dhm_P);
3183             mbedtls_mpi_free(&s->ssl_ctx->dhm_G);
3184             int rc = mbedtls_ssl_config_defaults(s->ssl_ctx,
3185                                                  MBEDTLS_SSL_IS_SERVER,
3186                                                  MBEDTLS_SSL_TRANSPORT_STREAM,
3187                                                  MBEDTLS_SSL_PRESET_SUITEB);
3188             if (0 != rc) {
3189                 elog(srv->errh, __FILE__,__LINE__, rc,
3190                      "Init of ssl config context SUITEB defaults failed");
3191                 return 0;
3192             }
3193             e += (0 == strncmp(e, CONST_STR_LEN("SUITEB128ONLY")))
3194                  ? sizeof("SUITEB128ONLY")-1
3195                  : sizeof("SUITEB128")-1;
3196             if (*e)
3197                 log_error(srv->errh, __FILE__, __LINE__,
3198                   "MTLS: ignoring cipher string after SUITEB: %s", e);
3199             return 1;
3200         }
3201 
3202         if (e != b->ptr && *e != ':' && *e != '\0') {
3203             log_error(srv->errh, __FILE__, __LINE__,
3204               "MTLS: error: missing support for cipher list: %s", b->ptr);
3205             return 0;
3206         }
3207 
3208         if (default_suite) {
3209             crt_profile_default = 1;
3210             nids =
3211               mod_mbedtls_ssl_DEFAULT_ciphersuite(srv, ids, nids, idsz);
3212             if (-1 == nids) return 0;
3213         }
3214 
3215         /* not handled: "ALL" is "DEFAULT" and "RC4" */
3216         /* not handled: "COMPLEMENTOFALL" is "eNULL" */
3217 
3218         int rc = 1;
3219         if (e == b->ptr || *e == '\0') --e; /*initial condition for loop below*/
3220         for (const char *p; e && (e = strchr((p = e+1),':')); ) {
3221             size_t len = e ? (size_t)(e - p) : strlen(p);
3222             if (len >= sizeof(n)) {
3223                 log_error(srv->errh, __FILE__, __LINE__,
3224                   "MTLS: skipped ciphersuite; too long: %.*s",
3225                   (int)len, p);
3226                 continue;
3227             }
3228             char c = (*p == '!' || *p == '-' || *p == '+') ? *p : 0;
3229             size_t nlen = c ? len-1 : len;
3230             memcpy(n, c ? p+1 : p, nlen);
3231             n[nlen] = '\0';
3232 
3233             /* not handled: !xxxxx -xxxxx and most +xxxxx */
3234             if (c) {
3235                 log_error(srv->errh, __FILE__, __LINE__,
3236                   "MTLS: error: missing support for cipher list: %s", b->ptr);
3237             }
3238 
3239             /* ignore @STRENGTH sorting and ignore @SECLEVEL=n */
3240             char *a = strchr(n, '@');
3241             if (a) {
3242                 log_error(srv->errh, __FILE__, __LINE__,
3243                   "MTLS: ignored %s in %.*s", a, (int)len, p);
3244                 *a = '\0';
3245                 nlen = (size_t)(a - n);
3246             }
3247 
3248             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("TLSv1.2"))) {
3249                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3250                          suite_TLSv12,
3251                          (int)(sizeof(suite_TLSv12)/sizeof(*suite_TLSv12)));
3252                 if (-1 == nids) return 0;
3253                 continue;
3254             }
3255 
3256             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("TLSv1.0"))) {
3257                 crt_profile_default = 1;
3258                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3259                          suite_TLSv10,
3260                          (int)(sizeof(suite_TLSv10)/sizeof(*suite_TLSv10)));
3261                 if (-1 == nids) return 0;
3262                 continue;
3263             }
3264 
3265             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("SSLv3"))) {
3266                 crt_profile_default = 1;
3267                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3268                          suite_SSLv3,
3269                          (int)(sizeof(suite_SSLv3)/sizeof(*suite_SSLv3)));
3270                 if (-1 == nids) return 0;
3271                 continue;
3272             }
3273 
3274             /* handle a popular recommendations
3275              *   ssl.cipher-list = "EECDH+AESGCM:EDH+AESGCM"
3276              *   ssl.cipher-list = "AES256+EECDH:AES256+EDH"
3277              * which uses AES hardware acceleration built into popular CPUs */
3278             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ECDHE+AESGCM"))
3279              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("EECDH+AESGCM"))) {
3280                 if (nids + 4 >= idsz) {
3281                     log_error(srv->errh, __FILE__, __LINE__,
3282                       "MTLS: error: too many ciphersuites during list expand");
3283                     return 0;
3284                 }
3285                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
3286                 ids[++nids] = MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
3287                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
3288                 ids[++nids] = MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
3289                 continue;
3290             }
3291             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("DHE+AESGCM"))
3292              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("EDH+AESGCM"))) {
3293                 if (nids + 2 >= idsz) {
3294                     log_error(srv->errh, __FILE__, __LINE__,
3295                       "MTLS: error: too many ciphersuites during list expand");
3296                     return 0;
3297                 }
3298                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384;
3299                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256;
3300                 continue;
3301             }
3302             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256+EECDH"))) {
3303                 if (nids + 8 >= idsz) {
3304                     log_error(srv->errh, __FILE__, __LINE__,
3305                       "MTLS: error: too many ciphersuites during list expand");
3306                     return 0;
3307                 }
3308                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
3309                 ids[++nids] = MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
3310                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM;
3311                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
3312                 ids[++nids] = MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384;
3313                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA;
3314                 ids[++nids] = MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA;
3315                 ids[++nids] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8;
3316                 continue;
3317             }
3318             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256+EDH"))) {
3319                 if (nids + 5 >= idsz) {
3320                     log_error(srv->errh, __FILE__, __LINE__,
3321                       "MTLS: error: too many ciphersuites during list expand");
3322                     return 0;
3323                 }
3324                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384;
3325                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM;
3326                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256;
3327                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
3328                 ids[++nids] = MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8;
3329                 continue;
3330             }
3331 
3332             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("HIGH"))) {
3333                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3334                          suite_HIGH,
3335                          (int)(sizeof(suite_HIGH)/sizeof(*suite_HIGH)));
3336                 if (-1 == nids) return 0;
3337                 continue;
3338             }
3339 
3340             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256"))
3341              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES"))) {
3342                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3343                          suite_AES_256_ephemeral,
3344                          (int)(sizeof(suite_AES_256_ephemeral)
3345                               /sizeof(*suite_AES_256_ephemeral)));
3346                 if (-1 == nids) return 0;
3347                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3348                          suite_AES_256,
3349                          (int)(sizeof(suite_AES_256)/sizeof(*suite_AES_256)));
3350                 if (-1 == nids) return 0;
3351                 /* XXX: not done: AES256 PSK suites */
3352                 if (nlen == sizeof("AES256")-1) continue;
3353             }
3354 
3355             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES128"))
3356              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES"))) {
3357                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3358                          suite_AES_128_ephemeral,
3359                          (int)(sizeof(suite_AES_128_ephemeral)
3360                               /sizeof(*suite_AES_128_ephemeral)));
3361                 if (-1 == nids) return 0;
3362                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3363                          suite_AES_128,
3364                          (int)(sizeof(suite_AES_128)/sizeof(*suite_AES_128)));
3365                 if (-1 == nids) return 0;
3366                 /* XXX: not done: AES128 PSK suites */
3367                 continue;
3368             }
3369 
3370             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA256"))
3371              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA"))) {
3372                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3373                          suite_CAMELLIA_256_ephemeral,
3374                          (int)(sizeof(suite_CAMELLIA_256_ephemeral)
3375                               /sizeof(*suite_CAMELLIA_256_ephemeral)));
3376                 if (-1 == nids) return 0;
3377                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3378                          suite_CAMELLIA_256,
3379                          (int)(sizeof(suite_CAMELLIA_256)
3380                               /sizeof(*suite_CAMELLIA_256)));
3381                 if (-1 == nids) return 0;
3382                 /* XXX: not done: CAMELLIA256 PSK suites */
3383                 if (nlen == sizeof("CAMELLIA256")-1) continue;
3384             }
3385 
3386             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA128"))
3387              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA"))) {
3388                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3389                          suite_CAMELLIA_128_ephemeral,
3390                          (int)(sizeof(suite_CAMELLIA_128_ephemeral)
3391                               /sizeof(*suite_CAMELLIA_128_ephemeral)));
3392                 if (-1 == nids) return 0;
3393                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3394                          suite_CAMELLIA_128,
3395                          (int)(sizeof(suite_CAMELLIA_128)
3396                               /sizeof(*suite_CAMELLIA_128)));
3397                 if (-1 == nids) return 0;
3398                 /* XXX: not done: CAMELLIA128 PSK suites */
3399                 continue;
3400             }
3401 
3402             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ARIA256"))
3403              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ARIA"))) {
3404                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3405                          suite_ARIA_256_ephemeral,
3406                          (int)(sizeof(suite_ARIA_256_ephemeral)
3407                               /sizeof(*suite_ARIA_256_ephemeral)));
3408                 if (-1 == nids) return 0;
3409                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3410                          suite_ARIA_256,
3411                          (int)(sizeof(suite_ARIA_256)/sizeof(*suite_ARIA_256)));
3412                 if (-1 == nids) return 0;
3413                 /* XXX: not done: ARIA256 PSK suites */
3414                 if (nlen == sizeof("ARIA256")-1) continue;
3415             }
3416 
3417             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ARIA128"))
3418              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ARIA"))) {
3419                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3420                          suite_ARIA_128_ephemeral,
3421                          (int)(sizeof(suite_ARIA_128_ephemeral)
3422                               /sizeof(*suite_ARIA_128_ephemeral)));
3423                 if (-1 == nids) return 0;
3424                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3425                          suite_ARIA_128,
3426                          (int)(sizeof(suite_ARIA_128)/sizeof(*suite_ARIA_128)));
3427                 if (-1 == nids) return 0;
3428                 /* XXX: not done: ARIA128 PSK suites */
3429                 continue;
3430             }
3431 
3432             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CHACHA20"))) {
3433                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3434                          suite_CHACHAPOLY_ephemeral,
3435                          (int)(sizeof(suite_CHACHAPOLY_ephemeral)
3436                               /sizeof(*suite_CHACHAPOLY_ephemeral)));
3437                 if (-1 == nids) return 0;
3438                 /* XXX: not done: CHACHA20 PSK suites */
3439                 continue;
3440             }
3441 
3442             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("PSK"))) {
3443                 /* XXX: intentionally not including overlapping eNULL ciphers */
3444                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3445                          suite_PSK_ephemeral,
3446                          (int)(sizeof(suite_PSK_ephemeral)
3447                               /sizeof(*suite_PSK_ephemeral)));
3448                 if (-1 == nids) return 0;
3449                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3450                          suite_RSA_PSK,
3451                          (int)(sizeof(suite_RSA_PSK)/sizeof(*suite_RSA_PSK)));
3452                 if (-1 == nids) return 0;
3453                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3454                          suite_PSK,
3455                          (int)(sizeof(suite_PSK)/sizeof(*suite_PSK)));
3456                 if (-1 == nids) return 0;
3457                 continue;
3458             }
3459 
3460             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("3DES"))) {
3461                 crt_profile_default = 1;
3462                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3463                          suite_3DES,
3464                          (int)(sizeof(suite_3DES)/sizeof(*suite_3DES)));
3465                 if (-1 == nids) return 0;
3466                 continue;
3467             }
3468 
3469             /* not recommended, but permitted if explicitly requested */
3470             /* "RC4" is same as openssl "COMPLEMENTOFALL" */
3471             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("RC4"))) {
3472                 crt_profile_default = 1;
3473                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3474                          suite_RC4,
3475                          (int)(sizeof(suite_RC4)/sizeof(*suite_RC4)));
3476                 if (-1 == nids) return 0;
3477                 continue;
3478             }
3479 
3480             /* not recommended, but permitted if explicitly requested */
3481             if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("NULL"))
3482              || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("eNULL"))) {
3483                 crt_profile_default = 1;
3484                 nids = mod_mbedtls_ssl_append_ciphersuite(srv, ids, nids, idsz,
3485                          suite_null,
3486                          (int)(sizeof(suite_null)/sizeof(*suite_null)));
3487                 if (-1 == nids) return 0;
3488                 continue;
3489             }
3490 
3491             if (*e != ':' && *e != '\0') {
3492                 log_error(srv->errh, __FILE__, __LINE__,
3493                   "MTLS: error: missing support for cipher list: %.*s",
3494                   (int)len, p);
3495                 rc = 0;
3496                 continue;
3497             }
3498         }
3499         if (0 == rc) return 0;
3500     }
3501 
3502     if (-1 == nids) {
3503         /* Do not set a default if ssl.cipher-list was set (and we are
3504          * are processing ssl.openssl.ssl-conf-cmd, not ssl.cipher-list) */
3505         if (cipherstring != s->ssl_cipher_list
3506             && !buffer_string_is_empty(s->ssl_cipher_list))
3507             return 1;
3508 
3509         /* obtain default ciphersuite list and filter out RC4, weak, and NULL */
3510         nids =
3511           mod_mbedtls_ssl_DEFAULT_ciphersuite(srv, ids, nids,
3512                                               sizeof(ids)/sizeof(*ids));
3513         if (-1 == nids) return 0;
3514     }
3515 
3516     ids[++nids] = 0; /* terminate list */
3517     ++nids;
3518 
3519     if (!crt_profile_default)
3520         mbedtls_ssl_conf_cert_profile(s->ssl_ctx,
3521                                       &mbedtls_x509_crt_profile_next);
3522 
3523     /* ciphersuites list must be persistent for lifetime of mbedtls_ssl_config*/
3524     s->ciphersuites = malloc(nids * sizeof(int));
3525     force_assert(s->ciphersuites);
3526     memcpy(s->ciphersuites, ids, nids * sizeof(int));
3527 
3528     mbedtls_ssl_conf_ciphersuites(s->ssl_ctx, s->ciphersuites);
3529     return 1;
3530 }
3531 
3532 
3533 static int
3534 mod_mbedtls_ssl_append_curve (server *srv, mbedtls_ecp_group_id *ids, int nids, int idsz, const mbedtls_ecp_group_id id)
3535 {
3536     if (1 >= idsz - (nids + 1)) {
3537         log_error(srv->errh, __FILE__, __LINE__,
3538           "MTLS: error: too many curves during list expand");
3539         return -1;
3540     }
3541 
3542     ids[++nids] = id;
3543 
3544     return nids;
3545 }
3546 
3547 
3548 static int
3549 mod_mbedtls_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *curvelist)
3550 {
3551     mbedtls_ecp_group_id ids[512];
3552     int nids = -1;
3553     const int idsz = (int)(sizeof(ids)/sizeof(*ids)-1);
3554     const mbedtls_ecp_curve_info * const curve_info = mbedtls_ecp_curve_list();
3555 
3556     const buffer * const b = curvelist;
3557     for (const char *n, *e = b->ptr-1; e && (e = strchr((n = e+1),':')); ) {
3558         size_t len = e ? (size_t)(e - n) : strlen(n);
3559         /* similar to mbedtls_ecp_curve_info_from_name() */
3560         const mbedtls_ecp_curve_info *info;
3561         for (info = curve_info; info->grp_id != MBEDTLS_ECP_DP_NONE; ++info) {
3562             if (0 == strncmp(info->name, n, len) && info->name[len] == '\0')
3563                 break;
3564         }
3565         if (info->grp_id == MBEDTLS_ECP_DP_NONE) {
3566             log_error(srv->errh, __FILE__, __LINE__,
3567                       "MTLS: unrecognized curve: %.*s; ignored", (int)len, n);
3568             continue;
3569         }
3570 
3571         nids = mod_mbedtls_ssl_append_curve(srv, ids, nids, idsz, info->grp_id);
3572         if (-1 == nids) return 0;
3573     }
3574 
3575     /* XXX: mod_openssl configures "prime256v1" if curve list not specified,
3576      * but mbedtls provides a list of supported curves if not explicitly set */
3577     if (-1 == nids) return 1; /* empty list; no-op */
3578 
3579     ids[++nids] = MBEDTLS_ECP_DP_NONE; /* terminate list */
3580     ++nids;
3581 
3582     /* curves list must be persistent for lifetime of mbedtls_ssl_config */
3583     s->curves = malloc(nids * sizeof(mbedtls_ecp_group_id));
3584     force_assert(s->curves);
3585     memcpy(s->curves, ids, nids * sizeof(mbedtls_ecp_group_id));
3586 
3587     mbedtls_ssl_conf_curves(s->ssl_ctx, s->curves);
3588     return 1;
3589 }
3590 
3591 
3592 static void
3593 mod_mbedtls_ssl_conf_proto (server *srv, plugin_config_socket *s, const buffer *b, int max)
3594 {
3595     int v = MBEDTLS_SSL_MINOR_VERSION_3; /* default: TLS v1.2 */
3596     if (NULL == b) /* default: min TLSv1.2, max TLSv1.3 */
3597       #ifdef MBEDTLS_SSL_MINOR_VERSION_4
3598         v = max ? MBEDTLS_SSL_MINOR_VERSION_4 : MBEDTLS_SSL_MINOR_VERSION_3;
3599       #else
3600         v = max ? MBEDTLS_SSL_MINOR_VERSION_3 : MBEDTLS_SSL_MINOR_VERSION_3;
3601       #endif
3602     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("None"))) /*"disable" limit*/
3603         v = max
3604           ?
3605            #ifdef MBEDTLS_SSL_MINOR_VERSION_4
3606             MBEDTLS_SSL_MINOR_VERSION_4  /* TLS v1.3 */
3607            #else
3608             MBEDTLS_SSL_MINOR_VERSION_3  /* TLS v1.2 */
3609            #endif
3610           : s->ssl_use_sslv3
3611               ? MBEDTLS_SSL_MINOR_VERSION_0  /* SSL v3.0 */
3612               : MBEDTLS_SSL_MINOR_VERSION_1; /* TLS v1.0 */
3613     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("SSLv3")))
3614         v = MBEDTLS_SSL_MINOR_VERSION_0; /* SSL v3.0 */
3615     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.0")))
3616         v = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS v1.0 */
3617     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.1")))
3618         v = MBEDTLS_SSL_MINOR_VERSION_2; /* TLS v1.1 */
3619     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.2")))
3620         v = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS v1.2 */
3621   #ifdef MBEDTLS_SSL_MINOR_VERSION_4
3622     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3")))
3623         v = MBEDTLS_SSL_MINOR_VERSION_4; /* TLS v1.3 */
3624   #endif
3625     else {
3626         if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3")))
3627             log_error(srv->errh, __FILE__, __LINE__,
3628                       "MTLS: ssl.openssl.ssl-conf-cmd %s TLSv1.3 not supported "
3629                       "by mod_mbedtls; using TLSv1.2",
3630                       max ? "MaxProtocol" : "MinProtocol");
3631         else if (buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1"))
3632                  || buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1.2"))) {
3633             log_error(srv->errh, __FILE__, __LINE__,
3634                       "MTLS: ssl.openssl.ssl-conf-cmd %s %s ignored",
3635                       max ? "MaxProtocol" : "MinProtocol", b->ptr);
3636             return;
3637         }
3638         else {
3639             log_error(srv->errh, __FILE__, __LINE__,
3640                       "MTLS: ssl.openssl.ssl-conf-cmd %s %s invalid; ignored",
3641                       max ? "MaxProtocol" : "MinProtocol", b->ptr);
3642             return;
3643         }
3644     }
3645 
3646     max
3647       ? mbedtls_ssl_conf_max_version(s->ssl_ctx,MBEDTLS_SSL_MAJOR_VERSION_3,v)
3648       : mbedtls_ssl_conf_min_version(s->ssl_ctx,MBEDTLS_SSL_MAJOR_VERSION_3,v);
3649 }
3650