openssl-server.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. /*
  26. * Care: many openssl apis return 1 for success. These are translated to the
  27. * lws convention of 0 for success.
  28. */
  29. extern int openssl_websocket_private_data_index,
  30. openssl_SSL_CTX_private_data_index;
  31. int lws_openssl_describe_cipher(struct lws *wsi);
  32. static int
  33. OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
  34. {
  35. SSL *ssl;
  36. int n;
  37. struct lws *wsi;
  38. union lws_tls_cert_info_results ir;
  39. X509 *topcert = X509_STORE_CTX_get_current_cert(x509_ctx);
  40. ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
  41. SSL_get_ex_data_X509_STORE_CTX_idx());
  42. /*
  43. * !!! nasty openssl requires the index to come as a library-scope
  44. * static
  45. */
  46. wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
  47. n = lws_tls_openssl_cert_info(topcert, LWS_TLS_CERT_INFO_COMMON_NAME,
  48. &ir, sizeof(ir.ns.name));
  49. if (!n)
  50. lwsl_info("%s: client cert CN '%s'\n", __func__, ir.ns.name);
  51. else
  52. lwsl_info("%s: couldn't get client cert CN\n", __func__);
  53. n = wsi->a.vhost->protocols[0].callback(wsi,
  54. LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
  55. x509_ctx, ssl, preverify_ok);
  56. /* convert return code from 0 = OK to 1 = OK */
  57. return !n;
  58. }
  59. int
  60. lws_tls_server_client_cert_verify_config(struct lws_vhost *vh)
  61. {
  62. int verify_options = SSL_VERIFY_PEER;
  63. /* as a server, are we requiring clients to identify themselves? */
  64. if (!lws_check_opt(vh->options,
  65. LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT))
  66. return 0;
  67. if (!lws_check_opt(vh->options,
  68. LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
  69. verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  70. SSL_CTX_set_session_id_context(vh->tls.ssl_ctx, (uint8_t *)vh->context,
  71. sizeof(void *));
  72. /* absolutely require the client cert */
  73. SSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options,
  74. OpenSSL_verify_callback);
  75. return 0;
  76. }
  77. #if defined(SSL_TLSEXT_ERR_NOACK) && !defined(OPENSSL_NO_TLSEXT)
  78. static int
  79. lws_ssl_server_name_cb(SSL *ssl, int *ad, void *arg)
  80. {
  81. struct lws_context *context = (struct lws_context *)arg;
  82. struct lws_vhost *vhost, *vh;
  83. const char *servername;
  84. if (!ssl)
  85. return SSL_TLSEXT_ERR_NOACK;
  86. /*
  87. * We can only get ssl accepted connections by using a vhost's ssl_ctx
  88. * find out which listening one took us and only match vhosts on the
  89. * same port.
  90. */
  91. vh = context->vhost_list;
  92. while (vh) {
  93. if (!vh->being_destroyed &&
  94. vh->tls.ssl_ctx == SSL_get_SSL_CTX(ssl))
  95. break;
  96. vh = vh->vhost_next;
  97. }
  98. if (!vh) {
  99. assert(vh); /* can't match the incoming vh? */
  100. return SSL_TLSEXT_ERR_OK;
  101. }
  102. servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  103. if (!servername) {
  104. /* the client doesn't know what hostname it wants */
  105. lwsl_info("SNI: Unknown ServerName\n");
  106. return SSL_TLSEXT_ERR_OK;
  107. }
  108. vhost = lws_select_vhost(context, vh->listen_port, servername);
  109. if (!vhost) {
  110. lwsl_info("SNI: none: %s:%d\n", servername, vh->listen_port);
  111. return SSL_TLSEXT_ERR_OK;
  112. }
  113. lwsl_info("SNI: Found: %s:%d\n", servername, vh->listen_port);
  114. /* select the ssl ctx from the selected vhost for this conn */
  115. SSL_set_SSL_CTX(ssl, vhost->tls.ssl_ctx);
  116. return SSL_TLSEXT_ERR_OK;
  117. }
  118. #endif
  119. /*
  120. * this may now get called after the vhost creation, when certs become
  121. * available.
  122. */
  123. int
  124. lws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi,
  125. const char *cert, const char *private_key,
  126. const char *mem_cert, size_t mem_cert_len,
  127. const char *mem_privkey, size_t mem_privkey_len)
  128. {
  129. #if !defined(OPENSSL_NO_EC)
  130. const char *ecdh_curve = "prime256v1";
  131. #if !defined(LWS_WITH_BORINGSSL) && defined(LWS_HAVE_SSL_EXTRA_CHAIN_CERTS)
  132. STACK_OF(X509) *extra_certs = NULL;
  133. #endif
  134. EC_KEY *ecdh, *EC_key = NULL;
  135. EVP_PKEY *pkey;
  136. X509 *x = NULL;
  137. int ecdh_nid;
  138. int KeyType;
  139. #endif
  140. unsigned long error;
  141. lws_filepos_t flen;
  142. uint8_t *p;
  143. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  144. int ret;
  145. #endif
  146. int n = lws_tls_generic_cert_checks(vhost, cert, private_key), m;
  147. if (!cert && !private_key)
  148. n = LWS_TLS_EXTANT_ALTERNATIVE;
  149. if (n == LWS_TLS_EXTANT_NO && (!mem_cert || !mem_privkey))
  150. return 0;
  151. if (n == LWS_TLS_EXTANT_NO)
  152. n = LWS_TLS_EXTANT_ALTERNATIVE;
  153. if (n == LWS_TLS_EXTANT_ALTERNATIVE && (!mem_cert || !mem_privkey))
  154. return 1; /* no alternative */
  155. if (n == LWS_TLS_EXTANT_ALTERNATIVE) {
  156. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  157. /*
  158. * Although we have prepared update certs, we no longer have
  159. * the rights to read our own cert + key we saved.
  160. *
  161. * If we were passed copies in memory buffers, use those
  162. * in favour of the filepaths we normally want.
  163. */
  164. cert = NULL;
  165. private_key = NULL;
  166. }
  167. /*
  168. * use the multi-cert interface for backwards compatibility in the
  169. * both simple files case
  170. */
  171. if (n != LWS_TLS_EXTANT_ALTERNATIVE && cert) {
  172. /* set the local certificate from CertFile */
  173. m = SSL_CTX_use_certificate_chain_file(vhost->tls.ssl_ctx, cert);
  174. if (m != 1) {
  175. error = ERR_get_error();
  176. lwsl_err("problem getting cert '%s' %lu: %s\n",
  177. cert, error, ERR_error_string(error,
  178. (char *)vhost->context->pt[0].serv_buf));
  179. return 1;
  180. }
  181. if (private_key) {
  182. /* set the private key from KeyFile */
  183. if (SSL_CTX_use_PrivateKey_file(vhost->tls.ssl_ctx, private_key,
  184. SSL_FILETYPE_PEM) != 1) {
  185. error = ERR_get_error();
  186. lwsl_err("ssl problem getting key '%s' %lu: %s\n",
  187. private_key, error,
  188. ERR_error_string(error,
  189. (char *)vhost->context->pt[0].serv_buf));
  190. return 1;
  191. }
  192. } else {
  193. if (vhost->protocols[0].callback(wsi,
  194. LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
  195. vhost->tls.ssl_ctx, NULL, 0)) {
  196. lwsl_err("ssl private key not set\n");
  197. return 1;
  198. }
  199. }
  200. return 0;
  201. }
  202. /* otherwise allow for DER or PEM, file or memory image */
  203. if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, mem_cert,
  204. mem_cert_len, &p, &flen)) {
  205. lwsl_err("%s: couldn't read cert file\n", __func__);
  206. return 1;
  207. }
  208. #if !defined(USE_WOLFSSL)
  209. ret = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx, (int)flen, p);
  210. #else
  211. ret = wolfSSL_CTX_use_certificate_buffer(vhost->tls.ssl_ctx,
  212. (uint8_t *)p, (int)flen,
  213. WOLFSSL_FILETYPE_ASN1);
  214. #endif
  215. lws_free_set_NULL(p);
  216. if (ret != 1) {
  217. lwsl_err("%s: Problem loading cert\n", __func__);
  218. return 1;
  219. }
  220. if (lws_tls_alloc_pem_to_der_file(vhost->context, private_key,
  221. mem_privkey, mem_privkey_len,
  222. &p, &flen)) {
  223. lwsl_notice("unable to convert memory privkey\n");
  224. return 1;
  225. }
  226. #if !defined(USE_WOLFSSL)
  227. ret = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, vhost->tls.ssl_ctx, p,
  228. (long)(long long)flen);
  229. if (ret != 1) {
  230. ret = SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC,
  231. vhost->tls.ssl_ctx, p,
  232. (long)(long long)flen);
  233. }
  234. #else
  235. ret = wolfSSL_CTX_use_PrivateKey_buffer(vhost->tls.ssl_ctx, p, flen,
  236. WOLFSSL_FILETYPE_ASN1);
  237. #endif
  238. lws_free_set_NULL(p);
  239. if (ret != 1) {
  240. lwsl_notice("unable to use memory privkey\n");
  241. return 1;
  242. }
  243. #else
  244. /*
  245. * Although we have prepared update certs, we no longer have
  246. * the rights to read our own cert + key we saved.
  247. *
  248. * If we were passed copies in memory buffers, use those
  249. * instead.
  250. *
  251. * The passed memory-buffer cert image is in DER, and the
  252. * memory-buffer private key image is PEM.
  253. */
  254. #ifndef USE_WOLFSSL
  255. if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, mem_cert,
  256. mem_cert_len, &p, &flen)) {
  257. lwsl_err("%s: couldn't convert pem to der\n", __func__);
  258. return 1;
  259. }
  260. if (SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx,
  261. (int)flen,
  262. (uint8_t *)p) != 1) {
  263. #else
  264. if (wolfSSL_CTX_use_certificate_buffer(vhost->tls.ssl_ctx,
  265. (uint8_t *)mem_cert,
  266. (int)mem_cert_len,
  267. WOLFSSL_FILETYPE_ASN1) != 1) {
  268. #endif
  269. lwsl_err("Problem loading update cert\n");
  270. return 1;
  271. }
  272. if (lws_tls_alloc_pem_to_der_file(vhost->context, NULL,
  273. mem_privkey, mem_privkey_len,
  274. &p, &flen)) {
  275. lwsl_notice("unable to convert memory privkey\n");
  276. return 1;
  277. }
  278. #ifndef USE_WOLFSSL
  279. if (SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA,
  280. vhost->tls.ssl_ctx, p,
  281. (long)(long long)flen) != 1) {
  282. #else
  283. if (wolfSSL_CTX_use_PrivateKey_buffer(vhost->tls.ssl_ctx, p,
  284. flen, WOLFSSL_FILETYPE_ASN1) != 1) {
  285. #endif
  286. lwsl_notice("unable to use memory privkey\n");
  287. return 1;
  288. }
  289. goto check_key;
  290. }
  291. /* set the local certificate from CertFile */
  292. m = SSL_CTX_use_certificate_chain_file(vhost->tls.ssl_ctx, cert);
  293. if (m != 1) {
  294. error = ERR_get_error();
  295. lwsl_err("problem getting cert '%s' %lu: %s\n",
  296. cert, error, ERR_error_string(error,
  297. (char *)vhost->context->pt[0].serv_buf));
  298. return 1;
  299. }
  300. if (n != LWS_TLS_EXTANT_ALTERNATIVE && private_key) {
  301. /* set the private key from KeyFile */
  302. if (SSL_CTX_use_PrivateKey_file(vhost->tls.ssl_ctx, private_key,
  303. SSL_FILETYPE_PEM) != 1) {
  304. error = ERR_get_error();
  305. lwsl_err("ssl problem getting key '%s' %lu: %s\n",
  306. private_key, error,
  307. ERR_error_string(error,
  308. (char *)vhost->context->pt[0].serv_buf));
  309. return 1;
  310. }
  311. } else {
  312. if (vhost->protocols[0].callback(wsi,
  313. LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
  314. vhost->tls.ssl_ctx, NULL, 0)) {
  315. lwsl_err("ssl private key not set\n");
  316. return 1;
  317. }
  318. }
  319. check_key:
  320. #endif
  321. /* verify private key */
  322. if (!SSL_CTX_check_private_key(vhost->tls.ssl_ctx)) {
  323. lwsl_err("Private SSL key doesn't match cert\n");
  324. return 1;
  325. }
  326. #if !defined(OPENSSL_NO_EC)
  327. if (vhost->tls.ecdh_curve[0])
  328. ecdh_curve = vhost->tls.ecdh_curve;
  329. ecdh_nid = OBJ_sn2nid(ecdh_curve);
  330. if (NID_undef == ecdh_nid) {
  331. lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve);
  332. return 1;
  333. }
  334. ecdh = EC_KEY_new_by_curve_name(ecdh_nid);
  335. if (NULL == ecdh) {
  336. lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve);
  337. return 1;
  338. }
  339. SSL_CTX_set_tmp_ecdh(vhost->tls.ssl_ctx, ecdh);
  340. EC_KEY_free(ecdh);
  341. SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
  342. lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve);
  343. if (lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_SSL_ECDH))
  344. lwsl_notice(" Using ECDH certificate support\n");
  345. /* Get X509 certificate from ssl context */
  346. #if !defined(LWS_WITH_BORINGSSL)
  347. #if !defined(LWS_HAVE_SSL_EXTRA_CHAIN_CERTS)
  348. x = sk_X509_value(vhost->tls.ssl_ctx->extra_certs, 0);
  349. #else
  350. SSL_CTX_get_extra_chain_certs_only(vhost->tls.ssl_ctx, &extra_certs);
  351. if (extra_certs)
  352. x = sk_X509_value(extra_certs, 0);
  353. else
  354. lwsl_info("%s: no extra certs\n", __func__);
  355. #endif
  356. if (!x) {
  357. //lwsl_err("%s: x is NULL\n", __func__);
  358. goto post_ecdh;
  359. }
  360. #else
  361. return 0;
  362. #endif
  363. /* Get the public key from certificate */
  364. pkey = X509_get_pubkey(x);
  365. if (!pkey) {
  366. lwsl_err("%s: pkey is NULL\n", __func__);
  367. return 1;
  368. }
  369. /* Get the key type */
  370. KeyType = EVP_PKEY_type(EVP_PKEY_id(pkey));
  371. if (EVP_PKEY_EC != KeyType) {
  372. lwsl_notice("Key type is not EC\n");
  373. return 0;
  374. }
  375. /* Get the key */
  376. EC_key = EVP_PKEY_get1_EC_KEY(pkey);
  377. /* Set ECDH parameter */
  378. if (!EC_key) {
  379. lwsl_err("%s: ECDH key is NULL \n", __func__);
  380. return 1;
  381. }
  382. SSL_CTX_set_tmp_ecdh(vhost->tls.ssl_ctx, EC_key);
  383. EC_KEY_free(EC_key);
  384. #else
  385. lwsl_notice(" OpenSSL doesn't support ECDH\n");
  386. #endif
  387. #if !defined(OPENSSL_NO_EC) && !defined(LWS_WITH_BORINGSSL)
  388. post_ecdh:
  389. #endif
  390. vhost->tls.skipped_certs = 0;
  391. return 0;
  392. }
  393. int
  394. lws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info,
  395. struct lws_vhost *vhost, struct lws *wsi)
  396. {
  397. unsigned long error;
  398. SSL_METHOD *method = (SSL_METHOD *)SSLv23_server_method();
  399. if (!method) {
  400. error = ERR_get_error();
  401. lwsl_err("problem creating ssl method %lu: %s\n",
  402. error, ERR_error_string(error,
  403. (char *)vhost->context->pt[0].serv_buf));
  404. return 1;
  405. }
  406. vhost->tls.ssl_ctx = SSL_CTX_new(method); /* create context */
  407. if (!vhost->tls.ssl_ctx) {
  408. error = ERR_get_error();
  409. lwsl_err("problem creating ssl context %lu: %s\n",
  410. error, ERR_error_string(error,
  411. (char *)vhost->context->pt[0].serv_buf));
  412. return 1;
  413. }
  414. SSL_CTX_set_ex_data(vhost->tls.ssl_ctx,
  415. openssl_SSL_CTX_private_data_index,
  416. (char *)vhost->context);
  417. /* Disable SSLv2 and SSLv3 */
  418. SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_NO_SSLv2 |
  419. SSL_OP_NO_SSLv3);
  420. #ifdef SSL_OP_NO_COMPRESSION
  421. SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_NO_COMPRESSION);
  422. #endif
  423. SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_SINGLE_DH_USE);
  424. SSL_CTX_set_options(vhost->tls.ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  425. if (info->ssl_cipher_list)
  426. SSL_CTX_set_cipher_list(vhost->tls.ssl_ctx, info->ssl_cipher_list);
  427. #if defined(LWS_HAVE_SSL_CTX_set_ciphersuites)
  428. if (info->tls1_3_plus_cipher_list)
  429. SSL_CTX_set_ciphersuites(vhost->tls.ssl_ctx,
  430. info->tls1_3_plus_cipher_list);
  431. #endif
  432. #if !defined(OPENSSL_NO_TLSEXT)
  433. SSL_CTX_set_tlsext_servername_callback(vhost->tls.ssl_ctx,
  434. lws_ssl_server_name_cb);
  435. SSL_CTX_set_tlsext_servername_arg(vhost->tls.ssl_ctx, vhost->context);
  436. #endif
  437. if (info->ssl_ca_filepath &&
  438. #if defined(LWS_HAVE_SSL_CTX_load_verify_file)
  439. !SSL_CTX_load_verify_file(vhost->tls.ssl_ctx,
  440. info->ssl_ca_filepath)) {
  441. #else
  442. !SSL_CTX_load_verify_locations(vhost->tls.ssl_ctx,
  443. info->ssl_ca_filepath, NULL)) {
  444. #endif
  445. lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n",
  446. __func__);
  447. }
  448. if (info->ssl_options_set)
  449. SSL_CTX_set_options(vhost->tls.ssl_ctx, info->ssl_options_set);
  450. /* SSL_clear_options introduced in 0.9.8m */
  451. #if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL)
  452. if (info->ssl_options_clear)
  453. SSL_CTX_clear_options(vhost->tls.ssl_ctx,
  454. info->ssl_options_clear);
  455. #endif
  456. lwsl_info(" SSL options 0x%lX\n",
  457. (unsigned long)SSL_CTX_get_options(vhost->tls.ssl_ctx));
  458. if (!vhost->tls.use_ssl ||
  459. (!info->ssl_cert_filepath && !info->server_ssl_cert_mem))
  460. return 0;
  461. lws_ssl_bind_passphrase(vhost->tls.ssl_ctx, 0, info);
  462. return lws_tls_server_certs_load(vhost, wsi, info->ssl_cert_filepath,
  463. info->ssl_private_key_filepath,
  464. info->server_ssl_cert_mem,
  465. info->server_ssl_cert_mem_len,
  466. info->server_ssl_private_key_mem,
  467. info->server_ssl_private_key_mem_len);
  468. }
  469. int
  470. lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd)
  471. {
  472. #if !defined(USE_WOLFSSL)
  473. BIO *bio;
  474. #endif
  475. errno = 0;
  476. ERR_clear_error();
  477. wsi->tls.ssl = SSL_new(wsi->a.vhost->tls.ssl_ctx);
  478. if (wsi->tls.ssl == NULL) {
  479. lwsl_err("SSL_new failed: %d (errno %d)\n",
  480. lws_ssl_get_error(wsi, 0), errno);
  481. lws_tls_err_describe_clear();
  482. return 1;
  483. }
  484. SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index, wsi);
  485. SSL_set_fd(wsi->tls.ssl, (int)(lws_intptr_t)accept_fd);
  486. #ifdef USE_WOLFSSL
  487. #ifdef USE_OLD_CYASSL
  488. CyaSSL_set_using_nonblock(wsi->tls.ssl, 1);
  489. #else
  490. wolfSSL_set_using_nonblock(wsi->tls.ssl, 1);
  491. #endif
  492. #else
  493. SSL_set_mode(wsi->tls.ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
  494. SSL_MODE_RELEASE_BUFFERS);
  495. bio = SSL_get_rbio(wsi->tls.ssl);
  496. if (bio)
  497. BIO_set_nbio(bio, 1); /* nonblocking */
  498. else
  499. lwsl_notice("NULL rbio\n");
  500. bio = SSL_get_wbio(wsi->tls.ssl);
  501. if (bio)
  502. BIO_set_nbio(bio, 1); /* nonblocking */
  503. else
  504. lwsl_notice("NULL rbio\n");
  505. #endif
  506. #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
  507. if (wsi->a.vhost->tls.ssl_info_event_mask)
  508. SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);
  509. #endif
  510. return 0;
  511. }
  512. int
  513. lws_tls_server_abort_connection(struct lws *wsi)
  514. {
  515. SSL_shutdown(wsi->tls.ssl);
  516. SSL_free(wsi->tls.ssl);
  517. return 0;
  518. }
  519. enum lws_ssl_capable_status
  520. lws_tls_server_accept(struct lws *wsi)
  521. {
  522. struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
  523. union lws_tls_cert_info_results ir;
  524. int m, n;
  525. errno = 0;
  526. ERR_clear_error();
  527. n = SSL_accept(wsi->tls.ssl);
  528. wsi->skip_fallback = 1;
  529. if (n == 1) {
  530. n = lws_tls_peer_cert_info(wsi, LWS_TLS_CERT_INFO_COMMON_NAME, &ir,
  531. sizeof(ir.ns.name));
  532. if (!n)
  533. lwsl_notice("%s: client cert CN '%s'\n", __func__,
  534. ir.ns.name);
  535. else
  536. lwsl_info("%s: no client cert CN\n", __func__);
  537. lws_openssl_describe_cipher(wsi);
  538. if (SSL_pending(wsi->tls.ssl) &&
  539. lws_dll2_is_detached(&wsi->tls.dll_pending_tls))
  540. lws_dll2_add_head(&wsi->tls.dll_pending_tls,
  541. &pt->tls.dll_pending_tls_owner);
  542. return LWS_SSL_CAPABLE_DONE;
  543. }
  544. m = lws_ssl_get_error(wsi, n);
  545. lws_tls_err_describe_clear();
  546. if (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL)
  547. return LWS_SSL_CAPABLE_ERROR;
  548. if (m == SSL_ERROR_WANT_READ ||
  549. (m != SSL_ERROR_ZERO_RETURN && SSL_want_read(wsi->tls.ssl))) {
  550. if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
  551. lwsl_info("%s: WANT_READ change_pollfd failed\n",
  552. __func__);
  553. return LWS_SSL_CAPABLE_ERROR;
  554. }
  555. lwsl_info("SSL_ERROR_WANT_READ: m %d\n", m);
  556. return LWS_SSL_CAPABLE_MORE_SERVICE_READ;
  557. }
  558. if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {
  559. lwsl_debug("%s: WANT_WRITE\n", __func__);
  560. if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
  561. lwsl_info("%s: WANT_WRITE change_pollfd failed\n",
  562. __func__);
  563. return LWS_SSL_CAPABLE_ERROR;
  564. }
  565. return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;
  566. }
  567. return LWS_SSL_CAPABLE_ERROR;
  568. }
  569. #if defined(LWS_WITH_ACME)
  570. static int
  571. lws_tls_openssl_rsa_new_key(RSA **rsa, int bits)
  572. {
  573. BIGNUM *bn = BN_new();
  574. int n;
  575. if (!bn)
  576. return 1;
  577. if (BN_set_word(bn, RSA_F4) != 1) {
  578. BN_free(bn);
  579. return 1;
  580. }
  581. *rsa = RSA_new();
  582. if (!*rsa) {
  583. BN_free(bn);
  584. return 1;
  585. }
  586. n = RSA_generate_key_ex(*rsa, bits, bn, NULL);
  587. BN_free(bn);
  588. if (n == 1)
  589. return 0;
  590. RSA_free(*rsa);
  591. *rsa = NULL;
  592. return 1;
  593. }
  594. struct lws_tls_ss_pieces {
  595. X509 *x509;
  596. EVP_PKEY *pkey;
  597. RSA *rsa;
  598. };
  599. int
  600. lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,
  601. const char *san_b)
  602. {
  603. GENERAL_NAMES *gens = sk_GENERAL_NAME_new_null();
  604. GENERAL_NAME *gen = NULL;
  605. ASN1_IA5STRING *ia5 = NULL;
  606. X509_NAME *name;
  607. if (!gens)
  608. return 1;
  609. vhost->tls.ss = lws_zalloc(sizeof(*vhost->tls.ss), "sni cert");
  610. if (!vhost->tls.ss) {
  611. GENERAL_NAMES_free(gens);
  612. return 1;
  613. }
  614. vhost->tls.ss->x509 = X509_new();
  615. if (!vhost->tls.ss->x509)
  616. goto bail;
  617. ASN1_INTEGER_set(X509_get_serialNumber(vhost->tls.ss->x509), 1);
  618. X509_gmtime_adj(X509_get_notBefore(vhost->tls.ss->x509), 0);
  619. X509_gmtime_adj(X509_get_notAfter(vhost->tls.ss->x509), 3600);
  620. vhost->tls.ss->pkey = EVP_PKEY_new();
  621. if (!vhost->tls.ss->pkey)
  622. goto bail0;
  623. if (lws_tls_openssl_rsa_new_key(&vhost->tls.ss->rsa, 4096))
  624. goto bail1;
  625. if (!EVP_PKEY_assign_RSA(vhost->tls.ss->pkey, vhost->tls.ss->rsa))
  626. goto bail2;
  627. X509_set_pubkey(vhost->tls.ss->x509, vhost->tls.ss->pkey);
  628. name = X509_get_subject_name(vhost->tls.ss->x509);
  629. X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
  630. (unsigned char *)"GB", -1, -1, 0);
  631. X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
  632. (unsigned char *)"somecompany", -1, -1, 0);
  633. if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_UTF8,
  634. (unsigned char *)"temp.acme.invalid",
  635. -1, -1, 0) != 1) {
  636. lwsl_notice("failed to add CN\n");
  637. goto bail2;
  638. }
  639. X509_set_issuer_name(vhost->tls.ss->x509, name);
  640. /* add the SAN payloads */
  641. gen = GENERAL_NAME_new();
  642. ia5 = ASN1_IA5STRING_new();
  643. if (!ASN1_STRING_set(ia5, san_a, -1)) {
  644. lwsl_notice("failed to set ia5\n");
  645. GENERAL_NAME_free(gen);
  646. goto bail2;
  647. }
  648. GENERAL_NAME_set0_value(gen, GEN_DNS, ia5);
  649. sk_GENERAL_NAME_push(gens, gen);
  650. if (X509_add1_ext_i2d(vhost->tls.ss->x509, NID_subject_alt_name,
  651. gens, 0, X509V3_ADD_APPEND) != 1)
  652. goto bail2;
  653. GENERAL_NAMES_free(gens);
  654. if (san_b && san_b[0]) {
  655. gens = sk_GENERAL_NAME_new_null();
  656. gen = GENERAL_NAME_new();
  657. ia5 = ASN1_IA5STRING_new();
  658. if (!ASN1_STRING_set(ia5, san_a, -1)) {
  659. lwsl_notice("failed to set ia5\n");
  660. GENERAL_NAME_free(gen);
  661. goto bail2;
  662. }
  663. GENERAL_NAME_set0_value(gen, GEN_DNS, ia5);
  664. sk_GENERAL_NAME_push(gens, gen);
  665. if (X509_add1_ext_i2d(vhost->tls.ss->x509, NID_subject_alt_name,
  666. gens, 0, X509V3_ADD_APPEND) != 1)
  667. goto bail2;
  668. GENERAL_NAMES_free(gens);
  669. }
  670. /* sign it with our private key */
  671. if (!X509_sign(vhost->tls.ss->x509, vhost->tls.ss->pkey, EVP_sha256()))
  672. goto bail2;
  673. #if 0
  674. {/* useful to take a sample of a working cert for mbedtls to crib */
  675. FILE *fp = fopen("/tmp/acme-temp-cert", "w+");
  676. i2d_X509_fp(fp, vhost->tls.ss->x509);
  677. fclose(fp);
  678. }
  679. #endif
  680. /* tell the vhost to use our crafted certificate */
  681. SSL_CTX_use_certificate(vhost->tls.ssl_ctx, vhost->tls.ss->x509);
  682. /* and to use our generated private key */
  683. SSL_CTX_use_PrivateKey(vhost->tls.ssl_ctx, vhost->tls.ss->pkey);
  684. return 0;
  685. bail2:
  686. RSA_free(vhost->tls.ss->rsa);
  687. bail1:
  688. EVP_PKEY_free(vhost->tls.ss->pkey);
  689. bail0:
  690. X509_free(vhost->tls.ss->x509);
  691. bail:
  692. lws_free(vhost->tls.ss);
  693. GENERAL_NAMES_free(gens);
  694. return 1;
  695. }
  696. void
  697. lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost)
  698. {
  699. if (!vhost->tls.ss)
  700. return;
  701. EVP_PKEY_free(vhost->tls.ss->pkey);
  702. X509_free(vhost->tls.ss->x509);
  703. lws_free_set_NULL(vhost->tls.ss);
  704. }
  705. static int
  706. lws_tls_openssl_add_nid(X509_NAME *name, int nid, const char *value)
  707. {
  708. X509_NAME_ENTRY *e;
  709. int n;
  710. if (!value || value[0] == '\0')
  711. value = "none";
  712. e = X509_NAME_ENTRY_create_by_NID(NULL, nid, MBSTRING_ASC,
  713. (unsigned char *)value, -1);
  714. if (!e)
  715. return 1;
  716. n = X509_NAME_add_entry(name, e, -1, 0);
  717. X509_NAME_ENTRY_free(e);
  718. return n != 1;
  719. }
  720. static int nid_list[] = {
  721. NID_countryName, /* LWS_TLS_REQ_ELEMENT_COUNTRY */
  722. NID_stateOrProvinceName, /* LWS_TLS_REQ_ELEMENT_STATE */
  723. NID_localityName, /* LWS_TLS_REQ_ELEMENT_LOCALITY */
  724. NID_organizationName, /* LWS_TLS_REQ_ELEMENT_ORGANIZATION */
  725. NID_commonName, /* LWS_TLS_REQ_ELEMENT_COMMON_NAME */
  726. NID_subject_alt_name, /* LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME */
  727. NID_pkcs9_emailAddress, /* LWS_TLS_REQ_ELEMENT_EMAIL */
  728. };
  729. int
  730. lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],
  731. uint8_t *csr, size_t csr_len, char **privkey_pem,
  732. size_t *privkey_len)
  733. {
  734. uint8_t *csr_in = csr;
  735. RSA *rsakey;
  736. X509_REQ *req;
  737. X509_NAME *subj;
  738. EVP_PKEY *pkey;
  739. char *p, *end;
  740. BIO *bio;
  741. long bio_len;
  742. int n, ret = -1;
  743. if (lws_tls_openssl_rsa_new_key(&rsakey, 4096))
  744. return -1;
  745. pkey = EVP_PKEY_new();
  746. if (!pkey)
  747. goto bail0;
  748. if (!EVP_PKEY_set1_RSA(pkey, rsakey))
  749. goto bail1;
  750. req = X509_REQ_new();
  751. if (!req)
  752. goto bail1;
  753. X509_REQ_set_pubkey(req, pkey);
  754. subj = X509_NAME_new();
  755. if (!subj)
  756. goto bail2;
  757. for (n = 0; n < LWS_TLS_REQ_ELEMENT_COUNT; n++)
  758. if (elements[n] &&
  759. lws_tls_openssl_add_nid(subj, nid_list[n],
  760. elements[n])) {
  761. lwsl_notice("%s: failed to add element %d\n",
  762. __func__, n);
  763. goto bail3;
  764. }
  765. if (X509_REQ_set_subject_name(req, subj) != 1)
  766. goto bail3;
  767. if (elements[LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME]) {
  768. STACK_OF(X509_EXTENSION) *exts;
  769. X509_EXTENSION *ext;
  770. char san[256];
  771. exts = sk_X509_EXTENSION_new_null();
  772. if (!exts)
  773. goto bail3;
  774. lws_snprintf(san, sizeof(san), "DNS:%s,DNS:%s",
  775. elements[LWS_TLS_REQ_ELEMENT_COMMON_NAME],
  776. elements[LWS_TLS_REQ_ELEMENT_SUBJECT_ALT_NAME]);
  777. ext = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_alt_name,
  778. san);
  779. if (!ext) {
  780. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  781. goto bail3;
  782. }
  783. sk_X509_EXTENSION_push(exts, ext);
  784. if (!X509_REQ_add_extensions(req, exts)) {
  785. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  786. goto bail3;
  787. }
  788. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  789. }
  790. if (!X509_REQ_sign(req, pkey, EVP_sha256()))
  791. goto bail3;
  792. /*
  793. * issue the CSR as PEM to a BIO, and translate to b64urlenc without
  794. * headers, trailers, or whitespace
  795. */
  796. bio = BIO_new(BIO_s_mem());
  797. if (!bio)
  798. goto bail3;
  799. if (PEM_write_bio_X509_REQ(bio, req) != 1) {
  800. BIO_free(bio);
  801. goto bail3;
  802. }
  803. bio_len = BIO_get_mem_data(bio, &p);
  804. end = p + bio_len;
  805. /* strip the header line */
  806. while (p < end && *p != '\n')
  807. p++;
  808. while (p < end && csr_len) {
  809. if (*p == '\n') {
  810. p++;
  811. continue;
  812. }
  813. if (*p == '-')
  814. break;
  815. if (*p == '+')
  816. *csr++ = '-';
  817. else
  818. if (*p == '/')
  819. *csr++ = '_';
  820. else
  821. *csr++ = *p;
  822. p++;
  823. csr_len--;
  824. }
  825. BIO_free(bio);
  826. if (!csr_len) {
  827. lwsl_notice("%s: need %ld for CSR\n", __func__, bio_len);
  828. goto bail3;
  829. }
  830. /*
  831. * Also return the private key as a PEM in memory
  832. * (platform may not have a filesystem)
  833. */
  834. bio = BIO_new(BIO_s_mem());
  835. if (!bio)
  836. goto bail3;
  837. if (PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, 0, NULL) != 1) {
  838. BIO_free(bio);
  839. goto bail3;
  840. }
  841. bio_len = BIO_get_mem_data(bio, &p);
  842. *privkey_pem = malloc(bio_len); /* malloc so user code can own / free */
  843. *privkey_len = (size_t)bio_len;
  844. if (!*privkey_pem) {
  845. lwsl_notice("%s: need %ld for private key\n", __func__,
  846. bio_len);
  847. BIO_free(bio);
  848. goto bail3;
  849. }
  850. memcpy(*privkey_pem, p, (int)(long long)bio_len);
  851. BIO_free(bio);
  852. ret = lws_ptr_diff(csr, csr_in);
  853. bail3:
  854. X509_NAME_free(subj);
  855. bail2:
  856. X509_REQ_free(req);
  857. bail1:
  858. EVP_PKEY_free(pkey);
  859. bail0:
  860. RSA_free(rsakey);
  861. return ret;
  862. }
  863. #endif