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