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