mbedtls-server.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010 - 2019 Andy Green <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to
  8. * deal in the Software without restriction, including without limitation the
  9. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. * sell copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. * IN THE SOFTWARE.
  23. */
  24. #include "private-lib-core.h"
  25. #include <mbedtls/x509_csr.h>
  26. #include <errno.h>
  27. int
  28. lws_tls_server_client_cert_verify_config(struct lws_vhost *vh)
  29. {
  30. int verify_options = SSL_VERIFY_PEER;
  31. /* as a server, are we requiring clients to identify themselves? */
  32. if (!lws_check_opt(vh->options,
  33. LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT)) {
  34. lwsl_notice("no client cert required\n");
  35. return 0;
  36. }
  37. /*
  38. * The wrapper has this messed-up mapping:
  39. *
  40. * else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  41. * mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
  42. *
  43. * ie the meaning is inverted. So where we should test for ! we don't
  44. */
  45. if (lws_check_opt(vh->options, LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
  46. verify_options = SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  47. lwsl_notice("%s: vh %s requires client cert %d\n", __func__, vh->name,
  48. verify_options);
  49. SSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options, NULL);
  50. return 0;
  51. }
  52. static int
  53. lws_mbedtls_sni_cb(void *arg, mbedtls_ssl_context *mbedtls_ctx,
  54. const unsigned char *servername, size_t len)
  55. {
  56. SSL *ssl = SSL_SSL_from_mbedtls_ssl_context(mbedtls_ctx);
  57. struct lws_context *context = (struct lws_context *)arg;
  58. struct lws_vhost *vhost, *vh;
  59. lwsl_notice("%s: %s\n", __func__, servername);
  60. /*
  61. * We can only get ssl accepted connections by using a vhost's ssl_ctx
  62. * find out which listening one took us and only match vhosts on the
  63. * same port.
  64. */
  65. vh = context->vhost_list;
  66. while (vh) {
  67. if (!vh->being_destroyed &&
  68. vh->tls.ssl_ctx == SSL_get_SSL_CTX(ssl))
  69. break;
  70. vh = vh->vhost_next;
  71. }
  72. if (!vh) {
  73. assert(vh); /* can't match the incoming vh? */
  74. return 0;
  75. }
  76. vhost = lws_select_vhost(context, vh->listen_port,
  77. (const char *)servername);
  78. if (!vhost) {
  79. lwsl_info("SNI: none: %s:%d\n", servername, vh->listen_port);
  80. return 0;
  81. }
  82. lwsl_info("SNI: Found: %s:%d at vhost '%s'\n", servername,
  83. vh->listen_port, vhost->name);
  84. if (!vhost->tls.ssl_ctx) {
  85. lwsl_err("%s: vhost %s matches SNI but no valid cert\n",
  86. __func__, vh->name);
  87. return 1;
  88. }
  89. /* select the ssl ctx from the selected vhost for this conn */
  90. SSL_set_SSL_CTX(ssl, vhost->tls.ssl_ctx);
  91. return 0;
  92. }
  93. int
  94. lws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi,
  95. const char *cert, const char *private_key,
  96. const char *mem_cert, size_t mem_cert_len,
  97. const char *mem_privkey, size_t mem_privkey_len)
  98. {
  99. lws_filepos_t flen;
  100. uint8_t *p = NULL;
  101. long err;
  102. int n;
  103. if ((!cert || !private_key) && (!mem_cert || !mem_privkey)) {
  104. lwsl_notice("%s: no usable input\n", __func__);
  105. return 0;
  106. }
  107. n = lws_tls_generic_cert_checks(vhost, cert, private_key);
  108. if (n == LWS_TLS_EXTANT_NO && (!mem_cert || !mem_privkey))
  109. return 0;
  110. /*
  111. * we can't read the root-privs files. But if mem_cert is provided,
  112. * we should use that.
  113. */
  114. if (n == LWS_TLS_EXTANT_NO)
  115. n = LWS_TLS_EXTANT_ALTERNATIVE;
  116. if (n == LWS_TLS_EXTANT_ALTERNATIVE && (!mem_cert || !mem_privkey))
  117. return 1; /* no alternative */
  118. if (n == LWS_TLS_EXTANT_ALTERNATIVE) {
  119. /*
  120. * Although we have prepared update certs, we no longer have
  121. * the rights to read our own cert + key we saved.
  122. *
  123. * If we were passed copies in memory buffers, use those
  124. * instead.
  125. *
  126. * The passed memory-buffer cert image is in DER, and the
  127. * memory-buffer private key image is PEM.
  128. */
  129. cert = NULL;
  130. private_key = NULL;
  131. }
  132. if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, mem_cert,
  133. mem_cert_len, &p, &flen)) {
  134. lwsl_err("couldn't find cert file %s\n", cert);
  135. return 1;
  136. }
  137. err = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx, flen, p);
  138. lws_free_set_NULL(p);
  139. if (!err) {
  140. lwsl_err("Problem loading cert\n");
  141. return 1;
  142. }
  143. if (lws_tls_alloc_pem_to_der_file(vhost->context, private_key,
  144. (char *)mem_privkey, mem_privkey_len,
  145. &p, &flen)) {
  146. lwsl_err("couldn't find private key\n");
  147. return 1;
  148. }
  149. err = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx, p, flen);
  150. lws_free_set_NULL(p);
  151. if (!err) {
  152. lwsl_err("Problem loading key\n");
  153. return 1;
  154. }
  155. vhost->tls.skipped_certs = 0;
  156. return 0;
  157. }
  158. int
  159. lws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info,
  160. struct lws_vhost *vhost, struct lws *wsi)
  161. {
  162. const SSL_METHOD *method = TLS_server_method();
  163. uint8_t *p;
  164. lws_filepos_t flen;
  165. int n;
  166. vhost->tls.ssl_ctx = SSL_CTX_new(method); /* create context */
  167. if (!vhost->tls.ssl_ctx) {
  168. lwsl_err("problem creating ssl context\n");
  169. return 1;
  170. }
  171. if (!vhost->tls.use_ssl ||
  172. (!info->ssl_cert_filepath && !info->server_ssl_cert_mem))
  173. return 0;
  174. if (info->ssl_ca_filepath) {
  175. lwsl_notice("%s: vh %s: loading CA filepath %s\n", __func__,
  176. vhost->name, info->ssl_ca_filepath);
  177. if (lws_tls_alloc_pem_to_der_file(vhost->context,
  178. info->ssl_ca_filepath, NULL, 0, &p, &flen)) {
  179. lwsl_err("couldn't find client CA file %s\n",
  180. info->ssl_ca_filepath);
  181. return 1;
  182. }
  183. if (SSL_CTX_add_client_CA_ASN1(vhost->tls.ssl_ctx, (int)flen, p) != 1) {
  184. lwsl_err("%s: SSL_CTX_add_client_CA_ASN1 unhappy\n",
  185. __func__);
  186. free(p);
  187. return 1;
  188. }
  189. free(p);
  190. } else {
  191. if (info->server_ssl_ca_mem && info->server_ssl_ca_mem_len &&
  192. SSL_CTX_add_client_CA_ASN1(vhost->tls.ssl_ctx,
  193. (int)info->server_ssl_ca_mem_len,
  194. info->server_ssl_ca_mem) != 1) {
  195. lwsl_err("%s: mem SSL_CTX_add_client_CA_ASN1 unhappy\n",
  196. __func__);
  197. return 1;
  198. }
  199. lwsl_notice("%s: vh %s: mem CA OK\n", __func__, vhost->name);
  200. }
  201. n = lws_tls_server_certs_load(vhost, wsi, info->ssl_cert_filepath,
  202. info->ssl_private_key_filepath,
  203. info->server_ssl_cert_mem,
  204. info->server_ssl_cert_mem_len,
  205. info->server_ssl_private_key_mem,
  206. info->server_ssl_private_key_mem_len);
  207. if (n)
  208. return n;
  209. return 0;
  210. }
  211. int
  212. lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd)
  213. {
  214. errno = 0;
  215. wsi->tls.ssl = SSL_new(wsi->a.vhost->tls.ssl_ctx);
  216. if (wsi->tls.ssl == NULL) {
  217. lwsl_err("SSL_new failed: errno %d\n", errno);
  218. lws_tls_err_describe_clear();
  219. return 1;
  220. }
  221. SSL_set_fd(wsi->tls.ssl, accept_fd);
  222. if (wsi->a.vhost->tls.ssl_info_event_mask)
  223. SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
  224. SSL_set_sni_callback(wsi->tls.ssl, lws_mbedtls_sni_cb, wsi->a.context);
  225. return 0;
  226. }
  227. #if defined(LWS_AMAZON_RTOS)
  228. enum lws_ssl_capable_status
  229. #else
  230. int
  231. #endif
  232. lws_tls_server_abort_connection(struct lws *wsi)
  233. {
  234. __lws_tls_shutdown(wsi);
  235. SSL_free(wsi->tls.ssl);
  236. return 0;
  237. }
  238. enum lws_ssl_capable_status
  239. lws_tls_server_accept(struct lws *wsi)
  240. {
  241. union lws_tls_cert_info_results ir;
  242. int m, n;
  243. n = SSL_accept(wsi->tls.ssl);
  244. wsi->skip_fallback = 1;
  245. if (n == 1) {
  246. if (strstr(wsi->a.vhost->name, ".invalid")) {
  247. lwsl_notice("%s: vhost has .invalid, "
  248. "rejecting accept\n", __func__);
  249. return LWS_SSL_CAPABLE_ERROR;
  250. }
  251. n = lws_tls_peer_cert_info(wsi, LWS_TLS_CERT_INFO_COMMON_NAME,
  252. &ir, sizeof(ir.ns.name));
  253. if (!n)
  254. lwsl_notice("%s: client cert CN '%s'\n",
  255. __func__, ir.ns.name);
  256. else
  257. lwsl_info("%s: couldn't get client cert CN\n",
  258. __func__);
  259. return LWS_SSL_CAPABLE_DONE;
  260. }
  261. m = SSL_get_error(wsi->tls.ssl, n);
  262. lwsl_notice("%s: %p: accept SSL_get_error %d errno %d\n", __func__,
  263. wsi, m, errno);
  264. // mbedtls wrapper only
  265. if (m == SSL_ERROR_SYSCALL && errno == 11)
  266. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  267. #if defined(__APPLE__)
  268. if (m == SSL_ERROR_SYSCALL && errno == 35)
  269. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  270. #endif
  271. #if defined(WIN32)
  272. if (m == SSL_ERROR_SYSCALL && errno == 0)
  273. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  274. #endif
  275. if (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL)
  276. return LWS_SSL_CAPABLE_ERROR;
  277. if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {
  278. if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
  279. lwsl_info("%s: WANT_READ change_pollfd failed\n",
  280. __func__);
  281. return LWS_SSL_CAPABLE_ERROR;
  282. }
  283. lwsl_info("SSL_ERROR_WANT_READ\n");
  284. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  285. }
  286. if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
  287. lwsl_debug("%s: WANT_WRITE\n", __func__);
  288. if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
  289. lwsl_info("%s: WANT_WRITE change_pollfd failed\n",
  290. __func__);
  291. return LWS_SSL_CAPABLE_ERROR;
  292. }
  293. return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
  294. }
  295. return LWS_SSL_CAPABLE_ERROR;
  296. }
  297. #if defined(LWS_WITH_ACME)
  298. /*
  299. * mbedtls doesn't support SAN for cert creation. So we use a known-good
  300. * tls-sni-01 cert from OpenSSL that worked on Let's Encrypt, and just replace
  301. * the pubkey n part and the signature part.
  302. *
  303. * This will need redoing for tls-sni-02...
  304. */
  305. static uint8_t ss_cert_leadin[] = {
  306. 0x30, 0x82,
  307. 0x05, 0x56, /* total length: LEN1 (+2 / +3) (correct for 513 + 512)*/
  308. 0x30, 0x82, /* length: LEN2 (+6 / +7) (correct for 513) */
  309. 0x03, 0x3e,
  310. /* addition: v3 cert (+5 bytes)*/
  311. 0xa0, 0x03,
  312. 0x02, 0x01, 0x02,
  313. 0x02, 0x01, 0x01,
  314. 0x30, 0x0d, 0x06, 0x09, 0x2a,
  315. 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3f,
  316. 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47,
  317. 0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0b,
  318. 0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e, 0x79, 0x31,
  319. 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x74, 0x65,
  320. 0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e, 0x76, 0x61,
  321. 0x6c, 0x69, 0x64, 0x30, 0x1e, 0x17, 0x0d,
  322. /* from 2017-10-29 ... */
  323. 0x31, 0x37, 0x31, 0x30, 0x32, 0x39, 0x31, 0x31, 0x34, 0x39, 0x34, 0x35,
  324. 0x5a, 0x17, 0x0d,
  325. /* thru 2049-10-29 we immediately discard the private key, no worries */
  326. 0x34, 0x39, 0x31, 0x30, 0x32, 0x39, 0x31, 0x32, 0x34, 0x39, 0x34, 0x35,
  327. 0x5a,
  328. 0x30, 0x3f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
  329. 0x02, 0x47, 0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a,
  330. 0x0c, 0x0b, 0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e,
  331. 0x79, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11,
  332. 0x74, 0x65, 0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e,
  333. 0x76, 0x61, 0x6c, 0x69, 0x64, 0x30,
  334. 0x82,
  335. 0x02, 0x22, /* LEN3 (+C3 / C4) */
  336. 0x30, 0x0d, 0x06,
  337. 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
  338. 0x03,
  339. 0x82,
  340. 0x02, 0x0f, /* LEN4 (+D6 / D7) */
  341. 0x00, 0x30, 0x82,
  342. 0x02, 0x0a, /* LEN5 (+ DB / DC) */
  343. 0x02, 0x82,
  344. //0x02, 0x01, /* length of n in bytes (including leading 00 if any) */
  345. },
  346. /* 1 + (keybits / 8) bytes N */
  347. ss_cert_san_leadin[] = {
  348. /* e - fixed */
  349. 0x02, 0x03, 0x01, 0x00, 0x01,
  350. 0xa3, 0x5d, 0x30, 0x5b, 0x30, 0x59, 0x06, 0x03, 0x55, 0x1d,
  351. 0x11, 0x04, 0x52, 0x30, 0x50, /* <-- SAN length + 2 */
  352. 0x82, 0x4e, /* <-- SAN length */
  353. },
  354. /* 78 bytes of SAN (tls-sni-01)
  355. 0x61, 0x64, 0x34, 0x31, 0x61, 0x66, 0x62, 0x65, 0x30, 0x63, 0x61, 0x34,
  356. 0x36, 0x34, 0x32, 0x66, 0x30, 0x61, 0x34, 0x34, 0x39, 0x64, 0x39, 0x63,
  357. 0x61, 0x37, 0x36, 0x65, 0x62, 0x61, 0x61, 0x62, 0x2e, 0x32, 0x38, 0x39,
  358. 0x34, 0x64, 0x34, 0x31, 0x36, 0x63, 0x39, 0x38, 0x33, 0x66, 0x31, 0x32,
  359. 0x65, 0x64, 0x37, 0x33, 0x31, 0x61, 0x33, 0x30, 0x66, 0x35, 0x63, 0x34,
  360. 0x34, 0x37, 0x37, 0x66, 0x65, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69,
  361. 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, */
  362. /* end of LEN2 area */
  363. ss_cert_sig_leadin[] = {
  364. /* it's saying that the signature is SHA256 + RSA */
  365. 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  366. 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03,
  367. 0x82,
  368. 0x02, 0x01,
  369. 0x00,
  370. };
  371. /* (keybits / 8) bytes signature to end of LEN1 area */
  372. #define SAN_A_LENGTH 78
  373. int
  374. lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,
  375. const char *san_b)
  376. {
  377. int buflen = 0x560;
  378. uint8_t *buf = lws_malloc(buflen, "tmp cert buf"), *p = buf, *pkey_asn1;
  379. struct lws_genrsa_ctx ctx;
  380. struct lws_gencrypto_keyelem el[LWS_GENCRYPTO_RSA_KEYEL_COUNT];
  381. uint8_t digest[32];
  382. struct lws_genhash_ctx hash_ctx;
  383. int pkey_asn1_len = 3 * 1024;
  384. int n, m, keybits = lws_plat_recommended_rsa_bits(), adj;
  385. if (!buf)
  386. return 1;
  387. n = lws_genrsa_new_keypair(vhost->context, &ctx, LGRSAM_PKCS1_1_5,
  388. &el[0], keybits);
  389. if (n < 0) {
  390. lws_genrsa_destroy_elements(&el[0]);
  391. goto bail1;
  392. }
  393. n = sizeof(ss_cert_leadin);
  394. memcpy(p, ss_cert_leadin, n);
  395. p += n;
  396. adj = (0x0556 - 0x401) + (keybits / 4) + 1;
  397. buf[2] = adj >> 8;
  398. buf[3] = adj & 0xff;
  399. adj = (0x033e - 0x201) + (keybits / 8) + 1;
  400. buf[6] = adj >> 8;
  401. buf[7] = adj & 0xff;
  402. adj = (0x0222 - 0x201) + (keybits / 8) + 1;
  403. buf[0xc3] = adj >> 8;
  404. buf[0xc4] = adj & 0xff;
  405. adj = (0x020f - 0x201) + (keybits / 8) + 1;
  406. buf[0xd6] = adj >> 8;
  407. buf[0xd7] = adj & 0xff;
  408. adj = (0x020a - 0x201) + (keybits / 8) + 1;
  409. buf[0xdb] = adj >> 8;
  410. buf[0xdc] = adj & 0xff;
  411. *p++ = ((keybits / 8) + 1) >> 8;
  412. *p++ = ((keybits / 8) + 1) & 0xff;
  413. /* we need to drop 1 + (keybits / 8) bytes of n in here, 00 + key */
  414. *p++ = 0x00;
  415. memcpy(p, el[LWS_GENCRYPTO_RSA_KEYEL_N].buf, el[LWS_GENCRYPTO_RSA_KEYEL_N].len);
  416. p += el[LWS_GENCRYPTO_RSA_KEYEL_N].len;
  417. memcpy(p, ss_cert_san_leadin, sizeof(ss_cert_san_leadin));
  418. p += sizeof(ss_cert_san_leadin);
  419. /* drop in 78 bytes of san_a */
  420. memcpy(p, san_a, SAN_A_LENGTH);
  421. p += SAN_A_LENGTH;
  422. memcpy(p, ss_cert_sig_leadin, sizeof(ss_cert_sig_leadin));
  423. p[17] = ((keybits / 8) + 1) >> 8;
  424. p[18] = ((keybits / 8) + 1) & 0xff;
  425. p += sizeof(ss_cert_sig_leadin);
  426. /* hash the cert plaintext */
  427. if (lws_genhash_init(&hash_ctx, LWS_GENHASH_TYPE_SHA256))
  428. goto bail2;
  429. if (lws_genhash_update(&hash_ctx, buf, lws_ptr_diff(p, buf))) {
  430. lws_genhash_destroy(&hash_ctx, NULL);
  431. goto bail2;
  432. }
  433. if (lws_genhash_destroy(&hash_ctx, digest))
  434. goto bail2;
  435. /* sign the hash */
  436. n = lws_genrsa_hash_sign(&ctx, digest, LWS_GENHASH_TYPE_SHA256, p,
  437. buflen - lws_ptr_diff(p, buf));
  438. if (n < 0)
  439. goto bail2;
  440. p += n;
  441. pkey_asn1 = lws_malloc(pkey_asn1_len, "mbed crt tmp");
  442. if (!pkey_asn1)
  443. goto bail2;
  444. m = lws_genrsa_render_pkey_asn1(&ctx, 1, pkey_asn1, pkey_asn1_len);
  445. if (m < 0) {
  446. lws_free(pkey_asn1);
  447. goto bail2;
  448. }
  449. // lwsl_hexdump_level(LLL_DEBUG, buf, lws_ptr_diff(p, buf));
  450. n = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx,
  451. lws_ptr_diff(p, buf), buf);
  452. if (n != 1) {
  453. lws_free(pkey_asn1);
  454. lwsl_err("%s: generated cert failed to load 0x%x\n",
  455. __func__, -n);
  456. } else {
  457. //lwsl_debug("private key\n");
  458. //lwsl_hexdump_level(LLL_DEBUG, pkey_asn1, n);
  459. /* and to use our generated private key */
  460. n = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx,
  461. pkey_asn1, m);
  462. lws_free(pkey_asn1);
  463. if (n != 1) {
  464. lwsl_err("%s: SSL_CTX_use_PrivateKey_ASN1 failed\n",
  465. __func__);
  466. }
  467. }
  468. lws_genrsa_destroy(&ctx);
  469. lws_genrsa_destroy_elements(&el[0]);
  470. lws_free(buf);
  471. return n != 1;
  472. bail2:
  473. lws_genrsa_destroy(&ctx);
  474. lws_genrsa_destroy_elements(&el[0]);
  475. bail1:
  476. lws_free(buf);
  477. return -1;
  478. }
  479. void
  480. lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost)
  481. {
  482. }
  483. #if defined(LWS_WITH_JOSE)
  484. static int
  485. _rngf(void *context, unsigned char *buf, size_t len)
  486. {
  487. if ((size_t)lws_get_random(context, buf, len) == len)
  488. return 0;
  489. return -1;
  490. }
  491. static const char *x5[] = { "C", "ST", "L", "O", "CN" };
  492. /*
  493. * CSR is output formatted as b64url(DER)
  494. * Private key is output as a PEM in memory
  495. */
  496. int
  497. lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],
  498. uint8_t *dcsr, size_t csr_len, char **privkey_pem,
  499. size_t *privkey_len)
  500. {
  501. mbedtls_x509write_csr csr;
  502. mbedtls_pk_context mpk;
  503. int buf_size = 4096, n;
  504. char subject[200], *p = subject, *end = p + sizeof(subject) - 1;
  505. uint8_t *buf = malloc(buf_size); /* malloc because given to user code */
  506. if (!buf)
  507. return -1;
  508. mbedtls_x509write_csr_init(&csr);
  509. mbedtls_pk_init(&mpk);
  510. if (mbedtls_pk_setup(&mpk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA))) {
  511. lwsl_notice("%s: pk_setup failed\n", __func__);
  512. goto fail;
  513. }
  514. n = mbedtls_rsa_gen_key(mbedtls_pk_rsa(mpk), _rngf, context,
  515. lws_plat_recommended_rsa_bits(), 65537);
  516. if (n) {
  517. lwsl_notice("%s: failed to generate keys\n", __func__);
  518. goto fail1;
  519. }
  520. /* subject must be formatted like "C=TW,O=warmcat,CN=myserver" */
  521. for (n = 0; n < (int)LWS_ARRAY_SIZE(x5); n++) {
  522. if (p != subject)
  523. *p++ = ',';
  524. if (elements[n])
  525. p += lws_snprintf(p, end - p, "%s=%s", x5[n],
  526. elements[n]);
  527. }
  528. if (mbedtls_x509write_csr_set_subject_name(&csr, subject))
  529. goto fail1;
  530. mbedtls_x509write_csr_set_key(&csr, &mpk);
  531. mbedtls_x509write_csr_set_md_alg(&csr, MBEDTLS_MD_SHA256);
  532. /*
  533. * data is written at the end of the buffer! Use the
  534. * return value to determine where you should start
  535. * using the buffer
  536. */
  537. n = mbedtls_x509write_csr_der(&csr, buf, buf_size, _rngf, context);
  538. if (n < 0) {
  539. lwsl_notice("%s: write csr der failed\n", __func__);
  540. goto fail1;
  541. }
  542. /* we have it in DER, we need it in b64URL */
  543. n = lws_jws_base64_enc((char *)(buf + buf_size) - n, n,
  544. (char *)dcsr, csr_len);
  545. if (n < 0)
  546. goto fail1;
  547. /*
  548. * okay, the CSR is done, last we need the private key in PEM
  549. * re-use the DER CSR buf as the result buffer since we cn do it in
  550. * one step
  551. */
  552. if (mbedtls_pk_write_key_pem(&mpk, buf, buf_size)) {
  553. lwsl_notice("write key pem failed\n");
  554. goto fail1;
  555. }
  556. *privkey_pem = (char *)buf;
  557. *privkey_len = strlen((const char *)buf);
  558. mbedtls_pk_free(&mpk);
  559. mbedtls_x509write_csr_free(&csr);
  560. return n;
  561. fail1:
  562. mbedtls_pk_free(&mpk);
  563. fail:
  564. mbedtls_x509write_csr_free(&csr);
  565. free(buf);
  566. return -1;
  567. }
  568. #endif
  569. #endif