Coverage Report

Created: 2026-08-31 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebsockets/lib/tls/tls-server.c
Line
Count
Source
1
/*
2
 * libwebsockets - small server side websockets and web server implementation
3
 *
4
 * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
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
25
#include "private-lib-core.h"
26
27
#if defined(LWS_WITH_SERVER)
28
29
static void
30
lws_sul_tls_cb(lws_sorted_usec_list_t *sul)
31
0
{
32
0
  struct lws_context_per_thread *pt = lws_container_of(sul,
33
0
      struct lws_context_per_thread, sul_tls);
34
35
0
  lws_tls_check_all_cert_lifetimes(pt->context);
36
37
0
  __lws_sul_insert_us(&pt->pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
38
0
          &pt->sul_tls,
39
0
          (lws_usec_t)24 * 3600 * LWS_US_PER_SEC);
40
0
}
41
42
int
43
lws_context_init_server_ssl(const struct lws_context_creation_info *info,
44
          struct lws_vhost *vhost)
45
0
{
46
0
  struct lws_context *context = vhost->context;
47
0
  lws_fakewsi_def_plwsa(&vhost->context->pt[0]);
48
49
0
  lws_fakewsi_prep_plwsa_ctx(vhost->context);
50
51
0
  if (!lws_check_opt(info->options,
52
0
         LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {
53
0
    vhost->tls.use_ssl = 0;
54
55
0
    return 0;
56
0
  }
57
58
  /*
59
   * If he is giving a server cert, take it as a sign he wants to use
60
   * it on this vhost.  User code can leave the cert filepath NULL and
61
   * set the LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX option itself, in
62
   * which case he's expected to set up the cert himself at
63
   * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which
64
   * provides the vhost SSL_CTX * in the user parameter.
65
   */
66
0
  if (info->ssl_cert_filepath || info->server_ssl_cert_mem)
67
0
    vhost->options |= LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX;
68
69
0
  if (info->port != CONTEXT_PORT_NO_LISTEN) {
70
71
0
    vhost->tls.use_ssl = lws_check_opt(vhost->options,
72
0
          LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX);
73
74
0
    if (vhost->tls.use_ssl && info->ssl_cipher_list)
75
0
      lwsl_notice(" SSL ciphers: '%s'\n",
76
0
            info->ssl_cipher_list);
77
78
0
    lwsl_info(" Vhost '%s' using %sTLS mode\n",
79
0
          vhost->name, vhost->tls.use_ssl ? "" : "non-");
80
0
  }
81
82
  /*
83
   * give him a fake wsi with context + vhost set, so he can use
84
   * lws_get_context() in the callback
85
   */
86
0
  plwsa->vhost = vhost; /* not a real bound wsi */
87
88
  /*
89
   * as a server, if we are requiring clients to identify themselves
90
   * then set the backend up for it
91
   */
92
0
  if (lws_check_opt(info->options,
93
0
        LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT))
94
    /* Normally SSL listener rejects non-ssl, optionally allow */
95
0
    vhost->tls.allow_non_ssl_on_ssl_port = 1;
96
97
  /*
98
   * give user code a chance to load certs into the server
99
   * allowing it to verify incoming client certs
100
   */
101
0
  if (vhost->tls.use_ssl) {
102
0
    if (lws_tls_server_vhost_backend_init(info, vhost, (struct lws *)plwsa))
103
0
      return -1;
104
105
0
    if (vhost->tls.ssl_ctx && !vhost->tls.active_ctx_ref)
106
0
      vhost->tls.active_ctx_ref = lws_tls_ctx_ref_create(vhost, vhost->tls.ssl_ctx);
107
108
0
    lws_tls_server_client_cert_verify_config(vhost);
109
110
0
    if (vhost->protocols[0].callback((struct lws *)plwsa,
111
0
          LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
112
0
          vhost->tls.ssl_ctx, vhost, 0))
113
0
      return -1;
114
0
  }
115
116
0
  if (vhost->tls.use_ssl)
117
0
    lws_context_init_alpn(vhost);
118
119
  /* check certs in a few seconds (after protocol init) and then once a day */
120
121
0
  context->pt[0].sul_tls.cb = lws_sul_tls_cb;
122
0
  __lws_sul_insert_us(&context->pt[0].pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
123
0
          &context->pt[0].sul_tls,
124
0
          (lws_usec_t)5 * LWS_US_PER_SEC);
125
126
0
  return 0;
