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