ssl-client.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation:
  9. * version 2.1 of the License.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301 USA
  20. */
  21. #include "private-libwebsockets.h"
  22. extern int openssl_websocket_private_data_index,
  23. openssl_SSL_CTX_private_data_index;
  24. extern void
  25. lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info);
  26. extern int lws_ssl_get_error(struct lws *wsi, int n);
  27. #ifdef USE_WOLFSSL
  28. #else
  29. static int
  30. OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
  31. {
  32. SSL *ssl;
  33. int n;
  34. struct lws *wsi;
  35. /* keep old behaviour accepting self-signed server certs */
  36. if (!preverify_ok) {
  37. int err = X509_STORE_CTX_get_error(x509_ctx);
  38. if (err != X509_V_OK) {
  39. ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  40. wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
  41. if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
  42. err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
  43. wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED) {
  44. lwsl_notice("accepting self-signed certificate (verify_callback)\n");
  45. X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
  46. return 1; // ok
  47. } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID ||
  48. err == X509_V_ERR_CERT_HAS_EXPIRED) &&
  49. wsi->use_ssl & LCCSCF_ALLOW_EXPIRED) {
  50. if (err == X509_V_ERR_CERT_NOT_YET_VALID)
  51. lwsl_notice("accepting not yet valid certificate (verify_callback)\n");
  52. else if (err == X509_V_ERR_CERT_HAS_EXPIRED)
  53. lwsl_notice("accepting expired certificate (verify_callback)\n");
  54. X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
  55. return 1; // ok
  56. }
  57. }
  58. }
  59. ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  60. wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
  61. n = lws_get_context_protocol(wsi->context, 0).callback(wsi, LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION, x509_ctx, ssl, preverify_ok);
  62. /* keep old behaviour if something wrong with server certs */
  63. /* if ssl error is overruled in callback and cert is ok,
  64. * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and
  65. * return value is 0 from callback */
  66. if (!preverify_ok) {
  67. int err = X509_STORE_CTX_get_error(x509_ctx);
  68. if (err != X509_V_OK) { /* cert validation error was not handled in callback */
  69. int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
  70. const char* msg = X509_verify_cert_error_string(err);
  71. lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;depth=%d)\n", msg, preverify_ok, err, depth);
  72. return preverify_ok; // not ok
  73. }
  74. }
  75. /* convert callback return code from 0 = OK to verify callback return value 1 = OK */
  76. return !n;
  77. }
  78. #endif
  79. int
  80. lws_ssl_client_bio_create(struct lws *wsi)
  81. {
  82. char hostname[128], *p;
  83. if (lws_hdr_copy(wsi, hostname, sizeof(hostname),
  84. _WSI_TOKEN_CLIENT_HOST) <= 0) {
  85. lwsl_err("%s: Unable to get hostname\n", __func__);
  86. return -1;
  87. }
  88. /*
  89. * remove any :port part on the hostname... necessary for network
  90. * connection but typical certificates do not contain it
  91. */
  92. p = hostname;
  93. while (*p) {
  94. if (*p == ':') {
  95. *p = '\0';
  96. break;
  97. }
  98. p++;
  99. }
  100. wsi->ssl = SSL_new(wsi->vhost->ssl_client_ctx);
  101. if (!wsi->ssl) {
  102. lwsl_err("SSL_new failed: %s\n",
  103. ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
  104. lws_decode_ssl_error();
  105. return -1;
  106. }
  107. #if defined LWS_HAVE_X509_VERIFY_PARAM_set1_host
  108. X509_VERIFY_PARAM *param;
  109. (void)param;
  110. if (!(wsi->use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {
  111. param = SSL_get0_param(wsi->ssl);
  112. /* Enable automatic hostname checks */
  113. X509_VERIFY_PARAM_set_hostflags(param,
  114. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  115. X509_VERIFY_PARAM_set1_host(param, hostname, 0);
  116. }
  117. #endif
  118. #ifndef USE_WOLFSSL
  119. #ifndef USE_OLD_CYASSL
  120. /* OpenSSL_client_verify_callback will be called @ SSL_connect() */
  121. SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback);
  122. #endif
  123. #endif
  124. #ifndef USE_WOLFSSL
  125. SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  126. #endif
  127. /*
  128. * use server name indication (SNI), if supported,
  129. * when establishing connection
  130. */
  131. #ifdef USE_WOLFSSL
  132. #ifdef USE_OLD_CYASSL
  133. #ifdef CYASSL_SNI_HOST_NAME
  134. CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME, hostname, strlen(hostname));
  135. #endif
  136. #else
  137. #ifdef WOLFSSL_SNI_HOST_NAME
  138. wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME, hostname, strlen(hostname));
  139. #endif
  140. #endif
  141. #else
  142. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  143. SSL_set_tlsext_host_name(wsi->ssl, hostname);
  144. #endif
  145. #endif
  146. #ifdef USE_WOLFSSL
  147. /*
  148. * wolfSSL/CyaSSL does certificate verification differently
  149. * from OpenSSL.
  150. * If we should ignore the certificate, we need to set
  151. * this before SSL_new and SSL_connect is called.
  152. * Otherwise the connect will simply fail with error code -155
  153. */
  154. #ifdef USE_OLD_CYASSL
  155. if (wsi->use_ssl == 2)
  156. CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
  157. #else
  158. if (wsi->use_ssl == 2)
  159. wolfSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
  160. #endif
  161. #endif /* USE_WOLFSSL */
  162. wsi->client_bio = BIO_new_socket(wsi->desc.sockfd, BIO_NOCLOSE);
  163. SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
  164. #ifdef USE_WOLFSSL
  165. #ifdef USE_OLD_CYASSL
  166. CyaSSL_set_using_nonblock(wsi->ssl, 1);
  167. #else
  168. wolfSSL_set_using_nonblock(wsi->ssl, 1);
  169. #endif
  170. #else
  171. BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
  172. #endif
  173. SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index,
  174. wsi);
  175. return 0;
  176. }
  177. int
  178. lws_ssl_client_connect1(struct lws *wsi)
  179. {
  180. struct lws_context *context = wsi->context;
  181. int n = 0;
  182. lws_latency_pre(context, wsi);
  183. n = SSL_connect(wsi->ssl);
  184. lws_latency(context, wsi,
  185. "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
  186. if (n < 0) {
  187. n = lws_ssl_get_error(wsi, n);
  188. if (n == SSL_ERROR_WANT_READ)
  189. goto some_wait;
  190. if (n == SSL_ERROR_WANT_WRITE) {
  191. /*
  192. * wants us to retry connect due to
  193. * state of the underlying ssl layer...
  194. * but since it may be stalled on
  195. * blocked write, no incoming data may
  196. * arrive to trigger the retry.
  197. * Force (possibly many times if the SSL
  198. * state persists in returning the
  199. * condition code, but other sockets
  200. * are getting serviced inbetweentimes)
  201. * us to get called back when writable.
  202. */
  203. lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
  204. lws_callback_on_writable(wsi);
  205. some_wait:
  206. wsi->mode = LWSCM_WSCL_WAITING_SSL;
  207. return 0; /* no error */
  208. }
  209. {
  210. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  211. char *p = (char *)&pt->serv_buf[0];
  212. char *sb = p;
  213. lwsl_err("ssl hs1 error, X509_V_ERR = %d: %s\n",
  214. n, ERR_error_string(n, sb));
  215. lws_ssl_elaborate_error();
  216. }
  217. n = -1;
  218. }
  219. if (n <= 0) {
  220. /*
  221. * retry if new data comes until we
  222. * run into the connection timeout or win
  223. */
  224. unsigned long error = ERR_get_error();
  225. if (error != SSL_ERROR_NONE) {
  226. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  227. char *p = (char *)&pt->serv_buf[0];
  228. char *sb = p;
  229. lwsl_err("SSL connect error %lu: %s\n",
  230. error, ERR_error_string(error, sb));
  231. return -1;
  232. }
  233. }
  234. return 1;
  235. }
  236. int
  237. lws_ssl_client_connect2(struct lws *wsi)
  238. {
  239. struct lws_context *context = wsi->context;
  240. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  241. char *p = (char *)&pt->serv_buf[0];
  242. char *sb = p;
  243. int n = 0;
  244. if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
  245. lws_latency_pre(context, wsi);
  246. n = SSL_connect(wsi->ssl);
  247. lwsl_notice("%s: SSL_connect says %d\n", __func__, n);
  248. lws_latency(context, wsi,
  249. "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0);
  250. if (n < 0) {
  251. n = lws_ssl_get_error(wsi, n);
  252. if (n == SSL_ERROR_WANT_READ) {
  253. lwsl_info("SSL_connect WANT_READ... retrying\n");
  254. wsi->mode = LWSCM_WSCL_WAITING_SSL;
  255. return 0; /* no error */
  256. }
  257. if (n == SSL_ERROR_WANT_WRITE) {
  258. /*
  259. * wants us to retry connect due to
  260. * state of the underlying ssl layer...
  261. * but since it may be stalled on
  262. * blocked write, no incoming data may
  263. * arrive to trigger the retry.
  264. * Force (possibly many times if the SSL
  265. * state persists in returning the
  266. * condition code, but other sockets
  267. * are getting serviced inbetweentimes)
  268. * us to get called back when writable.
  269. */
  270. lwsl_info("SSL_connect WANT_WRITE... retrying\n");
  271. lws_callback_on_writable(wsi);
  272. wsi->mode = LWSCM_WSCL_WAITING_SSL;
  273. return 0; /* no error */
  274. }
  275. n = -1;
  276. }
  277. if (n <= 0) {
  278. /*
  279. * retry if new data comes until we
  280. * run into the connection timeout or win
  281. */
  282. unsigned long error = ERR_get_error();
  283. if (error != SSL_ERROR_NONE) {
  284. lwsl_err("SSL connect error %lu: %s\n",
  285. error, ERR_error_string(error, sb));
  286. return -1;
  287. }
  288. }
  289. }
  290. #ifndef USE_WOLFSSL
  291. /*
  292. * See comment above about wolfSSL certificate
  293. * verification
  294. */
  295. lws_latency_pre(context, wsi);
  296. n = SSL_get_verify_result(wsi->ssl);
  297. lws_latency(context, wsi,
  298. "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0);
  299. if (n != X509_V_OK) {
  300. if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
  301. n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) &&
  302. (wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED)) {
  303. lwsl_notice("accepting self-signed certificate\n");
  304. } else if ((n == X509_V_ERR_CERT_NOT_YET_VALID ||
  305. n == X509_V_ERR_CERT_HAS_EXPIRED) &&
  306. (wsi->use_ssl & LCCSCF_ALLOW_EXPIRED)) {
  307. lwsl_notice("accepting expired certificate\n");
  308. } else if (n == X509_V_ERR_CERT_NOT_YET_VALID) {
  309. lwsl_notice("Cert is from the future... "
  310. "probably our clock... accepting...\n");
  311. } else {
  312. lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
  313. n, ERR_error_string(n, sb));
  314. lws_ssl_elaborate_error();
  315. return -1;
  316. }
  317. }
  318. #endif /* USE_WOLFSSL */
  319. return 1;
  320. }
  321. int lws_context_init_client_ssl(struct lws_context_creation_info *info,
  322. struct lws_vhost *vhost)
  323. {
  324. SSL_METHOD *method = NULL;
  325. struct lws wsi;
  326. unsigned long error;
  327. const char *cipher_list = info->ssl_cipher_list;
  328. const char *ca_filepath = info->ssl_ca_filepath;
  329. const char *cert_filepath = info->ssl_cert_filepath;
  330. const char *private_key_filepath = info->ssl_private_key_filepath;
  331. int n;
  332. /*
  333. * for backwards-compatibility default to using ssl_... members, but
  334. * if the newer client-specific ones are given, use those
  335. */
  336. if (info->client_ssl_cipher_list)
  337. cipher_list = info->client_ssl_cipher_list;
  338. if (info->client_ssl_ca_filepath)
  339. ca_filepath = info->client_ssl_ca_filepath;
  340. if (info->client_ssl_cert_filepath)
  341. cert_filepath = info->client_ssl_cert_filepath;
  342. if (info->client_ssl_private_key_filepath)
  343. private_key_filepath = info->client_ssl_private_key_filepath;
  344. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
  345. return 0;
  346. if (info->provided_client_ssl_ctx) {
  347. /* use the provided OpenSSL context if given one */
  348. vhost->ssl_client_ctx = info->provided_client_ssl_ctx;
  349. /* nothing for lib to delete */
  350. vhost->user_supplied_ssl_ctx = 1;
  351. return 0;
  352. }
  353. if (info->port != CONTEXT_PORT_NO_LISTEN)
  354. return 0;
  355. /* basic openssl init already happened in context init */
  356. /* choose the most recent spin of the api */
  357. #if defined(LWS_HAVE_TLS_CLIENT_METHOD)
  358. method = (SSL_METHOD *)TLS_client_method();
  359. #elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD)
  360. method = (SSL_METHOD *)TLSv1_2_client_method();
  361. #else
  362. method = (SSL_METHOD *)SSLv23_client_method();
  363. #endif
  364. if (!method) {
  365. error = ERR_get_error();
  366. lwsl_err("problem creating ssl method %lu: %s\n",
  367. error, ERR_error_string(error,
  368. (char *)vhost->context->pt[0].serv_buf));
  369. return 1;
  370. }
  371. /* create context */
  372. vhost->ssl_client_ctx = SSL_CTX_new(method);
  373. if (!vhost->ssl_client_ctx) {
  374. error = ERR_get_error();
  375. lwsl_err("problem creating ssl context %lu: %s\n",
  376. error, ERR_error_string(error,
  377. (char *)vhost->context->pt[0].serv_buf));
  378. return 1;
  379. }
  380. #ifdef SSL_OP_NO_COMPRESSION
  381. SSL_CTX_set_options(vhost->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
  382. #endif
  383. SSL_CTX_set_options(vhost->ssl_client_ctx,
  384. SSL_OP_CIPHER_SERVER_PREFERENCE);
  385. if (cipher_list)
  386. SSL_CTX_set_cipher_list(vhost->ssl_client_ctx, cipher_list);
  387. #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
  388. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
  389. /* loads OS default CA certs */
  390. SSL_CTX_set_default_verify_paths(vhost->ssl_client_ctx);
  391. #endif
  392. /* openssl init for cert verification (for client sockets) */
  393. if (!ca_filepath) {
  394. if (!SSL_CTX_load_verify_locations(
  395. vhost->ssl_client_ctx, NULL,
  396. LWS_OPENSSL_CLIENT_CERTS))
  397. lwsl_err(
  398. "Unable to load SSL Client certs from %s "
  399. "(set by --with-client-cert-dir= "
  400. "in configure) -- client ssl isn't "
  401. "going to work\n", LWS_OPENSSL_CLIENT_CERTS);
  402. } else
  403. if (!SSL_CTX_load_verify_locations(
  404. vhost->ssl_client_ctx, ca_filepath, NULL)) {
  405. lwsl_err(
  406. "Unable to load SSL Client certs "
  407. "file from %s -- client ssl isn't "
  408. "going to work\n", info->client_ssl_ca_filepath);
  409. lws_ssl_elaborate_error();
  410. }
  411. else
  412. lwsl_info("loaded ssl_ca_filepath\n");
  413. /*
  414. * callback allowing user code to load extra verification certs
  415. * helping the client to verify server identity
  416. */
  417. /* support for client-side certificate authentication */
  418. if (cert_filepath) {
  419. lwsl_notice("%s: doing cert filepath\n", __func__);
  420. n = SSL_CTX_use_certificate_chain_file(vhost->ssl_client_ctx,
  421. cert_filepath);
  422. if (n < 1) {
  423. lwsl_err("problem %d getting cert '%s'\n", n,
  424. cert_filepath);
  425. lws_ssl_elaborate_error();
  426. return 1;
  427. }
  428. lwsl_notice("Loaded client cert %s\n", cert_filepath);
  429. }
  430. if (private_key_filepath) {
  431. lwsl_notice("%s: doing private key filepath\n", __func__);
  432. lws_ssl_bind_passphrase(vhost->ssl_client_ctx, info);
  433. /* set the private key from KeyFile */
  434. if (SSL_CTX_use_PrivateKey_file(vhost->ssl_client_ctx,
  435. private_key_filepath, SSL_FILETYPE_PEM) != 1) {
  436. lwsl_err("use_PrivateKey_file '%s'\n",
  437. private_key_filepath);
  438. lws_ssl_elaborate_error();
  439. return 1;
  440. }
  441. lwsl_notice("Loaded client cert private key %s\n",
  442. private_key_filepath);
  443. /* verify private key */
  444. if (!SSL_CTX_check_private_key(vhost->ssl_client_ctx)) {
  445. lwsl_err("Private SSL key doesn't match cert\n");
  446. return 1;
  447. }
  448. }
  449. /*
  450. * give him a fake wsi with context set, so he can use
  451. * lws_get_context() in the callback
  452. */
  453. memset(&wsi, 0, sizeof(wsi));
  454. wsi.vhost = vhost;
  455. wsi.context = vhost->context;
  456. vhost->protocols[0].callback(&wsi,
  457. LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
  458. vhost->ssl_client_ctx, NULL, 0);
  459. return 0;
  460. }