127
0
}
128
#endif
129
130
#if defined(LWS_WITH_TCP_TLS)
131
int
132
lws_tls_server_accept_completed(struct lws *wsi, int n)
133
0
{
134
0
  struct lws_context *context = wsi->a.context;
135
0
  struct lws_vhost *vh;
136
137
0
  lwsl_info("SSL_accept says %d\n", n);
138
0
  switch (n) {
139
0
  case LWS_SSL_CAPABLE_DONE:
140
0
    lws_tls_restrict_return_handshake(wsi);
141
0
    break;
142
0
  case LWS_SSL_CAPABLE_ERROR:
143
0
    lws_tls_restrict_return_handshake(wsi);
144
0
    lwsl_info("%s: SSL_accept failed socket %u: %d\n",
145
0
        __func__, wsi->desc.sockfd, n);
146
0
    wsi->socket_is_permanently_unusable = 1;
147
0
    return 1;
148
149
0
  default: /* MORE_SERVICE */
150
    // lwsl_notice("%s: %s: MORE_SERVICE (%d), setting LRS_SSL_ACK_PENDING\n", __func__, lws_wsi_tag(wsi), n);
151
0
    if (n == LWS_SSL_CAPABLE_MORE_SERVICE_READ) {
152
0
      if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
153
0
        return 1;
154
0
    } else if (n == LWS_SSL_CAPABLE_MORE_SERVICE_WRITE) {
155
0
      if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
156
0
        return 1;
157
0
    }
158
0
    lwsi_set_state(wsi, LRS_SSL_ACK_PENDING);
159
0
    return 0;
160
0
  }
161
162
  /* adapt our vhost to match the SNI SSL_CTX that was chosen */
163
0
  vh = lws_vhost_first(context);
164
0
  while (vh) {
165
0
    if (!vh->being_destroyed && wsi->tls.ssl &&
166
0
        vh->tls.ssl_ctx == lws_tls_ctx_from_wsi(wsi)) {
167
0
      lwsl_info("setting wsi to vh %s\n", vh->name);
168
0
      lws_vhost_bind_wsi(vh, wsi);
169
0
      break;
170
0
    }
171
0
    vh = lws_vhost_next(vh);
172
0
  }
173
174
  /* OK, we are accepted... give him some time to negotiate */
175
0
  lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
176
0
      (int)context->timeout_secs);
177
178
0
  lwsi_set_state(wsi, LRS_ESTABLISHED);
179
0
  if (lws_tls_server_conn_alpn(wsi)) {
180
0
    lwsl_warn("%s: fail on alpn\n", __func__);
181
0
    return 1; /* fail */
182
0
  }
183
0
  lwsl_debug("accepted new SSL conn\n");
184
185
186
  /* continue establishment */
187
0
  wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
188
189
0
  return 0;
190
0
}
191
192
int
193
lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd, char from_pollin)
194
0
{
195
0
  struct lws_context *context = wsi->a.context;
196
0
  struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
197
0
  ssize_t s;
198
0
  int n;
199
200
0
  if (!LWS_SSL_ENABLED(wsi->a.vhost))
201
0
    return 0;
202
203
0
  switch (lwsi_state(wsi)) {
204
0
  case LRS_SSL_INIT:
205
206
0
    if (wsi->tls.ssl)
207
0
      lwsl_err("%s: leaking ssl\n", __func__);
208
0
    if (accept_fd == LWS_SOCK_INVALID)
209
0
      assert(0);
210
211
0
    if (lws_tls_restrict_borrow(wsi)) {
212
0
      lwsl_err("%s: failed on ssl restriction\n", __func__);
213
0
      return 1;
214
0
    }
215
216
#if defined(LWS_WITH_LATENCY)
217
    lws_usec_t _ssl_new_start = lws_now_usecs();
218
#endif
219
220
0
    if (lws_tls_server_new_nonblocking(wsi, accept_fd)) {
221
0
      lwsl_err("%s: failed on lws_tls_server_new_nonblocking\n", __func__);
222
0
      if (accept_fd != LWS_SOCK_INVALID)
223
0
        compatible_close(accept_fd);
224
0
      lws_tls_restrict_return(wsi);
225
0
      goto fail;
226
0
    }
227
228
#if defined(LWS_WITH_LATENCY)
229
    {
230
      unsigned int ms = (unsigned int)((lws_now_usecs() - _ssl_new_start) / 1000);
231
      if (ms > 2)
232
        lws_latency_note(pt, _ssl_new_start, 2000, "sslnew:%dms", ms);
233
    }
234
#endif
235
236
    /*
237
     * we are not accepted yet, but we need to enter ourselves
238
     * as a live connection.  That way we can retry when more
239
     * pieces come if we're not sorted yet
240
     */
241
0
    lwsi_set_state(wsi, LRS_SSL_ACK_PENDING);
242
243
0
    lws_pt_lock(pt, __func__);
244
0
    if (__insert_wsi_socket_into_fds(context, wsi)) {
245
0
      lwsl_err("%s: failed to insert into fds\n", __func__);
246
0
      goto fail;
247
0
    }
248
0
    lws_pt_unlock(pt);
249
250
0
    lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
251
0
        (int)context->timeout_secs);
252
253
0
    lwsl_debug("inserted SSL accept into fds, trying SSL_accept\n");
254
255
    /* fallthru */
256
257
0
  case LRS_SSL_ACK_PENDING:
258
259
    // lwsl_notice("%s: %s: entering LRS_SSL_ACK_PENDING, from_pollin=%d\n", __func__, lws_wsi_tag(wsi), from_pollin);
260
261
0
    if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
262
0
      lwsl_err("%s: lws_change_pollfd failed\n", __func__);
263
0
      goto fail;
264
0
    }
