lighttpd 1.4.x https://www.lighttpd.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3649 lines
140 KiB

  1. /*
  2. * mod_mbedtls - mbedTLS support for lighttpd
  3. *
  4. * Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com All rights reserved
  5. * License: BSD 3-clause (same as lighttpd)
  6. */
  7. /*
  8. * reference:
  9. * https://tls.mbed.org/high-level-design
  10. * https://tls.mbed.org/tech-updates/blog/mbedtls-2.0-defaults-best-practices
  11. * mbedTLS header files (mbedtls/ssl.h and others) are extremely well-documented
  12. * https://tls.mbed.org/api/ (generated from mbedTLS headers and code)
  13. *
  14. * mbedTLS limitations:
  15. * - mbedTLS does not currently support TLSv1.3
  16. * - mbedTLS does not currently support OCSP
  17. * https://tls.mbed.org/discussions/feature-request/ocsp-stapling
  18. * TLS/DTLS: OCSP Stapling support #880
  19. * https://github.com/ARMmbed/mbedtls/issues/880
  20. * Add support for writing OCSP requests and parsing OCSP responses #1197
  21. * https://github.com/ARMmbed/mbedtls/issues/1197
  22. *
  23. * future possible enhancements to lighttpd mod_mbedtls:
  24. * - session cache (though session tickets are implemented)
  25. * sample code in mbedtls:programs/ssl/ssl_server2.c
  26. * (and do not enable unless server.feature-flags ssl.session-cache enabled)
  27. *
  28. * Note: If session tickets are -not- disabled with
  29. * ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
  30. * mbedtls rotates the session ticket key according to 2x timeout set with
  31. * mbedtls_ssl_ticket_setup() (currently 43200 s, so 24 hour ticket lifetime)
  32. * This is fine for use with a single lighttpd instance, but with multiple
  33. * lighttpd workers, no coordinated STEK (server ticket encryption key)
  34. * rotation occurs unless ssl.stek-file is defined and maintained (preferred),
  35. * or if some external job restarts lighttpd. Restarting lighttpd generates a
  36. * new key that is shared by lighttpd workers for the lifetime of the new key.
  37. * If the rotation period expires and lighttpd has not been restarted, and if
  38. * ssl.stek-file is not in use, then lighttpd workers will generate new
  39. * independent keys, making session tickets less effective for session
  40. * resumption, since clients have a lower chance for future connections to
  41. * reach the same lighttpd worker. However, things will still work, and a new
  42. * session will be created if session resumption fails. Admins should plan to
  43. * restart lighttpd at least every 12 hours if session tickets are enabled and
  44. * multiple lighttpd workers are configured. Since that is likely disruptive,
  45. * if multiple lighttpd workers are configured, ssl.stek-file should be
  46. * defined and the file maintained externally.
  47. */
  48. #include "first.h"
  49. #include <sys/types.h>
  50. #include <sys/stat.h>
  51. #include <errno.h>
  52. #include <fcntl.h>
  53. #include <stdarg.h>
  54. #include <stdlib.h>
  55. #include <stdio.h> /* vsnprintf() */
  56. #include <string.h>
  57. #include <mbedtls/config.h>
  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. #if MBEDTLS_VERSION_NUMBER >= 0x02040000 /* mbedtls 2.04.0 */
  70. #include <mbedtls/net_sockets.h>
  71. #else
  72. #include <mbedtls/net.h>
  73. #endif
  74. #if defined(MBEDTLS_SSL_TICKET_C)
  75. #include <mbedtls/ssl_ticket.h>
  76. #endif
  77. #ifndef MBEDTLS_X509_CRT_PARSE_C
  78. #error "lighttpd requires that mbedtls be built with MBEDTLS_X509_CRT_PARSE_C"
  79. #endif
  80. #include "base.h"
  81. #include "fdevent.h"
  82. #include "http_header.h"
  83. #include "http_kv.h"
  84. #include "log.h"
  85. #include "plugin.h"
  86. #include "safe_memclear.h"
  87. typedef struct {
  88. /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
  89. mbedtls_pk_context ssl_pemfile_pkey;/* parsed private key structure */
  90. mbedtls_x509_crt ssl_pemfile_x509; /* parsed public key structure */
  91. const buffer *ssl_pemfile;
  92. const buffer *ssl_privkey;
  93. int8_t need_chain;
  94. } plugin_cert;
  95. typedef struct {
  96. mbedtls_ssl_config *ssl_ctx; /* context shared between mbedtls_ssl_CONTEXT structures */
  97. int *ciphersuites;
  98. mbedtls_ecp_group_id *curves;
  99. } plugin_ssl_ctx;
  100. typedef struct {
  101. mbedtls_ssl_config *ssl_ctx; /* output from network_init_ssl() */
  102. int *ciphersuites; /* output from network_init_ssl() */
  103. mbedtls_ecp_group_id *curves; /* output from network_init_ssl() */
  104. /*(used only during startup; not patched)*/
  105. unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
  106. unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
  107. unsigned char ssl_empty_fragments;
  108. unsigned char ssl_use_sslv2;
  109. unsigned char ssl_use_sslv3;
  110. const buffer *ssl_cipher_list;
  111. const buffer *ssl_dh_file;
  112. const buffer *ssl_ec_curve;
  113. const buffer *ssl_acme_tls_1;
  114. array *ssl_conf_cmd;
  115. /*(copied from plugin_data for socket ssl_ctx config)*/
  116. plugin_cert *pc;
  117. mbedtls_pk_context *ssl_pemfile_pkey; /* parsed private key structure */
  118. mbedtls_x509_crt *ssl_pemfile_x509; /* parsed public key structure */
  119. mbedtls_x509_crt *ssl_ca_file;
  120. const buffer *ssl_pemfile;
  121. const buffer *ssl_privkey;
  122. unsigned char ssl_session_ticket;
  123. unsigned char ssl_verifyclient;
  124. unsigned char ssl_verifyclient_enforce;
  125. unsigned char ssl_verifyclient_depth;
  126. } plugin_config_socket; /*(used at startup during configuration)*/
  127. typedef struct {
  128. /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
  129. plugin_cert *pc;
  130. mbedtls_pk_context *ssl_pemfile_pkey; /* parsed private key structure */
  131. mbedtls_x509_crt *ssl_pemfile_x509; /* parsed public key structure */
  132. const buffer *ssl_pemfile;
  133. mbedtls_x509_crt *ssl_ca_file;
  134. mbedtls_x509_crt *ssl_ca_dn_file;
  135. mbedtls_x509_crl *ssl_ca_crl_file;
  136. unsigned char ssl_verifyclient;
  137. unsigned char ssl_verifyclient_enforce;
  138. unsigned char ssl_verifyclient_depth;
  139. unsigned char ssl_verifyclient_export_cert;
  140. unsigned char ssl_read_ahead;
  141. unsigned char ssl_log_noise;
  142. unsigned char ssl_disable_client_renegotiation;
  143. const buffer *ssl_verifyclient_username;
  144. const buffer *ssl_acme_tls_1;
  145. } plugin_config;
  146. typedef struct {
  147. PLUGIN_DATA;
  148. plugin_ssl_ctx *ssl_ctxs;
  149. plugin_config defaults;
  150. server *srv;
  151. /* NIST counter-mode deterministic random byte generator */
  152. mbedtls_ctr_drbg_context ctr_drbg;
  153. /* entropy collection and state management */
  154. mbedtls_entropy_context entropy;
  155. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  156. mbedtls_ssl_ticket_context ticket_ctx;
  157. const char *ssl_stek_file;
  158. #endif
  159. } plugin_data;
  160. static int ssl_is_init;
  161. /* need assigned p->id for deep access of module handler_ctx for connection
  162. * i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
  163. static plugin_data *plugin_data_singleton;
  164. #define LOCAL_SEND_BUFSIZE MBEDTLS_SSL_MAX_CONTENT_LEN
  165. static char *local_send_buffer;
  166. typedef struct {
  167. mbedtls_ssl_context ssl; /* mbedtls request/connection context */
  168. request_st *r;
  169. connection *con;
  170. int8_t close_notify;
  171. unsigned short alpn;
  172. int handshake_done;
  173. size_t pending_write;
  174. plugin_config conf;
  175. buffer *tmp_buf;
  176. log_error_st *errh;
  177. mbedtls_pk_context *acme_tls_1_pkey;
  178. mbedtls_x509_crt *acme_tls_1_x509;
  179. } handler_ctx;
  180. static handler_ctx *
  181. handler_ctx_init (void)
  182. {
  183. handler_ctx *hctx = calloc(1, sizeof(*hctx));
  184. force_assert(hctx);
  185. return hctx;
  186. }
  187. static void
  188. handler_ctx_free (handler_ctx *hctx)
  189. {
  190. mbedtls_ssl_free(&hctx->ssl);
  191. if (hctx->acme_tls_1_pkey) {
  192. mbedtls_pk_free(hctx->acme_tls_1_pkey);
  193. free(hctx->acme_tls_1_pkey);
  194. }
  195. if (hctx->acme_tls_1_x509) {
  196. mbedtls_x509_crt_free(hctx->acme_tls_1_x509);
  197. free(hctx->acme_tls_1_x509);
  198. }
  199. free(hctx);
  200. }
  201. #ifdef MBEDTLS_ERROR_C
  202. __attribute_cold__
  203. static void elog(log_error_st * const errh,
  204. const char * const file, const int line,
  205. const int rc, const char * const msg)
  206. {
  207. /* error logging convenience function that decodes mbedtls result codes */
  208. char buf[256];
  209. mbedtls_strerror(rc, buf, sizeof(buf));
  210. log_error(errh, file, line, "MTLS: %s: %s (-0x%04x)", msg, buf, -rc);
  211. }
  212. #else
  213. #define elog(errh, file, line, rc, msg) \
  214. log_error((errh), (file), (line), "MTLS: %s: (-0x%04x)", (msg), -(rc))
  215. #endif
  216. __attribute_cold__
  217. __attribute_format__((__printf__, 5, 6))
  218. static void elogf(log_error_st * const errh,
  219. const char * const file, const int line,
  220. const int rc, const char * const fmt, ...)
  221. {
  222. char msg[1024];
  223. va_list ap;
  224. va_start(ap, fmt);
  225. vsnprintf(msg, sizeof(msg), fmt, ap);
  226. va_end(ap);
  227. elog(errh, file, line, rc, msg);
  228. }
  229. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  230. #define TLSEXT_KEYNAME_LENGTH 16
  231. #define TLSEXT_TICK_KEY_LENGTH 32
  232. /* construct our own session ticket encryption key structure
  233. * to store keys that are not yet active
  234. * (mirror from mod_openssl, even though not all bits are used here) */
  235. typedef struct tlsext_ticket_key_st {
  236. time_t active_ts; /* tickets not issued w/ key until activation timestamp */
  237. time_t expire_ts; /* key not valid after expiration timestamp */
  238. unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
  239. unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
  240. unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
  241. } tlsext_ticket_key_t;
  242. static tlsext_ticket_key_t session_ticket_keys[1]; /* temp store until active */
  243. static time_t stek_rotate_ts;
  244. static int
  245. mod_mbedtls_session_ticket_key_file (const char *fn)
  246. {
  247. /* session ticket encryption key (STEK)
  248. *
  249. * STEK file should be stored in non-persistent storage,
  250. * e.g. /dev/shm/lighttpd/stek-file (in memory)
  251. * with appropriate permissions set to keep stek-file from being
  252. * read by other users. Where possible, systems should also be
  253. * configured without swap.
  254. *
  255. * admin should schedule an independent job to periodically
  256. * generate new STEK up to 3 times during key lifetime
  257. * (lighttpd stores up to 3 keys)
  258. *
  259. * format of binary file is:
  260. * 4-byte - format version (always 0; for use if format changes)
  261. * 4-byte - activation timestamp
  262. * 4-byte - expiration timestamp
  263. * 16-byte - session ticket key name
  264. * 32-byte - session ticket HMAC encrpytion key
  265. * 32-byte - session ticket AES encrpytion key
  266. *
  267. * STEK file can be created with a command such as:
  268. * dd if=/dev/random bs=1 count=80 status=none | \
  269. * perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
  270. * > STEK-file.$$ && mv STEK-file.$$ STEK-file
  271. *
  272. * The above delays activation time by 5 mins (+300 sec) to allow file to
  273. * be propagated to other machines. (admin must handle this independently)
  274. * If STEK generation is performed immediately prior to starting lighttpd,
  275. * admin should activate keys immediately (without +300).
  276. */
  277. int buf[23]; /* 92 bytes */
  278. int rc = 0; /*(will retry on next check interval upon any error)*/
  279. if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
  280. return rc;
  281. if (buf[0] == 0) { /*(format version 0)*/
  282. session_ticket_keys[0].active_ts = buf[1];
  283. session_ticket_keys[0].expire_ts = buf[2];
  284. memcpy(&session_ticket_keys[0].tick_key_name, buf+3, 80);
  285. rc = 1;
  286. }
  287. mbedtls_platform_zeroize(buf, sizeof(buf));
  288. return rc;
  289. }
  290. static void
  291. mod_mbedtls_session_ticket_key_check (plugin_data *p, const time_t cur_ts)
  292. {
  293. if (NULL == p->ssl_stek_file) return;
  294. struct stat st;
  295. if (0 == stat(p->ssl_stek_file, &st) && st.st_mtime > stek_rotate_ts
  296. && mod_mbedtls_session_ticket_key_file(p->ssl_stek_file)) {
  297. stek_rotate_ts = cur_ts;
  298. }
  299. tlsext_ticket_key_t *stek = session_ticket_keys;
  300. if (stek->active_ts != 0 && stek->active_ts - 63 <= cur_ts) {
  301. /* expect to get newer ssl.stek-file prior to mbedtls detecting
  302. * expiration and internally generating a new key. If not, then
  303. * lifetime may be up to 2x specified lifetime until overwritten
  304. * by mbedtls, but original key will be overwritten and discarded */
  305. mbedtls_ssl_ticket_context *ctx = &p->ticket_ctx;
  306. ctx->ticket_lifetime = stek->expire_ts - stek->active_ts;
  307. ctx->active = 1 - ctx->active;
  308. mbedtls_ssl_ticket_key *key = ctx->keys + ctx->active;
  309. /* set generation_time to cur_ts instead of stek->active_ts
  310. * since ctx->active was updated */
  311. key->generation_time = cur_ts;
  312. memcpy(key->name, stek->tick_key_name, sizeof(key->name));
  313. /* With GCM and CCM, same context can encrypt & decrypt */
  314. int rc = mbedtls_cipher_setkey(&key->ctx, stek->tick_aes_key,
  315. mbedtls_cipher_get_key_bitlen(&key->ctx),
  316. MBEDTLS_ENCRYPT);
  317. if (0 != rc) { /* expire key immediately if error occurs */
  318. key->generation_time = cur_ts - ctx->ticket_lifetime - 1;
  319. ctx->active = 1 - ctx->active;
  320. }
  321. mbedtls_platform_zeroize(stek, sizeof(tlsext_ticket_key_t));
  322. }
  323. }
  324. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  325. INIT_FUNC(mod_mbedtls_init)
  326. {
  327. plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
  328. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  329. mbedtls_ssl_ticket_init(&plugin_data_singleton->ticket_ctx);
  330. #endif
  331. return plugin_data_singleton;
  332. }
  333. static int mod_mbedtls_init_once_mbedtls (server *srv)
  334. {
  335. if (ssl_is_init) return 1;
  336. ssl_is_init = 1;
  337. plugin_data * const p = plugin_data_singleton;
  338. mbedtls_ctr_drbg_init(&p->ctr_drbg); /* init empty NSIT random num gen */
  339. mbedtls_entropy_init(&p->entropy); /* init empty entropy collection struct
  340. .. could add sources here too */
  341. int rc = /* init RNG */
  342. mbedtls_ctr_drbg_seed(&p->ctr_drbg, /* random number generator */
  343. mbedtls_entropy_func, /* default entropy func */
  344. &p->entropy, /* entropy context */
  345. NULL, 0); /* no personalization data */
  346. if (0 != rc) {
  347. elog(srv->errh, __FILE__,__LINE__, rc,
  348. "Init of random number generator failed");
  349. return 0;
  350. }
  351. local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
  352. force_assert(NULL != local_send_buffer);
  353. return 1;
  354. }
  355. static void mod_mbedtls_free_mbedtls (void)
  356. {
  357. if (!ssl_is_init) return;
  358. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  359. mbedtls_platform_zeroize(session_ticket_keys, sizeof(session_ticket_keys));
  360. stek_rotate_ts = 0;
  361. #endif
  362. plugin_data * const p = plugin_data_singleton;
  363. mbedtls_ctr_drbg_free(&p->ctr_drbg);
  364. mbedtls_entropy_free(&p->entropy);
  365. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  366. mbedtls_ssl_ticket_free(&p->ticket_ctx);
  367. #endif
  368. free(local_send_buffer);
  369. ssl_is_init = 0;
  370. }
  371. static void
  372. mod_mbedtls_free_config (server *srv, plugin_data * const p)
  373. {
  374. if (NULL != p->ssl_ctxs) {
  375. mbedtls_ssl_config * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
  376. /* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
  377. for (uint32_t i = 1; i < srv->config_context->used; ++i) {
  378. plugin_ssl_ctx * const s = p->ssl_ctxs + i;
  379. if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope) {
  380. mbedtls_ssl_config_free(s->ssl_ctx);
  381. free(s->ciphersuites);
  382. free(s->curves);
  383. }
  384. }
  385. /* free ssl_ctx from global scope */
  386. if (ssl_ctx_global_scope) {
  387. mbedtls_ssl_config_free(ssl_ctx_global_scope);
  388. free(p->ssl_ctxs[0].ciphersuites);
  389. free(p->ssl_ctxs[0].curves);
  390. }
  391. free(p->ssl_ctxs);
  392. }
  393. if (NULL == p->cvlist) return;
  394. /* (init i to 0 if global context; to 1 to skip empty global context) */
  395. for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
  396. config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
  397. for (; -1 != cpv->k_id; ++cpv) {
  398. switch (cpv->k_id) {
  399. case 0: /* ssl.pemfile */
  400. if (cpv->vtype == T_CONFIG_LOCAL) {
  401. plugin_cert *pc = cpv->v.v;
  402. mbedtls_pk_free(&pc->ssl_pemfile_pkey);
  403. mbedtls_x509_crt_free(&pc->ssl_pemfile_x509);
  404. free(pc);
  405. }
  406. break;
  407. case 2: /* ssl.ca-file */
  408. case 3: /* ssl.ca-dn-file */
  409. if (cpv->vtype == T_CONFIG_LOCAL) {
  410. mbedtls_x509_crt *cacert = cpv->v.v;
  411. mbedtls_x509_crt_free(cacert);
  412. free(cacert);
  413. }
  414. break;
  415. case 4: /* ssl.ca-dn-file */
  416. if (cpv->vtype == T_CONFIG_LOCAL) {
  417. mbedtls_x509_crl *crl = cpv->v.v;
  418. mbedtls_x509_crl_free(crl);
  419. free(crl);
  420. }
  421. break;
  422. default:
  423. break;
  424. }
  425. }
  426. }
  427. }
  428. FREE_FUNC(mod_mbedtls_free)
  429. {
  430. plugin_data *p = p_d;
  431. if (NULL == p->srv) return;
  432. mod_mbedtls_free_config(p->srv, p);
  433. mod_mbedtls_free_mbedtls();
  434. }
  435. static void
  436. mod_mbedtls_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
  437. {
  438. switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
  439. case 0: /* ssl.pemfile */
  440. if (cpv->vtype == T_CONFIG_LOCAL)
  441. pconf->pc = cpv->v.v;
  442. break;
  443. case 1: /* ssl.privkey */
  444. break;
  445. case 2: /* ssl.ca-file */
  446. if (cpv->vtype == T_CONFIG_LOCAL)
  447. pconf->ssl_ca_file = cpv->v.v;
  448. break;
  449. case 3: /* ssl.ca-dn-file */
  450. if (cpv->vtype == T_CONFIG_LOCAL)
  451. pconf->ssl_ca_dn_file = cpv->v.v;
  452. break;
  453. case 4: /* ssl.ca-crl-file */
  454. if (cpv->vtype == T_CONFIG_LOCAL)
  455. pconf->ssl_ca_dn_file = cpv->v.v;
  456. break;
  457. case 5: /* ssl.read-ahead */
  458. pconf->ssl_read_ahead = (0 != cpv->v.u);
  459. break;
  460. case 6: /* ssl.disable-client-renegotiation */
  461. pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
  462. break;
  463. case 7: /* ssl.verifyclient.activate */
  464. pconf->ssl_verifyclient = (0 != cpv->v.u);
  465. break;
  466. case 8: /* ssl.verifyclient.enforce */
  467. pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
  468. break;
  469. case 9: /* ssl.verifyclient.depth */
  470. pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
  471. break;
  472. case 10:/* ssl.verifyclient.username */
  473. pconf->ssl_verifyclient_username = cpv->v.b;
  474. break;
  475. case 11:/* ssl.verifyclient.exportcert */
  476. pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
  477. break;
  478. case 12:/* ssl.acme-tls-1 */
  479. pconf->ssl_acme_tls_1 = cpv->v.b;
  480. break;
  481. case 13:/* debug.log-ssl-noise */
  482. pconf->ssl_log_noise = (unsigned char)cpv->v.shrt;
  483. break;
  484. default:/* should not happen */
  485. return;
  486. }
  487. }
  488. static void
  489. mod_mbedtls_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
  490. {
  491. do {
  492. mod_mbedtls_merge_config_cpv(pconf, cpv);
  493. } while ((++cpv)->k_id != -1);
  494. }
  495. static void
  496. mod_mbedtls_patch_config (request_st * const r, plugin_config * const pconf)
  497. {
  498. plugin_data * const p = plugin_data_singleton;
  499. memcpy(pconf, &p->defaults, sizeof(plugin_config));
  500. for (int i = 1, used = p->nconfig; i < used; ++i) {
  501. if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
  502. mod_mbedtls_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
  503. }
  504. }
  505. __attribute_pure__
  506. static int
  507. mod_mbedtls_crt_is_self_issued (const mbedtls_x509_crt * const crt)
  508. {
  509. const mbedtls_x509_buf * const issuer = &crt->issuer_raw;
  510. const mbedtls_x509_buf * const subject = &crt->subject_raw;
  511. return subject->len == issuer->len
  512. && 0 == memcmp(issuer->p, subject->p, subject->len);
  513. }
  514. static int
  515. mod_mbedtls_construct_crt_chain (mbedtls_x509_crt *leaf, mbedtls_x509_crt *store, log_error_st *errh)
  516. {
  517. /* Historically, openssl will use the cert chain in (SSL_CTX *) if a cert
  518. * does not have a chain configured in (SSL *). While similar behavior
  519. * could be achieved with mbedtls_x509_crt_parse_file(crt, ssl_ca_file->ptr)
  520. * instead attempt to do better and build a proper, ordered cert chain. */
  521. if (leaf->next) return 0; /*(presume chain has already been provided)*/
  522. if (store == NULL) return 0;/*(unable to proceed; chain may be incomplete)*/
  523. /* attempt to construct certificate chain from certificate store */
  524. for (mbedtls_x509_crt *crt = leaf; crt; ) {
  525. const mbedtls_x509_buf * const issuer = &crt->issuer_raw;
  526. /*(walk entire store in case certs are not properly sorted)*/
  527. for (crt = store; crt; crt = crt->next) {
  528. /* The raw issuer/subject data (DER) is used for quick comparison */
  529. /* (see comments in mod_mbedtls_verify_cb())*/
  530. const mbedtls_x509_buf * const subject = &crt->subject_raw;
  531. if (issuer->len != subject->len
  532. || 0 != memcmp(subject->p, issuer->p, issuer->len)) continue;
  533. /* root cert is end condition; omit from chain of intermediates */
  534. if (mod_mbedtls_crt_is_self_issued(crt))
  535. return 0;
  536. int rc =
  537. #if MBEDTLS_VERSION_NUMBER >= 0x02110000 /* mbedtls 2.17.0 */
  538. /* save memory by eliding copy of already-loaded raw DER */
  539. mbedtls_x509_crt_parse_der_nocopy(leaf, crt->raw.p, crt->raw.len);
  540. #else
  541. mbedtls_x509_crt_parse_der(leaf, crt->raw.p, crt->raw.len);
  542. #endif
  543. if (0 != rc) { /*(failure not unexpected since already parsed)*/
  544. elog(errh, __FILE__, __LINE__, rc, "cert copy failed");
  545. return rc;
  546. }
  547. break;
  548. }
  549. }
  550. return 0; /*(no error, though cert chain may or may not be complete)*/
  551. }
  552. static int
  553. mod_mbedtls_verify_cb (void *arg, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
  554. {
  555. handler_ctx * const hctx = (handler_ctx *)arg;
  556. if (depth > hctx->conf.ssl_verifyclient_depth) {
  557. log_error(hctx->r->conf.errh, __FILE__, __LINE__,
  558. "MTLS: client cert chain too long");
  559. *flags |= MBEDTLS_X509_BADCERT_OTHER; /* cert chain too long */
  560. }
  561. else if (0 == depth && NULL != hctx->conf.ssl_ca_dn_file) {
  562. /* verify that client cert is issued by CA in ssl.ca-dn-file
  563. * if both ssl.ca-dn-file and ssl.ca-file were configured */
  564. /* The raw issuer/subject data (DER) is used for quick comparison. */
  565. const size_t len = crt->issuer_raw.len;
  566. mbedtls_x509_crt *chain = hctx->conf.ssl_ca_dn_file;
  567. do {
  568. #if 0 /* x509_name_cmp() is not a public func in mbedtls */
  569. if (0 == x509_name_cmp(&crt->issuer, &chain->subject))
  570. break;
  571. #else
  572. if (len == chain->subject_raw.len
  573. && 0 == memcmp(chain->subject_raw.p, crt->issuer_raw.p, len))
  574. break;
  575. #endif
  576. } while ((chain = chain->next));
  577. if (NULL == chain)
  578. *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  579. }
  580. if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
  581. log_error(hctx->r->conf.errh, __FILE__, __LINE__,
  582. "MTLS: client cert not trusted");
  583. }
  584. return 0;
  585. }
  586. #ifdef MBEDTLS_SSL_SERVER_NAME_INDICATION
  587. static int
  588. mod_mbedtls_SNI (void *arg, mbedtls_ssl_context *ssl, const unsigned char *servername, size_t len)
  589. {
  590. handler_ctx * const hctx = (handler_ctx *) arg;
  591. buffer_copy_string(&hctx->r->uri.scheme, "https");
  592. request_st * const r = hctx->r;
  593. if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
  594. log_error(r->conf.errh, __FILE__, __LINE__,
  595. "MTLS: SNI name too long %.*s", (int)len, servername);
  596. return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
  597. }
  598. /* use SNI to patch mod_mbedtls config and then reset COMP_HTTP_HOST */
  599. buffer_copy_string_len(&r->uri.authority, (const char *)servername, len);
  600. buffer_to_lower(&r->uri.authority);
  601. #if 0
  602. /*(r->uri.authority used below for configuration before request read;
  603. * revisit for h2)*/
  604. if (0 != http_request_host_policy(&r->uri.authority,
  605. r->conf.http_parseopts, 443))
  606. return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
  607. #endif
  608. const buffer * const ssl_pemfile = hctx->conf.pc->ssl_pemfile;
  609. r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
  610. | (1 << COMP_HTTP_HOST);
  611. mod_mbedtls_patch_config(r, &hctx->conf);
  612. /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
  613. /*(done in configfile-glue.c:config_cond_cache_reset() after request hdrs read)*/
  614. /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
  615. /*buffer_clear(&r->uri.authority);*/
  616. /*(compare strings as ssl.pemfile might repeat same file in lighttpd.conf
  617. * and mod_mbedtls does not attempt to de-dup)*/
  618. if (!buffer_is_equal(hctx->conf.pc->ssl_pemfile, ssl_pemfile)) {
  619. /* if needed, attempt to construct certificate chain for server cert */
  620. if (hctx->conf.pc->need_chain) {
  621. hctx->conf.pc->need_chain = 0; /*(attempt once to complete chain)*/
  622. mbedtls_x509_crt *ssl_cred = &hctx->conf.pc->ssl_pemfile_x509;
  623. mbedtls_x509_crt *store = hctx->conf.ssl_ca_file;
  624. if (!mod_mbedtls_construct_crt_chain(ssl_cred, store, r->conf.errh))
  625. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  626. }
  627. /* reconfigure to use SNI-specific cert */
  628. int rc =
  629. mbedtls_ssl_set_hs_own_cert(ssl,
  630. &hctx->conf.pc->ssl_pemfile_x509,
  631. &hctx->conf.pc->ssl_pemfile_pkey);
  632. if (0 != rc) {
  633. elogf(r->conf.errh, __FILE__, __LINE__, rc,
  634. "failed to set SNI certificate for TLS server name %s",
  635. r->uri.authority.ptr);
  636. return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
  637. }
  638. }
  639. return 0;
  640. }
  641. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  642. static int
  643. mod_mbedtls_conf_verify (handler_ctx *hctx, mbedtls_ssl_config *ssl_ctx)
  644. {
  645. if (NULL == hctx->conf.ssl_ca_file) {
  646. log_error(hctx->r->conf.errh, __FILE__, __LINE__,
  647. "MTLS: can't verify client without ssl.ca-file "
  648. "for TLS server name %s",
  649. hctx->r->uri.authority.ptr);
  650. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  651. }
  652. /* send ssl_ca_dn_file (if set) in client certificate request
  653. * (later changed to ssl_ca_file before client certificate verification) */
  654. mbedtls_x509_crt *ca_certs = hctx->conf.ssl_ca_dn_file
  655. ? hctx->conf.ssl_ca_dn_file
  656. : hctx->conf.ssl_ca_file;
  657. mbedtls_ssl_context * const ssl = &hctx->ssl;
  658. mbedtls_ssl_set_hs_ca_chain(ssl, ca_certs, hctx->conf.ssl_ca_crl_file);
  659. #if MBEDTLS_VERSION_NUMBER >= 0x02120000 /* mbedtls 2.18.0 */
  660. UNUSED(ssl_ctx);
  661. mbedtls_ssl_set_verify(ssl, mod_mbedtls_verify_cb, hctx);
  662. #else
  663. mbedtls_ssl_conf_verify(ssl_ctx, mod_mbedtls_verify_cb, hctx);
  664. #endif
  665. return 0;
  666. }
  667. /* mbedTLS interfaces are generally excellent. mbedTLS convenience interfaces
  668. * to read CRLs, X509 certs, and private keys are uniformly paranoid about
  669. * clearing memory. At the moment, stdio routines fopen(), fread(), fclose()
  670. * are used for portability, but without setvbuf(stream, NULL, _IOLBF, 0),
  671. * again for portability, since setvbuf() is not necessarily available. Since
  672. * stdio buffers by default, use our own funcs to read files without buffering.
  673. * mbedtls_pk_load_file() includes trailing '\0' in size when contents in PEM
  674. * format, so do the same with the value returned from fdevent_load_file().
  675. */
  676. static int
  677. mod_mbedtls_x509_crl_parse_file (mbedtls_x509_crl *chain, const char *fn)
  678. {
  679. int rc = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  680. off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
  681. char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
  682. if (NULL == data) return rc;
  683. rc = mbedtls_x509_crl_parse(chain, (unsigned char *)data, (size_t)dlen+1);
  684. if (dlen) safe_memclear(data, (size_t)dlen);
  685. free(data);
  686. return rc;
  687. }
  688. static int
  689. mod_mbedtls_x509_crt_parse_file (mbedtls_x509_crt *chain, const char *fn)
  690. {
  691. int rc = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  692. off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
  693. char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
  694. if (NULL == data) return rc;
  695. rc = mbedtls_x509_crt_parse(chain, (unsigned char *)data, (size_t)dlen+1);
  696. if (dlen) safe_memclear(data, (size_t)dlen);
  697. free(data);
  698. return rc;
  699. }
  700. static int
  701. mod_mbedtls_pk_parse_keyfile (mbedtls_pk_context *ctx, const char *fn, const char *pwd)
  702. {
  703. int rc = MBEDTLS_ERR_PK_FILE_IO_ERROR;
  704. off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
  705. char *data = fdevent_load_file(fn, &dlen, NULL, malloc, free);
  706. if (NULL == data) return rc;
  707. rc = mbedtls_pk_parse_key(ctx, (unsigned char *)data, (size_t)dlen+1,
  708. (const unsigned char *)pwd,
  709. pwd ? strlen(pwd) : 0);
  710. if (dlen) safe_memclear(data, (size_t)dlen);
  711. free(data);
  712. return rc;
  713. }
  714. static void *
  715. network_mbedtls_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey)
  716. {
  717. mbedtls_x509_crt ssl_pemfile_x509; /* parsed public key structure */
  718. mbedtls_pk_context ssl_pemfile_pkey; /* parsed private key structure */
  719. int rc;
  720. mbedtls_x509_crt_init(&ssl_pemfile_x509); /* init cert structure */
  721. rc = mod_mbedtls_x509_crt_parse_file(&ssl_pemfile_x509, pemfile->ptr);
  722. if (0 != rc) {
  723. elogf(srv->errh, __FILE__, __LINE__, rc,
  724. "PEM file cert read failed (%s)", pemfile->ptr);
  725. return NULL;
  726. }
  727. mbedtls_pk_init(&ssl_pemfile_pkey); /* init private key context */
  728. rc = mod_mbedtls_pk_parse_keyfile(&ssl_pemfile_pkey, privkey->ptr, NULL);
  729. if (0 != rc) {
  730. elogf(srv->errh, __FILE__, __LINE__, rc,
  731. "PEM file private key read failed %s", privkey->ptr);
  732. mbedtls_x509_crt_free(&ssl_pemfile_x509);
  733. return NULL;
  734. }
  735. rc = mbedtls_pk_check_pair(&ssl_pemfile_x509.pk, &ssl_pemfile_pkey);
  736. if (0 != rc) {
  737. elogf(srv->errh, __FILE__, __LINE__, rc,
  738. "PEM cert and private key did not verify (%s) (%s)",
  739. pemfile->ptr, privkey->ptr);
  740. mbedtls_pk_free(&ssl_pemfile_pkey);
  741. mbedtls_x509_crt_free(&ssl_pemfile_x509);
  742. return NULL;
  743. }
  744. plugin_cert *pc = malloc(sizeof(plugin_cert));
  745. force_assert(pc);
  746. pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
  747. pc->ssl_pemfile_x509 = ssl_pemfile_x509;
  748. pc->ssl_pemfile = pemfile;
  749. pc->ssl_privkey = privkey;
  750. pc->need_chain = (ssl_pemfile_x509.next == NULL
  751. && !mod_mbedtls_crt_is_self_issued(&ssl_pemfile_x509));
  752. mbedtls_platform_zeroize(&ssl_pemfile_pkey, sizeof(ssl_pemfile_pkey));
  753. return pc;
  754. }
  755. #ifdef MBEDTLS_SSL_ALPN
  756. static int
  757. mod_mbedtls_acme_tls_1 (handler_ctx *hctx)
  758. {
  759. buffer * const b = hctx->tmp_buf;
  760. const buffer * const name = &hctx->r->uri.authority;
  761. log_error_st * const errh = hctx->r->conf.errh;
  762. mbedtls_x509_crt *ssl_pemfile_x509 = NULL;
  763. mbedtls_pk_context *ssl_pemfile_pkey = NULL;
  764. size_t len;
  765. int rc = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
  766. /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
  767. if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
  768. return 0; /*(should not happen)*/
  769. buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
  770. buffer_append_slash(b);
  771. /* check if SNI set server name (required for acme-tls/1 protocol)
  772. * and perform simple path checks for no '/'
  773. * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
  774. if (buffer_string_is_empty(name)) return rc;
  775. if (NULL != strchr(name->ptr, '/')) return rc;
  776. if (name->ptr[0] == '.') return rc;
  777. #if 0
  778. if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443))
  779. return rc;
  780. #endif
  781. buffer_append_string_buffer(b, name);
  782. len = buffer_string_length(b);
  783. do {
  784. buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
  785. ssl_pemfile_x509 = malloc(sizeof(*ssl_pemfile_x509));
  786. force_assert(ssl_pemfile_x509);
  787. mbedtls_x509_crt_init(ssl_pemfile_x509); /* init cert structure */
  788. rc = mod_mbedtls_x509_crt_parse_file(ssl_pemfile_x509, b->ptr);
  789. if (0 != rc) {
  790. elogf(errh, __FILE__, __LINE__, rc,
  791. "Failed to load acme-tls/1 pemfile: %s", b->ptr);
  792. break;
  793. }
  794. buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
  795. buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
  796. ssl_pemfile_pkey = malloc(sizeof(*ssl_pemfile_pkey));
  797. force_assert(ssl_pemfile_pkey);
  798. mbedtls_pk_init(ssl_pemfile_pkey); /* init private key context */
  799. rc = mod_mbedtls_pk_parse_keyfile(ssl_pemfile_pkey, b->ptr, NULL);
  800. if (0 != rc) {
  801. elogf(errh, __FILE__, __LINE__, rc,
  802. "Failed to load acme-tls/1 pemfile: %s", b->ptr);
  803. break;
  804. }
  805. rc = mbedtls_ssl_set_hs_own_cert(&hctx->ssl,
  806. ssl_pemfile_x509, ssl_pemfile_pkey);
  807. if (0 != rc) {
  808. elogf(errh, __FILE__, __LINE__, rc,
  809. "failed to set acme-tls/1 certificate for TLS server "
  810. "name %s", name->ptr);
  811. break;
  812. }
  813. hctx->acme_tls_1_pkey = ssl_pemfile_pkey; /* save ptr and free later */
  814. hctx->acme_tls_1_x509 = ssl_pemfile_x509; /* save ptr and free later */
  815. return 0;
  816. } while (0);
  817. if (ssl_pemfile_pkey) {
  818. mbedtls_pk_free(ssl_pemfile_pkey);
  819. free(ssl_pemfile_pkey);
  820. }
  821. if (ssl_pemfile_x509) {
  822. mbedtls_x509_crt_free(ssl_pemfile_x509);
  823. free(ssl_pemfile_x509);
  824. }
  825. return rc;
  826. }
  827. enum {
  828. MOD_MBEDTLS_ALPN_HTTP11 = 1
  829. ,MOD_MBEDTLS_ALPN_HTTP10 = 2
  830. ,MOD_MBEDTLS_ALPN_H2 = 3
  831. ,MOD_MBEDTLS_ALPN_ACME_TLS_1 = 4
  832. };
  833. static int
  834. mod_mbedtls_alpn_select_cb (handler_ctx *hctx, const char *in)
  835. {
  836. const int n = (int)strlen(in);
  837. const int i = 0;
  838. unsigned short proto;
  839. switch (n) {
  840. case 2: /* "h2" */
  841. if (in[i] == 'h' && in[i+1] == '2') {
  842. proto = MOD_MBEDTLS_ALPN_H2;
  843. hctx->r->http_version = HTTP_VERSION_2;
  844. break;
  845. }
  846. return 0;
  847. case 8: /* "http/1.1" "http/1.0" */
  848. if (0 == memcmp(in+i, "http/1.", 7)) {
  849. if (in[i+7] == '1') {
  850. proto = MOD_MBEDTLS_ALPN_HTTP11;
  851. break;
  852. }
  853. if (in[i+7] == '0') {
  854. proto = MOD_MBEDTLS_ALPN_HTTP10;
  855. break;
  856. }
  857. }
  858. return 0;
  859. case 10: /* "acme-tls/1" */
  860. if (0 == memcmp(in+i, "acme-tls/1", 10)) {
  861. int rc = mod_mbedtls_acme_tls_1(hctx);
  862. if (0 == rc) {
  863. proto = MOD_MBEDTLS_ALPN_ACME_TLS_1;
  864. break;
  865. }
  866. return rc;
  867. }
  868. return 0;
  869. default:
  870. return 0;
  871. }
  872. hctx->alpn = proto;
  873. return 0;
  874. }
  875. #endif /* MBEDTLS_SSL_ALPN */
  876. static int
  877. mod_mbedtls_ssl_conf_ciphersuites (server *srv, plugin_config_socket *s, buffer *ciphersuites, const buffer *cipherstring);
  878. static int
  879. mod_mbedtls_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *curvelist);
  880. static void
  881. mod_mbedtls_ssl_conf_proto (server *srv, plugin_config_socket *s, const buffer *b, int max);
  882. static int
  883. mod_mbedtls_ssl_conf_cmd (server *srv, plugin_config_socket *s)
  884. {
  885. /* reference:
  886. * https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html */
  887. int rc = 0;
  888. buffer *cipherstring = NULL;
  889. buffer *ciphersuites = NULL;
  890. for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
  891. data_string *ds = (data_string *)s->ssl_conf_cmd->data[i];
  892. if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString")))
  893. cipherstring = &ds->value;
  894. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites")))
  895. ciphersuites = &ds->value;
  896. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves"))
  897. || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups"))) {
  898. if (!mod_mbedtls_ssl_conf_curves(srv, s, &ds->value))
  899. rc = -1;
  900. }
  901. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol")))
  902. mod_mbedtls_ssl_conf_proto(srv, s, &ds->value, 1); /* max */
  903. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol")))
  904. mod_mbedtls_ssl_conf_proto(srv, s, &ds->value, 0); /* min */
  905. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) {
  906. /* openssl config for Protocol=... is complex and deprecated */
  907. log_error(srv->errh, __FILE__, __LINE__,
  908. "MTLS: ssl.openssl.ssl-conf-cmd %s ignored; "
  909. "use MinProtocol=... and MaxProtocol=... instead",
  910. ds->key.ptr);
  911. }
  912. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) {
  913. for (char *v = ds->value.ptr, *e; *v; v = e) {
  914. while (*v == ' ' || *v == '\t' || *v == ',') ++v;
  915. int flag = 1;
  916. if (*v == '-') {
  917. flag = 0;
  918. ++v;
  919. }
  920. for (e = v; light_isalpha(*e); ++e) ;
  921. switch ((int)(e-v)) {
  922. case 11:
  923. if (buffer_eq_icase_ssn(v, "Compression", 11)) {
  924. /* mbedtls defaults to no record compression unless
  925. * mbedtls is built with MBEDTLS_ZLIB_SUPPORT, which
  926. * is deprecated and slated for removal*/
  927. if (!flag) continue;
  928. }
  929. break;
  930. case 13:
  931. if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) {
  932. s->ssl_session_ticket = flag;
  933. continue;
  934. }
  935. break;
  936. case 16:
  937. if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) {
  938. /* Note: The server uses its own preferences
  939. * over the preference of the client unless
  940. * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE defined! */
  941. s->ssl_honor_cipher_order = flag;
  942. continue;
  943. }
  944. break;
  945. default:
  946. break;
  947. }
  948. /* warn if not explicitly handled or ignored above */
  949. if (!flag) --v;
  950. log_error(srv->errh, __FILE__, __LINE__,
  951. "MTLS: ssl.openssl.ssl-conf-cmd Options %.*s ignored",
  952. (int)(e-v), v);
  953. }
  954. }
  955. #if 0
  956. else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) {
  957. }
  958. #endif
  959. else {
  960. /* warn if not explicitly handled or ignored above */
  961. log_error(srv->errh, __FILE__, __LINE__,
  962. "MTLS: ssl.openssl.ssl-conf-cmd %s ignored",
  963. ds->key.ptr);
  964. }
  965. }
  966. if (!mod_mbedtls_ssl_conf_ciphersuites(srv, s, ciphersuites, cipherstring))
  967. rc = -1;
  968. return rc;
  969. }
  970. static int
  971. network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p)
  972. {
  973. int rc;
  974. s->ssl_ctx = malloc(sizeof(mbedtls_ssl_config));
  975. force_assert(s->ssl_ctx);
  976. mbedtls_ssl_config_init(s->ssl_ctx);
  977. /* set the RNG in the ssl config context, using the default random func */
  978. mbedtls_ssl_conf_rng(s->ssl_ctx, mbedtls_ctr_drbg_random, &p->ctr_drbg);
  979. /* mbedtls defaults to disable client renegotiation
  980. * mbedtls defaults to no record compression unless mbedtls is built
  981. * with MBEDTLS_ZLIB_SUPPORT, which is deprecated and slated for removal
  982. * MBEDTLS_SSL_PRESET_SUITEB is stricter than MBEDTLS_SSL_PRESET_DEFAULT
  983. * (and is attempted to be supported in mod_mbedtls_ssl_conf_ciphersuites())
  984. * explanation: https://github.com/ARMmbed/mbedtls/issues/1591
  985. * reference: RFC 6460 */
  986. rc = mbedtls_ssl_config_defaults(s->ssl_ctx,
  987. MBEDTLS_SSL_IS_SERVER,
  988. MBEDTLS_SSL_TRANSPORT_STREAM,
  989. MBEDTLS_SSL_PRESET_DEFAULT);
  990. if (0 != rc) {
  991. elog(srv->errh, __FILE__,__LINE__, rc,
  992. "Init of ssl config context defaults failed");
  993. return -1;
  994. }
  995. /* mbedtls defaults minimum accepted SSL/TLS protocol version TLS v1.0
  996. * use of SSL v3 should be avoided, and SSL v2 is not supported */
  997. if (s->ssl_use_sslv3)
  998. mbedtls_ssl_conf_min_version(s->ssl_ctx, MBEDTLS_SSL_MAJOR_VERSION_3,
  999. MBEDTLS_SSL_MINOR_VERSION_0);
  1000. if (!buffer_string_is_empty(s->ssl_cipher_list)) {
  1001. if (!mod_mbedtls_ssl_conf_ciphersuites(srv,s,NULL,s->ssl_cipher_list))
  1002. return -1;
  1003. }
  1004. if (!buffer_string_is_empty(s->ssl_dh_file)) {
  1005. mbedtls_dhm_context dhm;
  1006. mbedtls_dhm_init(&dhm);
  1007. rc = mbedtls_dhm_parse_dhmfile(&dhm, s->ssl_dh_file->ptr);
  1008. if (0 != rc)
  1009. elogf(srv->errh, __FILE__,__LINE__, rc,
  1010. "mbedtls_dhm_parse_dhmfile() %s", s->ssl_dh_file->ptr);
  1011. else {
  1012. rc = mbedtls_ssl_conf_dh_param_ctx(s->ssl_ctx, &dhm);
  1013. if (0 != rc)
  1014. elogf(srv->errh, __FILE__,__LINE__, rc,
  1015. "mbedtls_ssl_conf_dh_param_ctx() %s", s->ssl_dh_file->ptr);
  1016. }
  1017. mbedtls_dhm_free(&dhm);
  1018. if (0 != rc)
  1019. return -1;
  1020. }
  1021. if (!buffer_string_is_empty(s->ssl_ec_curve)) {
  1022. if (!mod_mbedtls_ssl_conf_curves(srv, s, s->ssl_ec_curve))
  1023. return -1;
  1024. }
  1025. /* if needed, attempt to construct certificate chain for server cert */
  1026. if (s->pc->need_chain) {
  1027. s->pc->need_chain = 0; /*(attempt once to complete chain)*/
  1028. if (!mod_mbedtls_construct_crt_chain(s->ssl_pemfile_x509,
  1029. s->ssl_ca_file, srv->errh))
  1030. return -1;
  1031. }
  1032. rc = mbedtls_ssl_conf_own_cert(s->ssl_ctx,
  1033. s->ssl_pemfile_x509, s->ssl_pemfile_pkey);
  1034. if (0 != rc) {
  1035. elogf(srv->errh, __FILE__, __LINE__, rc,
  1036. "PEM cert and private key did not verify (%s) (%s)",
  1037. s->ssl_pemfile->ptr, s->ssl_privkey->ptr);
  1038. return -1;
  1039. }
  1040. #ifdef MBEDTLS_SSL_ALPN
  1041. /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
  1042. static const char *alpn_protos_http_acme[] = {
  1043. "h2"
  1044. ,"http/1.1"
  1045. ,"http/1.0"
  1046. ,"acme-tls/1"
  1047. ,NULL
  1048. };
  1049. static const char *alpn_protos_http[] = {
  1050. "h2"
  1051. ,"http/1.1"
  1052. ,"http/1.0"
  1053. ,NULL
  1054. };
  1055. const char **alpn_protos = (!buffer_string_is_empty(s->ssl_acme_tls_1))
  1056. ? alpn_protos_http_acme
  1057. : alpn_protos_http;
  1058. if (!srv->srvconf.h2proto) ++alpn_protos;
  1059. rc = mbedtls_ssl_conf_alpn_protocols(s->ssl_ctx, alpn_protos);
  1060. if (0 != rc) {
  1061. elog(srv->errh, __FILE__, __LINE__, rc, "error setting ALPN protocols");
  1062. return -1;
  1063. }
  1064. #endif
  1065. if (!s->ssl_use_sslv3 && !s->ssl_use_sslv2)
  1066. mod_mbedtls_ssl_conf_proto(srv, s, NULL, 0); /* min */
  1067. if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) {
  1068. if (0 != mod_mbedtls_ssl_conf_cmd(srv, s)) return -1;
  1069. }
  1070. /* server preference is used (default) unless mbedtls is built with
  1071. * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE defined (not default) */
  1072. #ifndef MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE
  1073. if (!s->ssl_honor_cipher_order)
  1074. log_error(srv->errh, __FILE__, __LINE__,
  1075. "MTLS: "
  1076. "ignoring ssl.honor-cipher-order; mbedtls uses server preference "
  1077. "unless mbedtls built MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE");
  1078. #else
  1079. if (s->ssl_honor_cipher_order)
  1080. log_error(srv->errh, __FILE__, __LINE__,
  1081. "MTLS: "
  1082. "ignoring ssl.honor-cipher-order; mbedtls uses client preference "
  1083. "since mbedtls built MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE");
  1084. #endif
  1085. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  1086. if (s->ssl_session_ticket && !p->ticket_ctx.ticket_lifetime) { /*init once*/
  1087. rc = mbedtls_ssl_ticket_setup(&p->ticket_ctx, mbedtls_ctr_drbg_random,
  1088. &p->ctr_drbg, MBEDTLS_CIPHER_AES_256_GCM,
  1089. 43200); /* ticket timeout: 12 hours */
  1090. if (0 != rc) {
  1091. elog(srv->errh, __FILE__,__LINE__, rc,
  1092. "mbedtls_ssl_ticket_setup()");
  1093. return -1;
  1094. }
  1095. }
  1096. #if defined(MBEDTLS_SSL_TICKET_C)
  1097. if (s->ssl_session_ticket)
  1098. mbedtls_ssl_conf_session_tickets_cb(s->ssl_ctx,
  1099. mbedtls_ssl_ticket_write,
  1100. mbedtls_ssl_ticket_parse,
  1101. &p->ticket_ctx);
  1102. #endif
  1103. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  1104. return 0;
  1105. }
  1106. static int
  1107. mod_mbedtls_set_defaults_sockets(server *srv, plugin_data *p)
  1108. {
  1109. static const config_plugin_keys_t cpk[] = {
  1110. { CONST_STR_LEN("ssl.engine"),
  1111. T_CONFIG_BOOL,
  1112. T_CONFIG_SCOPE_CONNECTION }
  1113. ,{ CONST_STR_LEN("ssl.cipher-list"),
  1114. T_CONFIG_STRING,
  1115. T_CONFIG_SCOPE_CONNECTION }
  1116. ,{ CONST_STR_LEN("ssl.honor-cipher-order"),
  1117. T_CONFIG_BOOL,
  1118. T_CONFIG_SCOPE_CONNECTION }
  1119. ,{ CONST_STR_LEN("ssl.dh-file"),
  1120. T_CONFIG_STRING,
  1121. T_CONFIG_SCOPE_CONNECTION }
  1122. ,{ CONST_STR_LEN("ssl.ec-curve"),
  1123. T_CONFIG_STRING,
  1124. T_CONFIG_SCOPE_CONNECTION }
  1125. ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"),
  1126. T_CONFIG_ARRAY_KVSTRING,
  1127. T_CONFIG_SCOPE_CONNECTION }
  1128. ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */
  1129. T_CONFIG_STRING,
  1130. T_CONFIG_SCOPE_CONNECTION }
  1131. ,{ CONST_STR_LEN("ssl.empty-fragments"),
  1132. T_CONFIG_BOOL,
  1133. T_CONFIG_SCOPE_CONNECTION }
  1134. ,{ CONST_STR_LEN("ssl.use-sslv2"),
  1135. T_CONFIG_BOOL,
  1136. T_CONFIG_SCOPE_CONNECTION }
  1137. ,{ CONST_STR_LEN("ssl.use-sslv3"),
  1138. T_CONFIG_BOOL,
  1139. T_CONFIG_SCOPE_CONNECTION }
  1140. ,{ CONST_STR_LEN("ssl.stek-file"),
  1141. T_CONFIG_STRING,
  1142. T_CONFIG_SCOPE_SERVER }
  1143. ,{ NULL, 0,
  1144. T_CONFIG_UNSET,
  1145. T_CONFIG_SCOPE_UNSET }
  1146. };
  1147. static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 };
  1148. p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx));
  1149. force_assert(p->ssl_ctxs);
  1150. int rc = HANDLER_GO_ON;
  1151. plugin_data_base srvplug;
  1152. memset(&srvplug, 0, sizeof(srvplug));
  1153. plugin_data_base * const ps = &srvplug;
  1154. if (!config_plugin_values_init(srv, ps, cpk, "mod_mbedtls"))
  1155. return HANDLER_ERROR;
  1156. plugin_config_socket defaults;
  1157. memset(&defaults, 0, sizeof(defaults));
  1158. #ifndef MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE
  1159. defaults.ssl_honor_cipher_order = 1;
  1160. #endif
  1161. defaults.ssl_session_ticket = 1; /* enabled by default */
  1162. defaults.ssl_cipher_list = &default_ssl_cipher_list;
  1163. /* process and validate config directives for global and $SERVER["socket"]
  1164. * (init i to 0 if global context; to 1 to skip empty global context) */
  1165. for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) {
  1166. config_cond_info cfginfo;
  1167. config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id);
  1168. int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET);
  1169. int count_not_engine = 0;
  1170. plugin_config_socket conf;
  1171. memcpy(&conf, &defaults, sizeof(conf));
  1172. /*(preserve prior behavior; not inherited)*/
  1173. /*(forcing inheritance might break existing configs where SSL is enabled
  1174. * by default in the global scope, but not $SERVER["socket"]=="*:80") */
  1175. conf.ssl_enabled = 0;
  1176. config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0];
  1177. for (; -1 != cpv->k_id; ++cpv) {
  1178. /* ignore ssl.pemfile (k_id=10); included to process global scope */
  1179. if (!is_socket_scope && cpv->k_id != 10) {
  1180. log_error(srv->errh, __FILE__, __LINE__,
  1181. "MTLS: %s is valid only in global scope or "
  1182. "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k);
  1183. continue;
  1184. }
  1185. ++count_not_engine;
  1186. switch (cpv->k_id) {
  1187. case 0: /* ssl.engine */
  1188. conf.ssl_enabled = (0 != cpv->v.u);
  1189. --count_not_engine;
  1190. break;
  1191. case 1: /* ssl.cipher-list */
  1192. conf.ssl_cipher_list = cpv->v.b;
  1193. break;
  1194. case 2: /* ssl.honor-cipher-order */
  1195. conf.ssl_honor_cipher_order = (0 != cpv->v.u);
  1196. break;
  1197. case 3: /* ssl.dh-file */
  1198. conf.ssl_dh_file = cpv->v.b;
  1199. break;
  1200. case 4: /* ssl.ec-curve */
  1201. conf.ssl_ec_curve = cpv->v.b;
  1202. break;
  1203. case 5: /* ssl.openssl.ssl-conf-cmd */
  1204. *(const array **)&conf.ssl_conf_cmd = cpv->v.a;
  1205. break;
  1206. case 6: /* ssl.pemfile */
  1207. /* ignore here; included to process global scope when
  1208. * ssl.pemfile is set, but ssl.engine is not "enable" */
  1209. break;
  1210. case 7: /* ssl.empty-fragments */
  1211. conf.ssl_empty_fragments = (0 != cpv->v.u);
  1212. log_error(srv->errh, __FILE__, __LINE__,
  1213. "MTLS: ignoring ssl.empty-fragments; openssl-specific "
  1214. "counter-measure against a SSL 3.0/TLS 1.0 protocol "
  1215. "vulnerability affecting CBC ciphers, which cannot be handled"
  1216. " by some broken (Microsoft) SSL implementations.");
  1217. break;
  1218. case 8: /* ssl.use-sslv2 */
  1219. conf.ssl_use_sslv2 = (0 != cpv->v.u);
  1220. log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
  1221. "ssl.use-sslv2 is deprecated and will soon be removed. "
  1222. "Many modern TLS libraries no longer support SSLv2.");
  1223. break;
  1224. case 9: /* ssl.use-sslv3 */
  1225. conf.ssl_use_sslv3 = (0 != cpv->v.u);
  1226. log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
  1227. "ssl.use-sslv3 is deprecated and will soon be removed. "
  1228. "Many modern TLS libraries no longer support SSLv3. "
  1229. "If needed, use: "
  1230. "ssl.openssl.ssl-conf-cmd = (\"MinProtocol\" => \"SSLv3\")");
  1231. break;
  1232. case 10:/* ssl.stek-file */
  1233. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  1234. if (!buffer_is_empty(cpv->v.b))
  1235. p->ssl_stek_file = cpv->v.b->ptr;
  1236. #else
  1237. log_error(srv->errh, __FILE__, __LINE__, "MTLS: "
  1238. "ssl.stek-file ignored; mbedtls library not built with "
  1239. "support for SSL session tickets");
  1240. #endif
  1241. break;
  1242. default:/* should not happen */
  1243. break;
  1244. }
  1245. }
  1246. if (HANDLER_GO_ON != rc) break;
  1247. if (0 == i) memcpy(&defaults, &conf, sizeof(conf));
  1248. if (0 != i && !conf.ssl_enabled) continue;
  1249. /* fill plugin_config_socket with global context then $SERVER["socket"]
  1250. * only for directives directly in current $SERVER["socket"] condition*/
  1251. /*conf.ssl_pemfile_pkey = p->defaults.ssl_pemfile_pkey;*/
  1252. /*conf.ssl_pemfile_x509 = p->defaults.ssl_pemfile_x509;*/
  1253. conf.ssl_verifyclient = p->defaults.ssl_verifyclient;
  1254. conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce;
  1255. conf.ssl_verifyclient_depth = p->defaults.ssl_verifyclient_depth;
  1256. conf.ssl_acme_tls_1 = p->defaults.ssl_acme_tls_1;
  1257. int sidx = ps->cvlist[i].k_id;
  1258. for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) {
  1259. if (p->cvlist[j].k_id != sidx) continue;
  1260. /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/
  1261. cpv = p->cvlist + p->cvlist[j].v.u2[0];
  1262. for (; -1 != cpv->k_id; ++cpv) {
  1263. ++count_not_engine;
  1264. switch (cpv->k_id) {
  1265. case 0: /* ssl.pemfile */
  1266. if (cpv->vtype == T_CONFIG_LOCAL) {
  1267. plugin_cert *pc = cpv->v.v;
  1268. conf.pc = pc;
  1269. conf.ssl_pemfile_pkey = &pc->ssl_pemfile_pkey;
  1270. conf.ssl_pemfile_x509 = &pc->ssl_pemfile_x509;
  1271. conf.ssl_pemfile = pc->ssl_pemfile;
  1272. conf.ssl_privkey = pc->ssl_privkey;
  1273. }
  1274. break;
  1275. case 2: /* ssl.ca-file */
  1276. if (cpv->vtype == T_CONFIG_LOCAL)
  1277. conf.ssl_ca_file = cpv->v.v;
  1278. break;
  1279. case 7: /* ssl.verifyclient.activate */
  1280. conf.ssl_verifyclient = (0 != cpv->v.u);
  1281. break;
  1282. case 8: /* ssl.verifyclient.enforce */
  1283. conf.ssl_verifyclient_enforce = (0 != cpv->v.u);
  1284. break;
  1285. case 9: /* ssl.verifyclient.depth */
  1286. conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
  1287. break;
  1288. case 13:/* ssl.acme-tls-1 */
  1289. conf.ssl_acme_tls_1 = cpv->v.b;
  1290. break;
  1291. default:
  1292. break;
  1293. }
  1294. }
  1295. break;
  1296. }
  1297. if (NULL == conf.ssl_pemfile_x509) {
  1298. if (0 == i && !conf.ssl_enabled) continue;
  1299. if (0 != i) {
  1300. /* inherit ssl settings from global scope
  1301. * (if only ssl.engine = "enable" and no other ssl.* settings)
  1302. * (This is for convenience when defining both IPv4 and IPv6
  1303. * and desiring to inherit the ssl config from global context
  1304. * without having to duplicate the directives)*/
  1305. if (count_not_engine
  1306. || (conf.ssl_enabled && NULL == p->ssl_ctxs[0].ssl_ctx)) {
  1307. log_error(srv->errh, __FILE__, __LINE__,
  1308. "MTLS: ssl.pemfile has to be set in same "
  1309. "$SERVER[\"socket\"] scope as other ssl.* directives, "
  1310. "unless only ssl.engine is set, inheriting ssl.* from "
  1311. "global scope");
  1312. rc = HANDLER_ERROR;
  1313. continue;
  1314. }
  1315. plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
  1316. *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/
  1317. continue;
  1318. }
  1319. /* PEM file is required */
  1320. log_error(srv->errh, __FILE__, __LINE__,
  1321. "MTLS: ssl.pemfile has to be set when ssl.engine = \"enable\"");
  1322. rc = HANDLER_ERROR;
  1323. continue;
  1324. }
  1325. /* (initialize once if module enabled) */
  1326. if (!mod_mbedtls_init_once_mbedtls(srv)) {
  1327. rc = HANDLER_ERROR;
  1328. break;
  1329. }
  1330. /* configure ssl_ctx for socket */
  1331. /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/
  1332. if (0 == network_init_ssl(srv, &conf, p)) {
  1333. plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
  1334. s->ssl_ctx = conf.ssl_ctx;
  1335. s->ciphersuites = conf.ciphersuites;
  1336. s->curves = conf.curves;
  1337. }
  1338. else {
  1339. mbedtls_ssl_config_free(conf.ssl_ctx);
  1340. free(conf.ciphersuites);
  1341. free(conf.curves);
  1342. rc = HANDLER_ERROR;
  1343. }
  1344. }
  1345. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  1346. if (rc == HANDLER_GO_ON && ssl_is_init)
  1347. mod_mbedtls_session_ticket_key_check(p, log_epoch_secs);
  1348. #endif
  1349. free(srvplug.cvlist);
  1350. return rc;
  1351. }
  1352. SETDEFAULTS_FUNC(mod_mbedtls_set_defaults)
  1353. {
  1354. static const config_plugin_keys_t cpk[] = {
  1355. { CONST_STR_LEN("ssl.pemfile"),
  1356. T_CONFIG_STRING,
  1357. T_CONFIG_SCOPE_CONNECTION }
  1358. ,{ CONST_STR_LEN("ssl.privkey"),
  1359. T_CONFIG_STRING,
  1360. T_CONFIG_SCOPE_CONNECTION }
  1361. ,{ CONST_STR_LEN("ssl.ca-file"),
  1362. T_CONFIG_STRING,
  1363. T_CONFIG_SCOPE_CONNECTION }
  1364. ,{ CONST_STR_LEN("ssl.ca-dn-file"),
  1365. T_CONFIG_STRING,
  1366. T_CONFIG_SCOPE_CONNECTION }
  1367. ,{ CONST_STR_LEN("ssl.ca-crl-file"),
  1368. T_CONFIG_STRING,
  1369. T_CONFIG_SCOPE_CONNECTION }
  1370. ,{ CONST_STR_LEN("ssl.read-ahead"),
  1371. T_CONFIG_BOOL,
  1372. T_CONFIG_SCOPE_CONNECTION }
  1373. ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"),
  1374. T_CONFIG_BOOL,
  1375. T_CONFIG_SCOPE_CONNECTION }
  1376. ,{ CONST_STR_LEN("ssl.verifyclient.activate"),
  1377. T_CONFIG_BOOL,
  1378. T_CONFIG_SCOPE_CONNECTION }
  1379. ,{ CONST_STR_LEN("ssl.verifyclient.enforce"),
  1380. T_CONFIG_BOOL,
  1381. T_CONFIG_SCOPE_CONNECTION }
  1382. ,{ CONST_STR_LEN("ssl.verifyclient.depth"),
  1383. T_CONFIG_SHORT,
  1384. T_CONFIG_SCOPE_CONNECTION }
  1385. ,{ CONST_STR_LEN("ssl.verifyclient.username"),
  1386. T_CONFIG_STRING,
  1387. T_CONFIG_SCOPE_CONNECTION }
  1388. ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"),
  1389. T_CONFIG_BOOL,
  1390. T_CONFIG_SCOPE_CONNECTION }
  1391. ,{ CONST_STR_LEN("ssl.acme-tls-1"),
  1392. T_CONFIG_STRING,
  1393. T_CONFIG_SCOPE_CONNECTION }
  1394. ,{ CONST_STR_LEN("debug.log-ssl-noise"),
  1395. T_CONFIG_SHORT,
  1396. T_CONFIG_SCOPE_CONNECTION }
  1397. ,{ NULL, 0,
  1398. T_CONFIG_UNSET,
  1399. T_CONFIG_SCOPE_UNSET }
  1400. };
  1401. plugin_data * const p = p_d;
  1402. p->srv = srv;
  1403. if (!config_plugin_values_init(srv, p, cpk, "mod_mbedtls"))
  1404. return HANDLER_ERROR;
  1405. /* process and validate config directives
  1406. * (init i to 0 if global context; to 1 to skip empty global context) */
  1407. for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
  1408. config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
  1409. config_plugin_value_t *pemfile = NULL;
  1410. config_plugin_value_t *privkey = NULL;
  1411. for (; -1 != cpv->k_id; ++cpv) {
  1412. switch (cpv->k_id) {
  1413. case 0: /* ssl.pemfile */
  1414. if (!buffer_string_is_empty(cpv->v.b)) pemfile = cpv;
  1415. break;
  1416. case 1: /* ssl.privkey */
  1417. if (!buffer_string_is_empty(cpv->v.b)) privkey = cpv;
  1418. break;
  1419. case 2: /* ssl.ca-file */
  1420. case 3: /* ssl.ca-dn-file */
  1421. #if 0 /* defer; not necessary for pemfile parsing */
  1422. if (!mod_mbedtls_init_once_mbedtls(srv)) return HANDLER_ERROR;
  1423. #endif
  1424. if (!buffer_string_is_empty(cpv->v.b)) {
  1425. mbedtls_x509_crt *cacert = calloc(1, sizeof(*cacert));
  1426. force_assert(cacert);
  1427. mbedtls_x509_crt_init(cacert);
  1428. int rc =
  1429. mod_mbedtls_x509_crt_parse_file(cacert, cpv->v.b->ptr);
  1430. if (0 == rc) {
  1431. cpv->vtype = T_CONFIG_LOCAL;
  1432. cpv->v.v = cacert;
  1433. }
  1434. else {
  1435. elogf(srv->errh, __FILE__, __LINE__, rc,
  1436. "%s = %s", cpk[cpv->k_id].k, cpv->v.b->ptr);
  1437. mbedtls_x509_crt_free(cacert);
  1438. free(cacert);
  1439. return HANDLER_ERROR;
  1440. }
  1441. }
  1442. break;
  1443. case 4: /* ssl.ca-crl-file */
  1444. if (!buffer_string_is_empty(cpv->v.b)) {
  1445. mbedtls_x509_crl *crl = malloc(sizeof(*crl));
  1446. force_assert(crl);
  1447. mbedtls_x509_crl_init(crl);
  1448. int rc =
  1449. mod_mbedtls_x509_crl_parse_file(crl, cpv->v.b->ptr);
  1450. if (0 == rc) {
  1451. cpv->vtype = T_CONFIG_LOCAL;
  1452. cpv->v.v = crl;
  1453. }
  1454. else {
  1455. elogf(srv->errh, __FILE__, __LINE__, rc,
  1456. "CRL file read failed (%s)", cpv->v.b->ptr);
  1457. free(crl);
  1458. return HANDLER_ERROR;
  1459. }
  1460. }
  1461. break;
  1462. case 5: /* ssl.read-ahead */
  1463. case 6: /* ssl.disable-client-renegotiation */
  1464. case 7: /* ssl.verifyclient.activate */
  1465. case 8: /* ssl.verifyclient.enforce */
  1466. break;
  1467. case 9: /* ssl.verifyclient.depth */
  1468. if (cpv->v.shrt > 255) {
  1469. log_error(srv->errh, __FILE__, __LINE__,
  1470. "MTLS: %s is absurdly large (%hu); limiting to 255",
  1471. cpk[cpv->k_id].k, cpv->v.shrt);
  1472. cpv->v.shrt = 255;
  1473. }
  1474. break;
  1475. case 10:/* ssl.verifyclient.username */
  1476. case 11:/* ssl.verifyclient.exportcert */
  1477. case 12:/* ssl.acme-tls-1 */
  1478. case 13:/* debug.log-ssl-noise */
  1479. break;
  1480. default:/* should not happen */
  1481. break;
  1482. }
  1483. }
  1484. if (pemfile) {
  1485. if (NULL == privkey) privkey = pemfile;
  1486. pemfile->v.v =
  1487. network_mbedtls_load_pemfile(srv, pemfile->v.b, privkey->v.b);
  1488. if (pemfile->v.v)
  1489. pemfile->vtype = T_CONFIG_LOCAL;
  1490. else
  1491. return HANDLER_ERROR;
  1492. }
  1493. }
  1494. p->defaults.ssl_verifyclient = 0;
  1495. p->defaults.ssl_verifyclient_enforce = 1;
  1496. p->defaults.ssl_verifyclient_depth = 9;
  1497. p->defaults.ssl_verifyclient_export_cert = 0;
  1498. p->defaults.ssl_disable_client_renegotiation = 1;
  1499. p->defaults.ssl_read_ahead = 0;
  1500. /* initialize p->defaults from global config context */
  1501. if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
  1502. const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
  1503. if (-1 != cpv->k_id)
  1504. mod_mbedtls_merge_config(&p->defaults, cpv);
  1505. }
  1506. #ifndef MBEDTLS_ERROR_C
  1507. log_error(srv->errh, __FILE__, __LINE__,
  1508. "MTLS: No error strings available. "
  1509. "Compile mbedtls with MBEDTLS_ERROR_C to enable.");
  1510. #endif
  1511. return mod_mbedtls_set_defaults_sockets(srv, p);
  1512. }
  1513. /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
  1514. *
  1515. * buffer is allocated once, is NOT realloced (note: not thread-safe)
  1516. * */
  1517. /* copy small mem chunks into single large buffer
  1518. * before mbedtls_ssl_write() to reduce number times
  1519. * write() called underneath mbedtls_ssl_write() and
  1520. * potentially reduce number of packets generated if TCP_NODELAY */
  1521. __attribute_cold__
  1522. static int
  1523. mod_mbedtls_ssl_write_err(connection *con, handler_ctx *hctx, int wr, size_t wr_len)
  1524. {
  1525. switch (wr) {
  1526. case MBEDTLS_ERR_SSL_WANT_READ:
  1527. con->is_readable = -1;
  1528. break; /* try again later */
  1529. case MBEDTLS_ERR_SSL_WANT_WRITE:
  1530. con->is_writable = -1;
  1531. break; /* try again later */
  1532. case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
  1533. case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
  1534. break; /* try again later */
  1535. case MBEDTLS_ERR_NET_CONN_RESET:
  1536. if (hctx->conf.ssl_log_noise)
  1537. elog(hctx->r->conf.errh, __FILE__, __LINE__, wr,
  1538. "peer closed connection");
  1539. return -1;
  1540. default:
  1541. elog(hctx->r->conf.errh, __FILE__, __LINE__, wr, __func__);
  1542. return -1;
  1543. }
  1544. if (0 != hctx->ssl.out_left) /* partial write; save attempted wr_len */
  1545. hctx->pending_write = wr_len;
  1546. return 0; /* try again later */
  1547. }
  1548. static int
  1549. mod_mbedtls_close_notify(handler_ctx *hctx);
  1550. static int
  1551. connection_write_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
  1552. {
  1553. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
  1554. mbedtls_ssl_context * const ssl = &hctx->ssl;
  1555. if (hctx->pending_write) {
  1556. int wr = (int)hctx->pending_write;
  1557. if (0 != ssl->out_left) {
  1558. /*(would prefer mbedtls_ssl_flush_output() from ssl_internal.h)*/
  1559. size_t data_len = hctx->pending_write;
  1560. wr = mbedtls_ssl_write(ssl, NULL, data_len);
  1561. if (wr <= 0)
  1562. return mod_mbedtls_ssl_write_err(con, hctx, wr, data_len);
  1563. max_bytes -= wr;
  1564. }
  1565. hctx->pending_write = 0;
  1566. chunkqueue_mark_written(cq, wr);
  1567. }
  1568. if (0 != hctx->close_notify) return mod_mbedtls_close_notify(hctx);
  1569. chunkqueue_remove_finished_chunks(cq);
  1570. const int lim = mbedtls_ssl_get_max_out_record_payload(ssl);
  1571. if (lim < 0) return mod_mbedtls_ssl_write_err(con, hctx, lim, 0);
  1572. log_error_st * const errh = hctx->errh;
  1573. while (max_bytes > 0 && !chunkqueue_is_empty(cq)) {
  1574. char *data = local_send_buffer;
  1575. uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes
  1576. ? LOCAL_SEND_BUFSIZE
  1577. : (uint32_t)max_bytes;
  1578. int wr;
  1579. if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1;
  1580. /* mbedtls_ssl_write() copies the data, up to max record size, but if
  1581. * (temporarily) unable to write the entire record, it is documented
  1582. * that the caller must call mbedtls_ssl_write() again, later, with the
  1583. * same arguments. This appears to be because mbedtls_ssl_context does
  1584. * not keep track of the original size of the caller data that
  1585. * mbedtls_ssl_write() attempted to write (and may have transformed to
  1586. * a different size). The func may return MBEDTLS_ERR_SSL_WANT_READ or
  1587. * MBEDTLS_ERR_SSL_WANT_WRITE to indicate that the caller should wait
  1588. * for the fd to be readable/writable before calling the func again,
  1589. * which is why those (temporary) errors are returned instead of telling
  1590. * the caller that the data was successfully copied. When the record is
  1591. * written successfully, the return value is supposed to indicate the
  1592. * number of (originally submitted) bytes written, but since that value
  1593. * is unknown (not saved), the caller's len parameter is reflected back,
  1594. * which is why the caller must call the func again with the same args.
  1595. * Additionally, to be accurate, the size must fit into a record which
  1596. * is why we restrict ourselves to sending max out record payload each
  1597. * iteration.
  1598. */
  1599. int wr_total = 0;
  1600. do {
  1601. size_t wr_len = (data_len > (size_t)lim) ? (size_t)lim : data_len;
  1602. wr = mbedtls_ssl_write(ssl, (const unsigned char *)data, wr_len);
  1603. if (wr <= 0) {
  1604. if (wr_total) chunkqueue_mark_written(cq, wr_total);
  1605. return mod_mbedtls_ssl_write_err(con, hctx, wr, wr_len);
  1606. }
  1607. wr_total += wr;
  1608. data += wr;
  1609. } while ((data_len -= wr));
  1610. chunkqueue_mark_written(cq, wr_total);
  1611. max_bytes -= wr_total;
  1612. }
  1613. return 0;
  1614. }
  1615. static int
  1616. mod_mbedtls_ssl_handshake (handler_ctx *hctx)
  1617. {
  1618. int rc = 0;
  1619. /* overwrite callback with hctx each time we enter here, before handshake
  1620. * (Some callbacks are on mbedtls_ssl_config, not mbedtls_ssl_context)
  1621. * (Not thread-safe if config (mbedtls_ssl_config *ssl_ctx) is shared)
  1622. * (XXX: there is probably a better way to do this...) */
  1623. /* (alternative: save ssl_ctx in hctx in mod_mbedtls_handle_con_accept()) */
  1624. mbedtls_ssl_config *ssl_ctx;
  1625. *(const mbedtls_ssl_config **)&ssl_ctx = hctx->ssl.conf;
  1626. #ifdef MBEDTLS_SSL_SERVER_NAME_INDICATION
  1627. mbedtls_ssl_conf_sni(ssl_ctx, mod_mbedtls_SNI, hctx);
  1628. #endif
  1629. if (hctx->ssl.state < MBEDTLS_SSL_SERVER_HELLO) {
  1630. while (hctx->ssl.state != MBEDTLS_SSL_SERVER_HELLO
  1631. && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  1632. rc = mbedtls_ssl_handshake_step(&hctx->ssl);
  1633. if (0 != rc) break;
  1634. }
  1635. if (0 == rc && hctx->ssl.state == MBEDTLS_SSL_SERVER_HELLO) {
  1636. #ifdef MBEDTLS_SSL_ALPN
  1637. const char *alpn = mbedtls_ssl_get_alpn_protocol(&hctx->ssl);
  1638. if (NULL != alpn)
  1639. rc = mod_mbedtls_alpn_select_cb(hctx, alpn);
  1640. #endif
  1641. }
  1642. }
  1643. /* overwrite callback with hctx each time we enter here, before handshake
  1644. * (Some callbacks are on mbedtls_ssl_config, not mbedtls_ssl_context)
  1645. * (Not thread-safe if config (mbedtls_ssl_config *ssl_ctx) is shared)
  1646. * (XXX: there is probably a better way to do this...) */
  1647. if (0 == rc && hctx->conf.ssl_verifyclient
  1648. && hctx->ssl.state >= MBEDTLS_SSL_SERVER_HELLO /*(after SNI and ALPN)*/
  1649. && hctx->ssl.state <= MBEDTLS_SSL_SERVER_HELLO_DONE
  1650. && hctx->alpn != MOD_MBEDTLS_ALPN_ACME_TLS_1) { /*(not "acme-tls/1")*/
  1651. int mode = (hctx->conf.ssl_verifyclient_enforce)
  1652. ? MBEDTLS_SSL_VERIFY_REQUIRED
  1653. : MBEDTLS_SSL_VERIFY_OPTIONAL;
  1654. mbedtls_ssl_set_hs_authmode(&hctx->ssl, mode);
  1655. while (hctx->ssl.state != MBEDTLS_SSL_CERTIFICATE_REQUEST
  1656. && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  1657. rc = mbedtls_ssl_handshake_step(&hctx->ssl);
  1658. if (0 != rc) break;
  1659. }
  1660. if (0 == rc && hctx->ssl.state == MBEDTLS_SSL_CERTIFICATE_REQUEST) {
  1661. rc = mod_mbedtls_conf_verify(hctx, ssl_ctx);
  1662. if (0 == rc)
  1663. rc = mbedtls_ssl_handshake_step(&hctx->ssl);
  1664. /* reconfigure CA trust chain after sending client certificate
  1665. * request (if ssl_ca_dn_file is set), before client certificate
  1666. * verification (MBEDTLS_SSL_CERTIFICATE_VERIFY) */
  1667. if (0 == rc && hctx->conf.ssl_ca_dn_file
  1668. && hctx->ssl.state == MBEDTLS_SSL_SERVER_HELLO_DONE) {
  1669. mbedtls_ssl_context * const ssl = &hctx->ssl;
  1670. mbedtls_x509_crt *ca_certs = hctx->conf.ssl_ca_file;
  1671. mbedtls_x509_crl *ca_crl = hctx->conf.ssl_ca_crl_file;
  1672. mbedtls_ssl_set_hs_ca_chain(ssl, ca_certs, ca_crl);
  1673. }
  1674. }
  1675. }
  1676. if (0 == rc && hctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
  1677. rc = mbedtls_ssl_handshake(&hctx->ssl);
  1678. }
  1679. switch (rc) {
  1680. case 0:
  1681. hctx->handshake_done = 1;
  1682. #ifdef MBEDTLS_SSL_ALPN
  1683. if (hctx->alpn == MOD_MBEDTLS_ALPN_ACME_TLS_1) {
  1684. /* Once TLS handshake is complete, return -1 to result in
  1685. * CON_STATE_ERROR so that socket connection is quickly closed */
  1686. return -1;
  1687. }
  1688. hctx->alpn = 0;
  1689. #endif
  1690. return 1; /* continue reading */
  1691. case MBEDTLS_ERR_SSL_WANT_WRITE:
  1692. hctx->con->is_writable = -1;
  1693. __attribute_fallthrough__
  1694. case MBEDTLS_ERR_SSL_WANT_READ:
  1695. hctx->con->is_readable = 0;
  1696. return 0;
  1697. case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
  1698. case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
  1699. return 0;
  1700. case MBEDTLS_ERR_SSL_CLIENT_RECONNECT:
  1701. return -1;
  1702. case MBEDTLS_ERR_NET_CONN_RESET:
  1703. case MBEDTLS_ERR_SSL_CONN_EOF:
  1704. if (!hctx->conf.ssl_log_noise) return -1;
  1705. __attribute_fallthrough__
  1706. default:
  1707. elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, __func__);
  1708. return -1;
  1709. }
  1710. }
  1711. static int
  1712. connection_read_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
  1713. {
  1714. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
  1715. int len;
  1716. char *mem = NULL;
  1717. size_t mem_len = 0;
  1718. UNUSED(max_bytes);
  1719. if (0 != hctx->close_notify) return mod_mbedtls_close_notify(hctx);
  1720. if (!hctx->handshake_done) {
  1721. int rc = mod_mbedtls_ssl_handshake(hctx);
  1722. if (1 != rc) return rc; /* !hctx->handshake_done; not done, or error */
  1723. }
  1724. do {
  1725. len = mbedtls_ssl_get_bytes_avail(&hctx->ssl);
  1726. mem_len = len < 2048 ? 2048 : (size_t)len;
  1727. chunk * const ckpt = cq->last;
  1728. mem = chunkqueue_get_memory(cq, &mem_len);
  1729. len = mbedtls_ssl_read(&hctx->ssl, (unsigned char *)mem, mem_len);
  1730. if (len > 0) {
  1731. chunkqueue_use_memory(cq, ckpt, len);
  1732. con->bytes_read += len;
  1733. } else {
  1734. chunkqueue_use_memory(cq, ckpt, 0);
  1735. }
  1736. } while (len > 0
  1737. && mbedtls_ssl_check_pending(&hctx->ssl));
  1738. if (len < 0) {
  1739. int rc = len;
  1740. request_st * const r = &con->request;
  1741. switch (rc) {
  1742. case MBEDTLS_ERR_SSL_WANT_WRITE:
  1743. con->is_writable = -1;
  1744. __attribute_fallthrough__
  1745. case MBEDTLS_ERR_SSL_WANT_READ:
  1746. con->is_readable = 0;
  1747. return 0;
  1748. case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
  1749. case MBEDTLS_ERR_SSL_CONN_EOF:
  1750. /* XXX: future: save state to avoid future read after response? */
  1751. con->is_readable = 0;
  1752. r->keep_alive = 0;
  1753. return -2;
  1754. case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
  1755. case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
  1756. return 0;
  1757. case MBEDTLS_ERR_SSL_CLIENT_RECONNECT:
  1758. return -1;
  1759. case MBEDTLS_ERR_NET_CONN_RESET:
  1760. if (!hctx->conf.ssl_log_noise) return -1;
  1761. __attribute_fallthrough__
  1762. default:
  1763. elog(hctx->errh, __FILE__, __LINE__, rc, "Reading mbedtls");
  1764. return -1;
  1765. }
  1766. } else if (len == 0) {
  1767. con->is_readable = 0;
  1768. /* the other end closed the connection -> KEEP-ALIVE */
  1769. return -2;
  1770. } else {
  1771. return 0;
  1772. }
  1773. }
  1774. static void
  1775. mod_mbedtls_debug_cb(void *ctx, int level,
  1776. const char *file, int line,
  1777. const char *str)
  1778. {
  1779. if (level < (intptr_t)ctx) /* level */
  1780. log_error(plugin_data_singleton->srv->errh,file,line,"MTLS: %s",str);
  1781. }
  1782. CONNECTION_FUNC(mod_mbedtls_handle_con_accept)
  1783. {
  1784. server_socket *srv_sock = con->srv_socket;
  1785. if (!srv_sock->is_ssl) return HANDLER_GO_ON;
  1786. plugin_data *p = p_d;
  1787. handler_ctx * const hctx = handler_ctx_init();
  1788. request_st * const r = &con->request;
  1789. hctx->r = r;
  1790. hctx->con = con;
  1791. hctx->tmp_buf = con->srv->tmp_buf;
  1792. hctx->errh = r->conf.errh;
  1793. con->plugin_ctx[p->id] = hctx;
  1794. plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx;
  1795. mbedtls_ssl_init(&hctx->ssl);
  1796. int rc = mbedtls_ssl_setup(&hctx->ssl, s->ssl_ctx);
  1797. if (0 == rc) {
  1798. con->network_read = connection_read_cq_ssl;
  1799. con->network_write = connection_write_cq_ssl;
  1800. con->proto_default_port = 443; /* "https" */
  1801. mod_mbedtls_patch_config(r, &hctx->conf);
  1802. }
  1803. else {
  1804. elog(r->conf.errh, __FILE__, __LINE__, rc, "ssl_setup() failed");
  1805. return HANDLER_ERROR;
  1806. }
  1807. mbedtls_ssl_set_bio(&hctx->ssl, (mbedtls_net_context *)&con->fd,
  1808. mbedtls_net_send, mbedtls_net_recv, NULL);
  1809. /* (mbedtls_ssl_config *) is shared across multiple connections, which may
  1810. * overlap, and so this debug setting is not reset upon connection close.
  1811. * Once enabled, debug hook will remain so for this mbedtls_ssl_config */
  1812. if (hctx->conf.ssl_log_noise) /* volume level for debug message callback */
  1813. mbedtls_ssl_conf_dbg(s->ssl_ctx, mod_mbedtls_debug_cb,
  1814. (void *)(intptr_t)hctx->conf.ssl_log_noise);
  1815. /* (mbedtls_ssl_config *) is shared across multiple connections, which may
  1816. * overlap, and so renegotiation setting is not reset upon connection close.
  1817. * Once enabled, renegotiation will remain so for this mbedtls_ssl_config.
  1818. * mbedtls defaults to disable client renegotiation
  1819. * (MBEDTLS_LEGACY_SSL_RENEGOTIATION_DISABLED)
  1820. * and it is recommended to leave it disabled (lighttpd mbedtls default) */
  1821. #ifdef MBEDTLS_LEGACY_SSL_RENEGOTIATION_ENABLED
  1822. if (!hctx->conf.ssl_disable_client_renegotiation)
  1823. mbedtls_legacy_ssl_conf_renegotiation(s->ssl_ctx,
  1824. MBEDTLS_LEGACY_SSL_RENEGOTIATION_ENABLED);
  1825. #endif
  1826. return HANDLER_GO_ON;
  1827. }
  1828. static void
  1829. mod_mbedtls_detach(handler_ctx *hctx)
  1830. {
  1831. /* step aside from further SSL processing
  1832. * (used after handle_connection_shut_wr hook) */
  1833. /* future: might restore prior network_read and network_write fn ptrs */
  1834. hctx->con->is_ssl_sock = 0;
  1835. /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
  1836. if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
  1837. hctx->close_notify = 1;
  1838. }
  1839. CONNECTION_FUNC(mod_mbedtls_handle_con_shut_wr)
  1840. {
  1841. plugin_data *p = p_d;
  1842. handler_ctx *hctx = con->plugin_ctx[p->id];
  1843. if (NULL == hctx) return HANDLER_GO_ON;
  1844. hctx->close_notify = -2;
  1845. if (hctx->handshake_done) {
  1846. mod_mbedtls_close_notify(hctx);
  1847. }
  1848. else {
  1849. mod_mbedtls_detach(hctx);
  1850. }
  1851. return HANDLER_GO_ON;
  1852. }
  1853. static int
  1854. mod_mbedtls_close_notify (handler_ctx *hctx)
  1855. {
  1856. if (1 == hctx->close_notify) return -2;
  1857. int rc = mbedtls_ssl_close_notify(&hctx->ssl);
  1858. switch (rc) {
  1859. case 0:
  1860. mod_mbedtls_detach(hctx);
  1861. return -2;
  1862. case MBEDTLS_ERR_SSL_WANT_READ:
  1863. case MBEDTLS_ERR_SSL_WANT_WRITE:
  1864. return 0;
  1865. default:
  1866. elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
  1867. "mbedtls_ssl_close_notify()");
  1868. __attribute_fallthrough__
  1869. case MBEDTLS_ERR_NET_CONN_RESET:
  1870. mbedtls_ssl_session_reset(&hctx->ssl);
  1871. mod_mbedtls_detach(hctx);
  1872. return -1;
  1873. }
  1874. }
  1875. CONNECTION_FUNC(mod_mbedtls_handle_con_close)
  1876. {
  1877. plugin_data *p = p_d;
  1878. handler_ctx *hctx = con->plugin_ctx[p->id];
  1879. if (NULL != hctx) {
  1880. con->plugin_ctx[p->id] = NULL;
  1881. if (1 != hctx->close_notify)
  1882. mod_mbedtls_close_notify(hctx); /*(one final try)*/
  1883. handler_ctx_free(hctx);
  1884. }
  1885. return HANDLER_GO_ON;
  1886. }
  1887. #if defined(MBEDTLS_PEM_WRITE_C)
  1888. __attribute_noinline__
  1889. static void
  1890. https_add_ssl_client_cert (request_st * const r, const mbedtls_x509_crt * const peer)
  1891. {
  1892. #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
  1893. #define PEM_END_CRT "-----END CERTIFICATE-----\n"
  1894. unsigned char buf[4096];
  1895. size_t olen;
  1896. if (0 == mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
  1897. peer->raw.p, peer->raw.len,
  1898. buf, sizeof(buf), &olen))
  1899. http_header_env_set(r,
  1900. CONST_STR_LEN("SSL_CLIENT_CERT"),
  1901. (char *)buf, olen);
  1902. }
  1903. #endif
  1904. static void
  1905. https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx)
  1906. {
  1907. /* Note: starting with mbedtls-2.17.0, peer cert is not available here if
  1908. * MBEDTLS_SSL_KEEP_PEER_CERTIFICATE *is not* defined at compile time,
  1909. * though default behavior is to have it defined. However, since earlier
  1910. * versions do keep the cert, but not set this define, attempt to retrieve
  1911. * the peer cert and check for NULL before using it. */
  1912. const mbedtls_x509_crt *crt = mbedtls_ssl_get_peer_cert(&hctx->ssl);
  1913. buffer * const tb = r->tmp_buf;
  1914. char buf[512];
  1915. int n;
  1916. uint32_t rc = (NULL != crt)
  1917. ? mbedtls_ssl_get_verify_result(&hctx->ssl)
  1918. : 0xFFFFFFFF;
  1919. if (0xFFFFFFFF == rc) { /*(e.g. no cert, or verify result not available)*/
  1920. http_header_env_set(r,
  1921. CONST_STR_LEN("SSL_CLIENT_VERIFY"),
  1922. CONST_STR_LEN("NONE"));
  1923. return;
  1924. }
  1925. else if (0 != rc) {
  1926. /* get failure string and translate newline to ':', removing last one */
  1927. n = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", rc);
  1928. buffer_copy_string_len(tb, CONST_STR_LEN("FAILED:"));
  1929. if (n > 0) {
  1930. for (char *nl = buf; NULL != (nl = strchr(nl, '\n')); ++nl)
  1931. nl[0] = ('\0' == nl[1] ? (--n, '\0') : ':');
  1932. buffer_append_string_len(tb, buf, n);
  1933. }
  1934. http_header_env_set(r,
  1935. CONST_STR_LEN("SSL_CLIENT_VERIFY"),
  1936. CONST_BUF_LEN(tb));
  1937. return;
  1938. }
  1939. else {
  1940. http_header_env_set(r,
  1941. CONST_STR_LEN("SSL_CLIENT_VERIFY"),
  1942. CONST_STR_LEN("SUCCESS"));
  1943. }
  1944. n = mbedtls_x509_dn_gets(buf, sizeof(buf), &crt->subject);
  1945. if (n > 0 && n < (int)sizeof(buf)) {
  1946. http_header_env_set(r,
  1947. CONST_STR_LEN("SSL_CLIENT_S_DN"),
  1948. buf, n);
  1949. }
  1950. /* add components of client Subject DN */
  1951. /* code block is similar to mbedtls_x509_dn_gets() */
  1952. /*(reuse buf; sizeof(buf) > MBEDTLS_X509_MAX_DN_NAME_SIZE, which is 256)*/
  1953. buffer_copy_string_len(tb, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
  1954. const mbedtls_x509_name *name = &crt->subject;
  1955. while (name != NULL) {
  1956. if (!name->oid.p) {
  1957. name = name->next;
  1958. continue;
  1959. }
  1960. const char *short_name = NULL;
  1961. if (0 != mbedtls_oid_get_attr_short_name(&name->oid, &short_name))
  1962. continue;
  1963. buffer_string_set_length(tb, sizeof("SSL_CLIENT_S_DN_")-1);
  1964. buffer_append_string(tb, short_name);
  1965. const mbedtls_x509_name *nm = name;
  1966. n = 0;
  1967. do {
  1968. if (nm != name && n < (int)sizeof(buf)-1)
  1969. buf[n++] = ',';
  1970. for (size_t i = 0; i < nm->val.len && n < (int)sizeof(buf)-1; ++n) {
  1971. unsigned char c = nm->val.p[i];
  1972. buf[n] = (c < 32 || c == 127 || (c > 128 && c < 160)) ? '?' : c;
  1973. }
  1974. buf[n] = '\0';
  1975. } while (nm->next_merged && nm->next && (nm = nm->next));
  1976. if (n == sizeof(buf)-1)
  1977. while (nm->next_merged && nm->next) nm = nm->next;
  1978. name = nm->next;
  1979. http_header_env_set(r,
  1980. CONST_BUF_LEN(tb),
  1981. buf, n);
  1982. }
  1983. n = mbedtls_x509_serial_gets(buf, sizeof(buf), &crt->serial);
  1984. if (n > 0 && n < (int)sizeof(buf)) {
  1985. http_header_env_set(r,
  1986. CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
  1987. buf, n);
  1988. }
  1989. if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
  1990. /* pick one of the exported values as "REMOTE_USER", for example
  1991. * ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
  1992. * or
  1993. * ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
  1994. */
  1995. const buffer *varname = hctx->conf.ssl_verifyclient_username;
  1996. const buffer *vb = http_header_env_get(r, CONST_BUF_LEN(varname));
  1997. if (vb) { /* same as http_auth.c:http_auth_setenv() */
  1998. http_header_env_set(r,
  1999. CONST_STR_LEN("REMOTE_USER"),
  2000. CONST_BUF_LEN(vb));
  2001. http_header_env_set(r,
  2002. CONST_STR_LEN("AUTH_TYPE"),
  2003. CONST_STR_LEN("SSL_CLIENT_VERIFY"));
  2004. }
  2005. }
  2006. #if defined(MBEDTLS_PEM_WRITE_C)
  2007. /* if (NULL != crt) (e.g. not PSK-based ciphersuite) */
  2008. if (hctx->conf.ssl_verifyclient_export_cert && NULL != crt)
  2009. https_add_ssl_client_cert(r, crt);
  2010. #endif
  2011. }
  2012. static void
  2013. http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx)
  2014. {
  2015. #if 1
  2016. /* XXX: reaching into ssl_internal.h here for mbedtls_ssl_transform */
  2017. const mbedtls_cipher_info_t *cipher_info =
  2018. hctx->ssl.transform->cipher_ctx_enc.cipher_info;
  2019. #else
  2020. const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  2021. mbedtls_ssl_ciphersuite_from_id(hctx->ssl.session->ciphersuite);
  2022. const mbedtls_cipher_info_t *cipher_info =
  2023. mbedtls_cipher_info_from_type(ciphersuite_info->cipher);
  2024. #endif
  2025. const char *s;
  2026. s = mbedtls_ssl_get_version(&hctx->ssl);
  2027. http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s));
  2028. /*s = ciphersuite_info->name;*/ /*mbedtls_ssl_get_ciphersuite(&hctx->ssl);*/
  2029. s = cipher_info->name;
  2030. http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s));
  2031. if (cipher_info != NULL) {
  2032. /* SSL_CIPHER_ALGKEYSIZE - Number of cipher bits (possible) */
  2033. /* SSL_CIPHER_USEKEYSIZE - Number of cipher bits (actually used) */
  2034. /* XXX: is usekeysize correct? XXX: reaching into ssl_internal.h here */
  2035. int usekeysize = hctx->ssl.transform->cipher_ctx_enc.key_bitlen;
  2036. unsigned int algkeysize = cipher_info->key_bitlen;
  2037. char buf[LI_ITOSTRING_LENGTH];
  2038. http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
  2039. buf, li_itostrn(buf, sizeof(buf), usekeysize));
  2040. http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
  2041. buf, li_utostrn(buf, sizeof(buf), algkeysize));
  2042. }
  2043. }
  2044. REQUEST_FUNC(mod_mbedtls_handle_request_env)
  2045. {
  2046. plugin_data *p = p_d;
  2047. /* simple flag for request_env_patched */
  2048. if (r->plugin_ctx[p->id]) return HANDLER_GO_ON;
  2049. handler_ctx *hctx = r->con->plugin_ctx[p->id];
  2050. if (NULL == hctx) return HANDLER_GO_ON;
  2051. r->plugin_ctx[p->id] = (void *)(uintptr_t)1u;
  2052. http_cgi_ssl_env(r, hctx);
  2053. if (hctx->conf.ssl_verifyclient) {
  2054. https_add_ssl_client_entries(r, hctx);
  2055. }
  2056. return HANDLER_GO_ON;
  2057. }
  2058. REQUEST_FUNC(mod_mbedtls_handle_uri_raw)
  2059. {
  2060. /* mod_mbedtls must be loaded prior to mod_auth
  2061. * if mod_mbedtls is configured to set REMOTE_USER based on client cert */
  2062. /* mod_mbedtls must be loaded after mod_extforward
  2063. * if mod_mbedtls config is based on lighttpd.conf remote IP conditional
  2064. * using remote IP address set by mod_extforward, *unless* PROXY protocol
  2065. * is enabled with extforward.hap-PROXY = "enable", in which case the
  2066. * reverse is true: mod_extforward must be loaded after mod_mbedtls */
  2067. plugin_data *p = p_d;
  2068. handler_ctx *hctx = r->con->plugin_ctx[p->id];
  2069. if (NULL == hctx) return HANDLER_GO_ON;
  2070. mod_mbedtls_patch_config(r, &hctx->conf);
  2071. if (hctx->conf.ssl_verifyclient) {
  2072. mod_mbedtls_handle_request_env(r, p);
  2073. }
  2074. return HANDLER_GO_ON;
  2075. }
  2076. REQUEST_FUNC(mod_mbedtls_handle_request_reset)
  2077. {
  2078. plugin_data *p = p_d;
  2079. r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */
  2080. return HANDLER_GO_ON;
  2081. }
  2082. TRIGGER_FUNC(mod_mbedtls_handle_trigger) {
  2083. plugin_data * const p = p_d;
  2084. const time_t cur_ts = log_epoch_secs;
  2085. if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/
  2086. UNUSED(srv);
  2087. UNUSED(p);
  2088. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  2089. mod_mbedtls_session_ticket_key_check(p, cur_ts);
  2090. #endif
  2091. return HANDLER_GO_ON;
  2092. }
  2093. int mod_mbedtls_plugin_init (plugin *p);
  2094. int mod_mbedtls_plugin_init (plugin *p)
  2095. {
  2096. p->version = LIGHTTPD_VERSION_ID;
  2097. p->name = "mbedtls";
  2098. p->init = mod_mbedtls_init;
  2099. p->cleanup = mod_mbedtls_free;
  2100. p->priv_defaults= mod_mbedtls_set_defaults;
  2101. p->handle_connection_accept = mod_mbedtls_handle_con_accept;
  2102. p->handle_connection_shut_wr = mod_mbedtls_handle_con_shut_wr;
  2103. p->handle_connection_close = mod_mbedtls_handle_con_close;
  2104. p->handle_uri_raw = mod_mbedtls_handle_uri_raw;
  2105. p->handle_request_env = mod_mbedtls_handle_request_env;
  2106. p->handle_request_reset = mod_mbedtls_handle_request_reset;
  2107. p->handle_trigger = mod_mbedtls_handle_trigger;
  2108. return 0;
  2109. }
  2110. /* cipher suites (taken from mbedtls/ssl_ciphersuites.[ch]) */
  2111. static const int suite_CHACHAPOLY_ephemeral[] = {
  2112. /* Chacha-Poly ephemeral suites */
  2113. MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  2114. MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  2115. MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  2116. };
  2117. static const int suite_AES_256_ephemeral[] = {
  2118. /* All AES-256 ephemeral suites */
  2119. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  2120. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  2121. MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
  2122. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
  2123. MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM,
  2124. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,