265
266
0
    if (wsi->a.vhost->tls.allow_non_ssl_on_ssl_port && !wsi->skip_fallback) {
267
      /*
268
       * We came here by POLLIN, so there is supposed to be
269
       * something to read...
270
       */
271
272
0
      s = recv(wsi->desc.sockfd, (char *)pt->serv_buf,
273
0
         context->pt_serv_buf_size, MSG_PEEK);
274
      /*
275
       * We have LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT..
276
       * this just means don't hang up on him because of no
277
       * tls hello... what happens next is driven by
278
       * additional option flags:
279
       *
280
       * none: fail the connection
281
       *
282
       * LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS:
283
       *     Destroy the TLS, issue a redirect using plaintext
284
       *     http (this may not be accepted by a client that
285
       *     has visited the site before and received an STS
286
       *     header).
287
       *
288
       * LWS_SERVER_OPTION_ALLOW_HTTP_ON_HTTPS_LISTENER:
289
       *     Destroy the TLS, continue and serve normally
290
       *     using http
291
       *
292
       * LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_ACCEPT_CONFIG:
293
       *     Destroy the TLS, apply whatever role and protocol
294
       *     were told in the vhost info struct
295
       *     .listen_accept_role / .listen_accept_protocol and
296
       *     continue with that
297
       */
298
299
0
      if (s >= 1 && pt->serv_buf[0] >= ' ') {
300
        /*
301
        * TLS content-type for Handshake is 0x16, and
302
        * for ChangeCipherSpec Record, it's 0x14
303
        *
304
        * A non-ssl session will start with the HTTP
305
        * method in ASCII.  If we see it's not a legit
306
        * SSL handshake kill the SSL for this
307
        * connection and try to handle as a HTTP
308
        * connection upgrade directly.
309
        */
310
0
        wsi->tls.use_ssl = 0;
311
312
0
        lws_tls_server_abort_connection(wsi);
313
        /*
314
         * care... this creates wsi with no ssl when ssl
315
         * is enabled and normally mandatory
316
         */
317
0
        wsi->tls.ssl = NULL;
318
319
0
        if (lws_check_opt(wsi->a.vhost->options,
320
0
            LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS)) {
321
0
          lwsl_info("%s: redirecting from http "
322
0
              "to https\n", __func__);
323
0
          wsi->tls.redirect_to_https = 1;
324
0
          goto notls_accepted;
325
0
        }
326
327
0
        if (lws_check_opt(wsi->a.vhost->options,
328
0
        LWS_SERVER_OPTION_ALLOW_HTTP_ON_HTTPS_LISTENER)) {
329
0
          lwsl_info("%s: allowing unencrypted "
330
0
              "http service on tls port\n",
331
0
              __func__);
332
0
          goto notls_accepted;
333
0
        }
334
335
0
        if (lws_check_opt(wsi->a.vhost->options,
336
0
        LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_ACCEPT_CONFIG)) {
337
0
          if (lws_http_to_fallback(wsi, NULL, 0))
338
0
            goto fail;
339
0
          lwsl_info("%s: allowing non-tls "
340
0
              "fallback\n", __func__);
341
0
          goto notls_accepted;
342
0
        }
343
344
0
        char ipbuf[64];
345
346
0
        lws_get_peer_simple(wsi, ipbuf, sizeof(ipbuf));
347
0
        lwsl_notice("%s: client did not send a valid "
348
0
              "tls hello (default vhost %s) from %s\n",
349
0
              __func__, wsi->a.vhost->name, ipbuf);
350
0
        lwsl_hexdump_notice(pt->serv_buf, s > 256 ? 256 : (size_t)s);
351
0
        goto fail;
352
0
      }
353
0
      if (!s) {
354
        /*
355
         * POLLIN but nothing to read is supposed to
356
         * mean the connection is gone, we should
357
         * fail out...
358
         *
359
         */
360
0
        lwsl_debug("%s: PEEKed 0 (from_pollin %d)\n",
361
0
            __func__, from_pollin);
362
0
        if (!from_pollin) {
363
          /*
364
           * If this wasn't actually info from a
365
           * pollin let it go around again until
366
           * either data came or we still get told
367
           * zero length peek AND POLLIN
368
           */
369
0
          if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
370
0
            lwsl_err("%s: change_pollfd failed\n",
371
0
                __func__);
372
0
            return -1;
373
0
          }
374
375
0
          lwsl_info("SSL_ERROR_WANT_READ\n");
376
0
          return 0;
377
0
        }
378
379
        /*
380
         * treat as remote closed
381
         */
382
383
0
        goto fail;
384
0
      }
385
0
      if (s < 0 && (LWS_ERRNO == LWS_EAGAIN ||
386
0
              LWS_ERRNO == LWS_EWOULDBLOCK)) {
387
388
        /*
389
         * well, we get no way to know ssl or not
390
         * so go around again waiting for something
391
         * to come and give us a hint, or timeout the
392
         * connection.
393
         */
394
        // lwsl_notice("%s: %s: punting (no data peeked)\n", __func__, lws_wsi_tag(wsi));
395
0
        if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
396
0
          lwsl_err("%s: change_pollfd failed\n",
397
0
              __func__);
398
0
          return -1;
399
0
        }
400
401
0
        lwsl_info("SSL_ERROR_WANT_READ\n");
402
0
        return 0;
403
0
      }
404
0
    }
405
406
    /* normal SSL connection processing path */
407
408
#if defined(LWS_WITH_ASYNC_QUEUE)
409
    if (lwsi_state(wsi) != LRS_AWAITING_SSL_ACCEPT && context->count_async_threads) {
410
      struct lws_async_job *job;
411
412
      if (lws_change_pollfd(wsi, LWS_POLLIN | LWS_POLLOUT, 0)) {
413
        lwsl_err("%s: lws_change_pollfd failed\n", __func__);
414
        goto fail;
415
      }
416
417
      job = lws_zalloc(sizeof(*job), "async ssl job");
418
      if (!job)
419
        goto fail;
420
421
      job->wsi = wsi;
422
      wsi->async_worker_job = job;
423
      job->type = LWS_AQ_SSL_ACCEPT;
424
425
      //lwsl_notice("%s: %s: QUEUING LWS_AQ_SSL_ACCEPT\n", __func__, lws_wsi_tag(wsi));
426
427
      pthread_mutex_lock(&context->async_worker_mutex);
428
      if (lws_dll2_count(&context->async_worker_waiting) >=
429
          (uint32_t)(context->count_async_threads * 10)) {
430
        pthread_mutex_unlock(&context->async_worker_mutex);
431
        lws_free(job);
432
        wsi->async_worker_job = NULL;
433
        goto fail;
434
      }
435
      lws_dll2_add_tail(&job->list, &context->async_worker_waiting);
436
437
      if (context->async_worker_threads_idle == 0 &&
438
          context->async_worker_threads_active < context->count_async_threads) {
439
        pthread_t pt_th;
440
        context->async_worker_threads_active++;
441
        if (pthread_create(&pt_th, NULL, lws_async_worker_worker, context) == 0)
442
          pthread_detach(pt_th);
443
        else
444
          context->async_worker_threads_active--;
445
      }
446
447
      /* wake up any idle worker threads */
448
      pthread_cond_signal(&context->async_worker_cond);
449
450
      pthread_mutex_unlock(&context->async_worker_mutex);
451
452
      lwsi_set_state(wsi, LRS_AWAITING_SSL_ACCEPT);
453
      return 0;
454
    }
455
#endif
456
457
0
    errno = 0;
458
#if defined(LWS_WITH_LATENCY)
459
    lws_usec_t _ssl_acc_start = lws_now_usecs();
460
#endif
461
0
    n = lws_tls_server_accept(wsi);
462
463
#if defined(LWS_WITH_LATENCY)
464
    {
465
      unsigned int ms = (unsigned int)((lws_now_usecs() - _ssl_acc_start) / 1000);
466
      if (ms > 2)
467
        lws_latency_note(pt, _ssl_acc_start, 2000, "sslacc:%dms", ms);
468
    }
469
#endif
470
471
0
    if (lws_tls_server_accept_completed(wsi, n))
472
0
      goto fail;
473
474
0
    if (lwsi_state(wsi) != LRS_ESTABLISHED)
475
0
      return 0;
476
477
0
    break;
478
479
0
  default:
480
0
    break;
481
0
  }
482
483
0
  return 0;
484
485
0
notls_accepted:
486
0
  lwsi_set_state(wsi, LRS_ESTABLISHED);
487
488
0
  return 0;
489
490
0
fail:
491
0
  return 1;
492
0
}
493
#endif
494