Coverage Report

Created: 2026-10-28 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl41/ssl/statem/statem.c
Line
Count
Source
1
/*
2
 * Copyright 2015-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include "internal/e_os.h"
11
12
#if defined(__TANDEM) && defined(_SPT_MODEL_)
13
#include <spthread.h>
14
#include <spt_extensions.h> /* timeval */
15
#endif
16
17
#include "internal/cryptlib.h"
18
#include "internal/ssl_unwrap.h"
19
#include <openssl/rand.h>
20
#include "../ssl_local.h"
21
#include "statem_local.h"
22
#include <assert.h>
23
24
/*
25
 * This file implements the SSL/TLS/DTLS state machines.
26
 *
27
 * There are two primary state machines:
28
 *
29
 * 1) Message flow state machine
30
 * 2) Handshake state machine
31
 *
32
 * The Message flow state machine controls the reading and sending of messages
33
 * including handling of non-blocking IO events, flushing of the underlying
34
 * write BIO, handling unexpected messages, etc. It is itself broken into two
35
 * separate sub-state machines which control reading and writing respectively.
36
 *
37
 * The Handshake state machine keeps track of the current SSL/TLS handshake
38
 * state. Transitions of the handshake state are the result of events that
39
 * occur within the Message flow state machine.
40
 *
41
 * Overall it looks like this:
42
 *
43
 * ---------------------------------------------            -------------------
44
 * |                                           |            |                 |
45
 * | Message flow state machine                |            |                 |
46
 * |                                           |            |                 |
47
 * | -------------------- -------------------- | Transition | Handshake state |
48
 * | | MSG_FLOW_READING | | MSG_FLOW_WRITING | | Event      | machine         |
49
 * | | sub-state        | | sub-state        | |----------->|                 |
50
 * | | machine for      | | machine for      | |            |                 |
51
 * | | reading messages | | writing messages | |            |                 |
52
 * | -------------------- -------------------- |            |                 |
53
 * |                                           |            |                 |
54
 * ---------------------------------------------            -------------------
55
 *
56
 */
57
58
/* Sub state machine return values */
59
typedef enum {
60
    /* Something bad happened or NBIO */
61
    SUB_STATE_ERROR,
62
    /* Sub state finished go to the next sub state */
63
    SUB_STATE_FINISHED,
64
    /* Sub state finished and handshake was completed */
65
    SUB_STATE_END_HANDSHAKE
66
} SUB_STATE_RETURN;
67
68
static int state_machine(SSL_CONNECTION *s, int server);
69
static void init_read_state_machine(SSL_CONNECTION *s);
70
static SUB_STATE_RETURN read_state_machine(SSL_CONNECTION *s);
71
static void init_write_state_machine(SSL_CONNECTION *s);
72
static SUB_STATE_RETURN write_state_machine(SSL_CONNECTION *s);
73
74
OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl)
75
401k
{
76
401k
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
77
78
401k
    if (sc == NULL)
79
0
        return TLS_ST_BEFORE;
80
81
401k
    return sc->statem.hand_state;
82
401k
}
83
84
int SSL_in_init(const SSL *s)
85
116M
{
86
116M
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
87
88
116M
    if (sc == NULL)
89
0
        return 0;
90
91
116M
    return sc->statem.in_init;
92
116M
}
93
94
int SSL_is_init_finished(const SSL *s)
95
262k
{
96
262k
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
97
98
262k
    if (sc == NULL)
99
0
        return 0;
100
101
262k
    return !(sc->statem.in_init) && (sc->statem.hand_state == TLS_ST_OK);
102
262k
}
103
104
int SSL_in_before(const SSL *s)
105
54.7M
{
106
54.7M
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
107
108
54.7M
    if (sc == NULL)
109
0
        return 0;
110
111
    /*
112
     * Historically being "in before" meant before anything had happened. In the
113
     * current code though we remain in the "before" state for a while after we
114
     * have started the handshake process (e.g. as a server waiting for the
115
     * first message to arrive). There "in before" is taken to mean "in before"
116
     * and not started any handshake process yet.
117
     */
118
54.7M
    return (sc->statem.hand_state == TLS_ST_BEFORE)
119
291k
        && (sc->statem.state == MSG_FLOW_UNINITED);
120
54.7M
}
121
122
OSSL_HANDSHAKE_STATE ossl_statem_get_state(SSL_CONNECTION *s)
123
0
{
124
0
    return s != NULL ? s->statem.hand_state : TLS_ST_BEFORE;
125
0
}
126
127
/*
128
 * Clear the state machine state and reset back to MSG_FLOW_UNINITED
129
 */
130
void ossl_statem_clear(SSL_CONNECTION *s)
131
517k
{
132
517k
    s->statem.state = MSG_FLOW_UNINITED;
133
517k
    s->statem.hand_state = TLS_ST_BEFORE;
134
517k
    s->statem.error_state = ERROR_STATE_NOERROR;
135
517k
    ossl_statem_set_in_init(s, 1);
136
517k
    s->statem.no_cert_verify = 0;
137
517k
    s->statem.ack_for_retransmit = 0;
138
517k
}
139
140
/*
141
 * Set the state machine up ready for a renegotiation handshake
142
 */
143
void ossl_statem_set_renegotiate(SSL_CONNECTION *s)
144
1.49k
{
145
1.49k
    ossl_statem_set_in_init(s, 1);
146
1.49k
    s->statem.request_state = TLS_ST_SW_HELLO_REQ;
147
1.49k
}
148
149
void ossl_statem_send_fatal(SSL_CONNECTION *s, int al)
150
86.4k
{
151
    /* We shouldn't call SSLfatal() twice. Once is enough */
152
86.4k
    if (s->statem.in_init && s->statem.state == MSG_FLOW_ERROR)
153
14
        return;
154
86.4k
    ossl_statem_set_in_init(s, 1);
155
86.4k
    s->statem.state = MSG_FLOW_ERROR;
156
86.4k
    if (al != SSL_AD_NO_ALERT && s->rlayer.wrlmethod != NULL)
157
84.5k
        ssl3_send_alert(s, SSL3_AL_FATAL, al);
158
86.4k
}
159
160
/*
161
 * Error reporting building block that's used instead of ERR_set_error().
162
 * In addition to what ERR_set_error() does, this puts the state machine
163
 * into an error state and sends an alert if appropriate.
164
 * This is a permanent error for the current connection.
165
 */
166
void ossl_statem_fatal(SSL_CONNECTION *s, int al, int reason,
167
    const char *fmt, ...)
168
84.6k
{
169
84.6k
    va_list args;
170
171
84.6k
    va_start(args, fmt);
172
84.6k
    ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
173
84.6k
    va_end(args);
174
175
84.6k
    ossl_statem_send_fatal(s, al);
176
84.6k
}
177
178
/*
179
 * This macro should only be called if we are already expecting to be in
180
 * a fatal error state. We verify that we are, and set it if not (this would
181
 * indicate a bug).
182
 */
183
#define check_fatal(s)                                               \
184
19.4k
    do {                                                             \
185
19.4k
        if (!ossl_assert((s)->statem.in_init                         \
186
19.4k
                && (s)->statem.state == MSG_FLOW_ERROR))             \
187
19.4k
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_FATAL); \
188
19.4k
    } while (0)
189
190
/*
191
 * Discover whether the current connection is in the error state.
192
 *
193
 * Valid return values are:
194
 *   1: Yes
195
 *   0: No
196
 */
197
int ossl_statem_in_error(const SSL_CONNECTION *s)
198
329k
{
199
329k
    if (s->statem.state == MSG_FLOW_ERROR)
200
0
        return 1;
201
202
329k
    return 0;
203
329k
}
204
205
void ossl_statem_set_in_init(SSL_CONNECTION *s, int init)
206
779k
{
207
779k
    s->statem.in_init = init;
208
779k
    if (s->rlayer.rrlmethod != NULL && s->rlayer.rrlmethod->set_in_init != NULL)
209
136k
        s->rlayer.rrlmethod->set_in_init(s->rlayer.rrl, init);
210
779k
}
211
212
int ossl_statem_get_in_handshake(SSL_CONNECTION *s)
213
92.6M
{
214
92.6M
    return s->statem.in_handshake;
215
92.6M
}
216
217
void ossl_statem_set_in_handshake(SSL_CONNECTION *s, int inhand)
218
8.50k
{
219
8.50k
    if (inhand)
220
4.25k
        s->statem.in_handshake++;
221
4.25k
    else
222
4.25k
        s->statem.in_handshake--;
223
8.50k
}
224
225
/* Are we in a sensible state to skip over unreadable early data? */
226
int ossl_statem_skip_early_data(SSL_CONNECTION *s)
227
133k
{
228
133k
    if (s->ext.early_data != SSL_EARLY_DATA_REJECTED)
229
2.21k
        return 0;
230
231
131k
    if (!s->server
232
131k
        || s->statem.hand_state != TLS_ST_EARLY_DATA
233
131k
        || s->hello_retry_request == SSL_HRR_COMPLETE)
234
25
        return 0;
235
236
131k
    return 1;
237
131k
}
238
239
/*
240
 * Called when we are in SSL_read*(), SSL_write*(), or SSL_accept()
241
 * /SSL_connect()/SSL_do_handshake(). Used to test whether we are in an early
242
 * data state and whether we should attempt to move the handshake on if so.
243
 * |sending| is 1 if we are attempting to send data (SSL_write*()), 0 if we are
244
 * attempting to read data (SSL_read*()), or -1 if we are in SSL_do_handshake()
245
 * or similar.
246
 */
247
int ossl_statem_check_finish_init(SSL_CONNECTION *s, int sending)
248
19.5M
{
249
    /*
250
     * A client that suppressed 0-RTT keeps SSL_write_early_data() reporting
251
     * success while the application streams early data. Any ordinary read,
252
     * write, or handshake call waits for the handshake to complete and so ends
253
     * that sequence: clear the suppressed flag, after which a further
254
     * SSL_write_early_data() returns the normal error instead of masking a
255
     * state-machine mistake. The internal SSL_connect() issued from
256
     * SSL_write_early_data() runs in the CONNECTING state and is excluded.
257
     */
258
19.5M
    if (!s->server
259
19.5M
        && s->ext.early_data_suppressed
260
0
        && s->early_data_state == SSL_EARLY_DATA_NONE)
261
0
        s->ext.early_data_suppressed = 0;
262
263
19.5M
    if (sending == -1) {
264
8.99M
        if (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
265
8.99M
            || s->statem.hand_state == TLS_ST_EARLY_DATA) {
266
464
            ossl_statem_set_in_init(s, 1);
267
464
            if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY) {
268
                /*
269
                 * SSL_connect() or SSL_do_handshake() has been called directly.
270
                 * We don't allow any more writing of early data.
271
                 */
272
0
                s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
273
0
            }
274
464
        }
275
10.5M
    } else if (!s->server) {
276
10.5M
        if ((sending && (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END || s->statem.hand_state == TLS_ST_EARLY_DATA)
277
0
                && s->early_data_state != SSL_EARLY_DATA_WRITING)
278
10.5M
            || (!sending && s->statem.hand_state == TLS_ST_EARLY_DATA)) {
279
0
            ossl_statem_set_in_init(s, 1);
280
            /*
281
             * SSL_write() has been called directly. We don't allow any more
282
             * writing of early data.
283
             */
284
0
            if (sending && s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY)
285
0
                s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
286
0
        }
287
10.5M
    } else {
288
954
        if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING
289
579
            && s->statem.hand_state == TLS_ST_EARLY_DATA)
290
0
            ossl_statem_set_in_init(s, 1);
291
954
    }
292
19.5M
    return 1;
293
19.5M
}
294
295
void ossl_statem_set_hello_verify_done(SSL_CONNECTION *s)
296
0
{
297
0
    s->statem.state = MSG_FLOW_UNINITED;
298
0
    ossl_statem_set_in_init(s, 1);
299
    /*
300
     * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
301
     * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
302
     * calls to SSL_in_before() will return false. Also calls to
303
     * SSL_state_string() and SSL_state_string_long() will return something
304
     * sensible.
305
     */
306
0
    s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
307
0
    s->statem.error_state = ERROR_STATE_NOERROR;
308
0
}
309
310
int ossl_statem_connect(SSL *s)
311
54.3M
{
312
54.3M
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
313
314
54.3M
    if (sc == NULL)
315
0
        return -1;
316
317
54.3M
    return state_machine(sc, 0);
318
54.3M
}
319
320
int ossl_statem_accept(SSL *s)
321
118k
{
322
118k
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
323
324
118k
    if (sc == NULL)
325
0
        return -1;
326
327
118k
    return state_machine(sc, 1);
328
118k
}
329
330
typedef void (*info_cb)(const SSL *, int, int);
331
332
static info_cb get_callback(SSL_CONNECTION *s)
333
129M
{
334
129M
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
335
336
129M
    if (s->info_callback != NULL)
337
0
        return s->info_callback;
338
129M
    else if (sctx->info_callback != NULL)
339
0
        return sctx->info_callback;
340
341
129M
    return NULL;
342
129M
}
343
344
/*
345
 * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
346
 * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
347
 * transitions are as follows:
348
 *
349
 * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
350
 *        |                       |
351
 *        +-----------------------+
352
 *        v
353
 * MSG_FLOW_WRITING <---> MSG_FLOW_READING
354
 *        |
355
 *        V
356
 * MSG_FLOW_FINISHED
357
 *        |
358
 *        V
359
 *    [SUCCESS]
360
 *
361
 * We may exit at any point due to an error or NBIO event. If an NBIO event
362
 * occurs then we restart at the point we left off when we are recalled.
363
 * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
364
 *
365
 * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
366
 * into that state at any point in the event that an irrecoverable error occurs.
367
 *
368
 * Valid return values are:
369
 *   1: Success
370
 * <=0: NBIO or error
371
 */
372
static int state_machine(SSL_CONNECTION *s, int server)
373
16.3M
{
374
16.3M
    BUF_MEM *buf = NULL;
375
16.3M
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
376
16.3M
    OSSL_STATEM *st = &s->statem;
377
16.3M
    int ret = -1;
378
16.3M
    int ssret;
379
16.3M
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
380
16.3M
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
381
382
16.3M
    if (st->state == MSG_FLOW_ERROR) {
383
        /* Shouldn't have been called if we're already in the error state */
384
0
        return -1;
385
0
    }
386
387
16.3M
    ERR_clear_error();
388
16.3M
    clear_sys_error();
389
390
16.3M
    cb = get_callback(s);
391
392
16.3M
    st->in_handshake++;
393
16.3M
    if (!SSL_in_init(ssl) || SSL_in_before(ssl)) {
394
        /*
395
         * If we are stateless then we already called SSL_clear() - don't do
396
         * it again and clear the STATELESS flag itself.
397
         */
398
57.8k
        if ((s->s3.flags & TLS1_FLAGS_STATELESS) == 0 && !SSL_clear(ssl))
399
0
            return -1;
400
57.8k
    }
401
#ifndef OPENSSL_NO_SCTP
402
    if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
403
        /*
404
         * Notify SCTP BIO socket to enter handshake mode and prevent stream
405
         * identifier other than 0.
406
         */
407
        BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
408
            st->in_handshake, NULL);
409
    }
410
#endif
411
412
    /* Initialise state machine */
413
16.3M
    if (st->state == MSG_FLOW_UNINITED
414
16.3M
        || st->state == MSG_FLOW_FINISHED) {
415
97.0k
        if (st->state == MSG_FLOW_UNINITED) {
416
57.8k
            st->hand_state = TLS_ST_BEFORE;
417
57.8k
            st->request_state = TLS_ST_BEFORE;
418
57.8k
        }
419
420
97.0k
        s->server = server;
421
97.0k
        if (cb != NULL) {
422
0
            if (SSL_IS_FIRST_HANDSHAKE(s) || !SSL_CONNECTION_IS_VERSION13(s))
423
0
                cb(ussl, SSL_CB_HANDSHAKE_START, 1);
424
0
        }
425
426
        /*
427
         * Fatal errors in this block don't send an alert because we have
428
         * failed to even initialise properly. Sending an alert is probably
429
         * doomed to failure.
430
         */
431
432
97.0k
        if (SSL_CONNECTION_IS_DTLS(s)) {
433
21.1k
            if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) && (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
434
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
435
0
                goto end;
436
0
            }
437
75.9k
        } else {
438
75.9k
            if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
439
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
440
0
                goto end;
441
0
            }
442
75.9k
        }
443
444
97.0k
        if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
445
0
            SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
446
0
            goto end;
447
0
        }
448
449
97.0k
        if (s->init_buf == NULL) {
450
97.0k
            if ((buf = BUF_MEM_new()) == NULL) {
451
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
452
0
                goto end;
453
0
            }
454
97.0k
            if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
455
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
456
0
                goto end;
457
0
            }
458
97.0k
            s->init_buf = buf;
459
97.0k
            buf = NULL;
460
97.0k
        }
461
462
97.0k
        s->init_num = 0;
463
464
        /*
465
         * Should have been reset by tls_process_finished, too.
466
         */
467
97.0k
        s->s3.change_cipher_spec = 0;
468
469
        /*
470
         * Ok, we now need to push on a buffering BIO ...but not with
471
         * SCTP
472
         */
473
#ifndef OPENSSL_NO_SCTP
474
        if (!SSL_CONNECTION_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(ssl)))
475
#endif
476
97.0k
            if (!ssl_init_wbio_buffer(s)) {
477
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
478
0
                goto end;
479
0
            }
480
481
97.0k
        if ((SSL_in_before(ssl))
482
57.8k
            || s->renegotiate) {
483
57.8k
            if (!tls_setup_handshake(s)) {
484
                /* SSLfatal() already called */
485
0
                goto end;
486
0
            }
487
488
57.8k
            if (SSL_IS_FIRST_HANDSHAKE(s))
489
57.8k
                st->read_state_first_init = 1;
490
57.8k
        }
491
492
97.0k
        st->state = MSG_FLOW_WRITING;
493
97.0k
        init_write_state_machine(s);
494
97.0k
    }
495
496
16.5M
    while (st->state != MSG_FLOW_FINISHED) {
497
16.5M
        if (st->state == MSG_FLOW_READING) {
498
16.3M
            ssret = read_state_machine(s);
499
16.3M
            if (ssret == SUB_STATE_FINISHED) {
500
61.8k
                st->state = MSG_FLOW_WRITING;
501
61.8k
                init_write_state_machine(s);
502
16.3M
            } else if (ssret == SUB_STATE_END_HANDSHAKE) {
503
0
                st->state = MSG_FLOW_FINISHED;
504
16.3M
            } else {
505
                /* NBIO or error */
506
16.3M
                goto end;
507
16.3M
            }
508
16.3M
        } else if (st->state == MSG_FLOW_WRITING) {
509
158k
            ssret = write_state_machine(s);
510
158k
            if (ssret == SUB_STATE_FINISHED) {
511
116k
                st->state = MSG_FLOW_READING;
512
116k
                init_read_state_machine(s);
513
116k
            } else if (ssret == SUB_STATE_END_HANDSHAKE) {
514
42.0k
                st->state = MSG_FLOW_FINISHED;
515
42.0k
            } else {
516
                /* NBIO or error */
517
561
                goto end;
518
561
            }
519
158k
        } else {
520
            /* Error */
521
0
            check_fatal(s);
522
0
            ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
523
0
            goto end;
524
0
        }
525
16.5M
    }
526
527
42.0k
    ret = 1;
528
529
16.3M
end:
530
16.3M
    st->in_handshake--;
531
532
#ifndef OPENSSL_NO_SCTP
533
    if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
534
        /*
535
         * Notify SCTP BIO socket to leave handshake mode and allow stream
536
         * identifier other than 0.
537
         */
538
        BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
539
            st->in_handshake, NULL);
540
    }
541
#endif
542
543
16.3M
    BUF_MEM_free(buf);
544
16.3M
    if (cb != NULL) {
545
0
        if (server)
546
0
            cb(ussl, SSL_CB_ACCEPT_EXIT, ret);
547
0
        else
548
0
            cb(ussl, SSL_CB_CONNECT_EXIT, ret);
549
0
    }
550
16.3M
    return ret;
551
42.0k
}
552
553
/*
554
 * Initialise the MSG_FLOW_READING sub-state machine
555
 */
556
static void init_read_state_machine(SSL_CONNECTION *s)
557
305k
{
558
305k
    OSSL_STATEM *st = &s->statem;
559
560
305k
    st->read_state = READ_STATE_HEADER;
561
305k
}
562
563
/*
564
 * This function implements the sub-state machine when the message flow is in
565
 * MSG_FLOW_READING. The valid sub-states and transitions are:
566
 *
567
 * READ_STATE_HEADER <--+<-------------+
568
 *        |             |              |
569
 *        v             |              |
570
 * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
571
 *        |                            |
572
 *        +----------------------------+
573
 *        v
574
 * [SUB_STATE_FINISHED]
575
 *
576
 * READ_STATE_HEADER has the responsibility for reading in the message header
577
 * and transitioning the state of the handshake state machine.
578
 *
579
 * READ_STATE_BODY reads in the rest of the message and then subsequently
580
 * processes it.
581
 *
582
 * READ_STATE_POST_PROCESS is an optional step that may occur if some post
583
 * processing activity performed on the message may block.
584
 *
585
 * Any of the above states could result in an NBIO event occurring in which case
586
 * control returns to the calling application. When this function is recalled we
587
 * will resume in the same state where we left off.
588
 */
589
static SUB_STATE_RETURN read_state_machine(SSL_CONNECTION *s)
590
16.3M
{
591
16.3M
    OSSL_STATEM *st = &s->statem;
592
16.3M
    int ret, mt;
593
16.3M
    size_t len = 0, headerlen;
594
16.3M
    int (*transition)(SSL_CONNECTION *s, int mt);
595
16.3M
    PACKET pkt;
596
16.3M
    MSG_PROCESS_RETURN (*process_message)(SSL_CONNECTION *s, PACKET *pkt);
597
16.3M
    WORK_STATE (*post_process_message)(SSL_CONNECTION *s, WORK_STATE wst);
598
16.3M
    size_t (*max_message_size)(SSL_CONNECTION *s);
599
16.3M
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
600
16.3M
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
601
602
16.3M
    cb = get_callback(s);
603
604
16.3M
    if (s->server) {
605
65.4k
        transition = ossl_statem_server_read_transition;
606
65.4k
        process_message = ossl_statem_server_process_message;
607
65.4k
        max_message_size = ossl_statem_server_max_message_size;
608
65.4k
        post_process_message = ossl_statem_server_post_process_message;
609
16.3M
    } else {
610
16.3M
        transition = ossl_statem_client_read_transition;
611
16.3M
        process_message = ossl_statem_client_process_message;
612
16.3M
        max_message_size = ossl_statem_client_max_message_size;
613
16.3M
        post_process_message = ossl_statem_client_post_process_message;
614
16.3M
    }
615
616
16.3M
    if (st->read_state_first_init) {
617
57.8k
        s->first_packet = 1;
618
57.8k
        st->read_state_first_init = 0;
619
57.8k
    }
620
621
16.4M
    while (1) {
622
16.4M
        switch (st->read_state) {
623
8.84M
        case READ_STATE_HEADER:
624
            /*
625
             * Restore the state after an incomplete ACK before reading again:
626
             * the DTLS record layer uses it to handle application data.
627
             */
628
8.84M
            if (SSL_CONNECTION_IS_DTLS13(s)
629
306
                && (st->hand_state == TLS_ST_CR_ACK
630
306
                    || st->hand_state == TLS_ST_SR_ACK)
631
0
                && !transition(s, SSL3_MT_DUMMY))
632
0
                return SUB_STATE_ERROR;
633
634
            /* Get the state the peer wants to move to */
635
8.84M
            if (SSL_CONNECTION_IS_DTLS(s)) {
636
                /*
637
                 * In DTLS we get the whole message in one go - header and body
638
                 */
639
55.8k
                ret = dtls_get_message(s, &mt);
640
8.79M
            } else {
641
8.79M
                ret = tls_get_message_header(s, &mt);
642
8.79M
            }
643
644
8.84M
            if (ret == 0) {
645
                /* Re-ACK a retransmission without completing our own flight. */
646
8.69M
                if (st->ack_for_retransmit)
647
0
                    return SUB_STATE_FINISHED;
648
649
                /*
650
                 * If we're in DTLSv1.3 and in state TLS_ST_OK, then we must
651
                 * have received a post-handshake message. If we subsequently
652
                 * try to receive that message and get nothing back (and did not
653
                 * encounter a fatal error), then that message must have been
654
                 * dropped, so we need to end the handshake now, and return to
655
                 * reading app data.
656
                 */
657
8.69M
                if (SSL_CONNECTION_IS_DTLS13(s)
658
305
                    && st->hand_state == TLS_ST_OK
659
0
                    && s->statem.state != MSG_FLOW_ERROR) {
660
0
                    if (!ssl_free_wbio_buffer(s)) {
661
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
662
0
                        return SUB_STATE_ERROR;
663
0
                    }
664
0
                    ossl_statem_set_in_init(s, 0);
665
0
                    return SUB_STATE_END_HANDSHAKE;
666
0
                }
667
                /* Could be non-blocking IO */
668
8.69M
                return SUB_STATE_ERROR;
669
8.69M
            }
670
671
153k
            if (cb != NULL) {
672
                /* Notify callback of an impending state change */
673
0
                if (s->server)
674
0
                    cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
675
0
                else
676
0
                    cb(ssl, SSL_CB_CONNECT_LOOP, 1);
677
0
            }
678
            /*
679
             * Validate that we are allowed to move to the new state and move
680
             * to that state if so
681
             */
682
153k
            if (!transition(s, mt))
683
2.45k
                return SUB_STATE_ERROR;
684
685
150k
            if (s->s3.tmp.message_size > max_message_size(s)) {
686
280
                SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
687
280
                    SSL_R_EXCESSIVE_MESSAGE_SIZE);
688
280
                return SUB_STATE_ERROR;
689
280
            }
690
691
150k
            st->read_state = READ_STATE_BODY;
692
            /* Fall through */
693
694
7.74M
        case READ_STATE_BODY:
695
7.74M
            if (SSL_CONNECTION_IS_DTLS(s)) {
696
                /*
697
                 * Actually we already have the body, but we give DTLS the
698
                 * opportunity to do any further processing.
699
                 */
700
41.5k
                ret = dtls_get_message_body(s, &len);
701
7.70M
            } else {
702
7.70M
                ret = tls_get_message_body(s, &len);
703
7.70M
            }
704
7.74M
            if (ret == 0) {
705
                /* Could be non-blocking IO */
706
7.60M
                return SUB_STATE_ERROR;
707
7.60M
            }
708
709
147k
            s->first_packet = 0;
710
            /*
711
             * We initialise the buffer including the message header, and
712
             * then skip over header ready to process the message. This
713
             * ensures that calls to PACKET_msg_start() gives us the whole
714
             * message
715
             */
716
147k
            headerlen = (char *)s->init_msg - s->init_buf->data;
717
147k
            if (!PACKET_buf_init(&pkt, (unsigned char *)s->init_buf->data,
718
147k
                    len + headerlen)) {
719
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
720
0
                return SUB_STATE_ERROR;
721
0
            }
722
147k
            if (!PACKET_forward(&pkt, headerlen)) {
723
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
724
0
                return SUB_STATE_ERROR;
725
0
            }
726
727
147k
            ret = process_message(s, &pkt);
728
729
            /* Discard the packet data */
730
147k
            s->init_num = 0;
731
732
147k
            switch (ret) {
733
14.8k
            case MSG_PROCESS_ERROR:
734
14.8k
                check_fatal(s);
735
14.8k
                return SUB_STATE_ERROR;
736
737
50.9k
            case MSG_PROCESS_FINISHED_READING:
738
50.9k
                if (SSL_CONNECTION_IS_DTLS(s)) {
739
6.17k
                    dtls1_stop_timer(s);
740
6.17k
                }
741
50.9k
                return SUB_STATE_FINISHED;
742
743
33.2k
            case MSG_PROCESS_CONTINUE_PROCESSING:
744
33.2k
                st->read_state = READ_STATE_POST_PROCESS;
745
33.2k
                st->read_state_work = WORK_MORE_A;
746
33.2k
                break;
747
748
48.7k
            default:
749
48.7k
                st->read_state = READ_STATE_HEADER;
750
48.7k
                break;
751
147k
            }
752
81.9k
            break;
753
754
81.9k
        case READ_STATE_POST_PROCESS:
755
33.2k
            st->read_state_work = post_process_message(s, st->read_state_work);
756
33.2k
            switch (st->read_state_work) {
757
3.61k
            case WORK_ERROR:
758
3.61k
                check_fatal(s);
759
                /* Fall through */
760
3.61k
            case WORK_MORE_A:
761
3.61k
            case WORK_MORE_B:
762
3.61k
            case WORK_MORE_C:
763
3.61k
                return SUB_STATE_ERROR;
764
765
18.7k
            case WORK_FINISHED_CONTINUE:
766
18.7k
                st->read_state = READ_STATE_HEADER;
767
18.7k
                break;
768
769
0
            case WORK_FINISHED_SWAP:
770
10.8k
            case WORK_FINISHED_STOP:
771
10.8k
                if (SSL_CONNECTION_IS_DTLS(s)) {
772
5.52k
                    dtls1_stop_timer(s);
773
5.52k
                }
774
10.8k
                return SUB_STATE_FINISHED;
775
33.2k
            }
776
18.7k
            break;
777
778
18.7k
        default:
779
            /* Shouldn't happen */
780
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
781
0
            return SUB_STATE_ERROR;
782
16.4M
        }
783
16.4M
    }
784
16.3M
}
785
786
/*
787
 * Send a previously constructed message to the peer.
788
 */
789
static int statem_do_write(SSL_CONNECTION *s)
790
107k
{
791
107k
    int record_type;
792
107k
    OSSL_STATEM *st = &s->statem;
793
794
107k
    switch (st->hand_state) {
795
6.58k
    case TLS_ST_CW_CHANGE:
796
8.44k
    case TLS_ST_SW_CHANGE:
797
8.44k
        record_type = SSL3_RT_CHANGE_CIPHER_SPEC;
798
799
8.44k
        break;
800
0
    case TLS_ST_CW_ACK:
801
0
    case TLS_ST_SW_ACK:
802
0
        record_type = SSL3_RT_ACK;
803
804
0
        break;
805
99.4k
    default:
806
99.4k
        return ssl_do_write(s);
807
107k
    }
808
809
8.44k
    if (SSL_CONNECTION_IS_DTLS(s))
810
3.80k
        return dtls1_do_write(s, record_type);
811
4.63k
    else
812
4.63k
        return ssl3_do_write(s, record_type);
813
8.44k
}
814
815
/*
816
 * Initialise the MSG_FLOW_WRITING sub-state machine
817
 */
818
static void init_write_state_machine(SSL_CONNECTION *s)
819
397k
{
820
397k
    OSSL_STATEM *st = &s->statem;
821
822
397k
    st->write_state = WRITE_STATE_TRANSITION;
823
397k
}
824
825
/*
826
 * This function implements the sub-state machine when the message flow is in
827
 * MSG_FLOW_WRITING. The valid sub-states and transitions are:
828
 *
829
 * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
830
 * |             |
831
 * |             v
832
 * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
833
 * |             |
834
 * |             v
835
 * |       WRITE_STATE_SEND
836
 * |             |
837
 * |             v
838
 * |     WRITE_STATE_POST_WORK
839
 * |             |
840
 * +-------------+
841
 *
842
 * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
843
844
 * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
845
 * sending of the message. This could result in an NBIO event occurring in
846
 * which case control returns to the calling application. When this function
847
 * is recalled we will resume in the same state where we left off.
848
 *
849
 * WRITE_STATE_SEND sends the message and performs any work to be done after
850
 * sending.
851
 *
852
 * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
853
 * message has been completed. As for WRITE_STATE_PRE_WORK this could also
854
 * result in an NBIO event.
855
 */
856
static SUB_STATE_RETURN write_state_machine(SSL_CONNECTION *s)
857
347k
{
858
347k
    OSSL_STATEM *st = &s->statem;
859
347k
    int ret;
860
347k
    WRITE_TRAN (*transition)(SSL_CONNECTION *s);
861
347k
    WORK_STATE (*pre_work)(SSL_CONNECTION *s, WORK_STATE wst);
862
347k
    WORK_STATE (*post_work)(SSL_CONNECTION *s, WORK_STATE wst);
863
347k
    int (*get_construct_message_f)(SSL_CONNECTION *s,
864
347k
        CON_FUNC_RETURN (**confunc)(SSL_CONNECTION *s,
865
347k
            WPACKET *pkt),
866
347k
        int *mt);
867
347k
    int (*dtls_use_timer)(SSL_CONNECTION *s);
868
347k
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
869
347k
    CON_FUNC_RETURN (*confunc)(SSL_CONNECTION *s, WPACKET *pkt);
870
347k
    int mt;
871
347k
    WPACKET pkt;
872
347k
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
873
874
347k
    cb = get_callback(s);
875
876
347k
    if (s->server) {
877
210k
        transition = ossl_statem_server_write_transition;
878
210k
        pre_work = ossl_statem_server_pre_work;
879
210k
        post_work = ossl_statem_server_post_work;
880
210k
        get_construct_message_f = ossl_statem_server_construct_message;
881
210k
        dtls_use_timer = ossl_statem_dtls_server_use_timer;
882
210k
    } else {
883
137k
        transition = ossl_statem_client_write_transition;
884
137k
        pre_work = ossl_statem_client_pre_work;
885
137k
        post_work = ossl_statem_client_post_work;
886
137k
        get_construct_message_f = ossl_statem_client_construct_message;
887
137k
        dtls_use_timer = ossl_statem_dtls_client_use_timer;
888
137k
    }
889
890
925k
    while (1) {
891
925k
        switch (st->write_state) {
892
591k
        case WRITE_STATE_TRANSITION:
893
591k
            if (cb != NULL) {
894
                /* Notify callback of an impending state change */
895
0
                if (s->server)
896
0
                    cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
897
0
                else
898
0
                    cb(ssl, SSL_CB_CONNECT_LOOP, 1);
899
0
            }
900
591k
            switch (transition(s)) {
901
331k
            case WRITE_TRAN_CONTINUE:
902
331k
                st->write_state = WRITE_STATE_PRE_WORK;
903
331k
                st->write_state_work = WORK_MORE_A;
904
331k
                break;
905
906
260k
            case WRITE_TRAN_FINISHED:
907
260k
                return SUB_STATE_FINISHED;
908
909
0
            case WRITE_TRAN_ERROR:
910
0
                check_fatal(s);
911
0
                return SUB_STATE_ERROR;
912
591k
            }
913
331k
            break;
914
915
331k
        case WRITE_STATE_PRE_WORK:
916
331k
            switch (st->write_state_work = pre_work(s, st->write_state_work)) {
917
0
            case WORK_ERROR:
918
0
                check_fatal(s);
919
                /* Fall through */
920
0
            case WORK_MORE_A:
921
0
            case WORK_MORE_B:
922
0
            case WORK_MORE_C:
923
0
                return SUB_STATE_ERROR;
924
925
245k
            case WORK_FINISHED_CONTINUE:
926
245k
                st->write_state = WRITE_STATE_SEND;
927
245k
                break;
928
929
0
            case WORK_FINISHED_SWAP:
930
0
                return SUB_STATE_FINISHED;
931
932
86.5k
            case WORK_FINISHED_STOP:
933
86.5k
                return SUB_STATE_END_HANDSHAKE;
934
331k
            }
935
245k
            if (!get_construct_message_f(s, &confunc, &mt)) {
936
                /* SSLfatal() already called */
937
0
                return SUB_STATE_ERROR;
938
0
            }
939
245k
            if (mt == SSL3_MT_DUMMY) {
940
                /* Skip construction and sending. This isn't a "real" state */
941
1.79k
                st->write_state = WRITE_STATE_POST_WORK;
942
1.79k
                st->write_state_work = WORK_MORE_A;
943
1.79k
                break;
944
1.79k
            }
945
243k
            if (!WPACKET_init(&pkt, s->init_buf)
946
243k
                || !ssl_set_handshake_header(s, &pkt, mt)) {
947
0
                WPACKET_cleanup(&pkt);
948
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
949
0
                return SUB_STATE_ERROR;
950
0
            }
951
243k
            if (confunc != NULL) {
952
243k
                CON_FUNC_RETURN tmpret;
953
954
243k
                tmpret = confunc(s, &pkt);
955
243k
                if (tmpret == CON_FUNC_ERROR) {
956
979
                    WPACKET_cleanup(&pkt);
957
979
                    check_fatal(s);
958
979
                    return SUB_STATE_ERROR;
959
242k
                } else if (tmpret == CON_FUNC_DONT_SEND) {
960
                    /*
961
                     * The construction function decided not to construct the
962
                     * message after all and continue. Skip sending.
963
                     */
964
0
                    WPACKET_cleanup(&pkt);
965
0
                    st->write_state = WRITE_STATE_POST_WORK;
966
0
                    st->write_state_work = WORK_MORE_A;
967
0
                    break;
968
0
                } /* else success */
969
243k
            }
970
242k
            if (!ssl_close_construct_packet(s, &pkt, mt)
971
242k
                || !WPACKET_finish(&pkt)) {
972
0
                WPACKET_cleanup(&pkt);
973
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
974
0
                return SUB_STATE_ERROR;
975
0
            }
976
977
            /* Fall through */
978
979
242k
        case WRITE_STATE_SEND:
980
242k
            if (SSL_CONNECTION_IS_DTLS(s) && dtls_use_timer(s))
981
81.4k
                dtls1_start_timer(s);
982
983
242k
            ret = statem_do_write(s);
984
242k
            if (ret <= 0) {
985
0
                return SUB_STATE_ERROR;
986
0
            }
987
242k
            st->write_state = WRITE_STATE_POST_WORK;
988
242k
            st->write_state_work = WORK_MORE_A;
989
            /* Fall through */
990
991
244k
        case WRITE_STATE_POST_WORK:
992
244k
            switch (st->write_state_work = post_work(s, st->write_state_work)) {
993
2
            case WORK_ERROR:
994
2
                check_fatal(s);
995
                /* Fall through */
996
2
            case WORK_MORE_A:
997
2
            case WORK_MORE_B:
998
2
            case WORK_MORE_C:
999
2
                return SUB_STATE_ERROR;
1000
1001
244k
            case WORK_FINISHED_CONTINUE:
1002
244k
                st->write_state = WRITE_STATE_TRANSITION;
1003
244k
                break;
1004
1005
0
            case WORK_FINISHED_SWAP:
1006
0
                return SUB_STATE_FINISHED;
1007
1008
0
            case WORK_FINISHED_STOP:
1009
0
                return SUB_STATE_END_HANDSHAKE;
1010
244k
            }
1011
244k
            break;
1012
1013
244k
        default:
1014
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1015
0
            return SUB_STATE_ERROR;
1016
925k
        }
1017
925k
    }
1018
347k
}
1019
1020
/*
1021
 * Flush the write BIO
1022
 */
1023
int statem_flush(SSL_CONNECTION *s)
1024
187k
{
1025
187k
    s->rwstate = SSL_WRITING;
1026
187k
    if (BIO_flush(s->wbio) <= 0) {
1027
0
        return 0;
1028
0
    }
1029
187k
    s->rwstate = SSL_NOTHING;
1030
1031
187k
    return 1;
1032
187k
}
1033
1034
/*
1035
 * Called by the record layer to determine whether application data is
1036
 * allowed to be received in the current handshake state or not.
1037
 *
1038
 * Return values are:
1039
 *   1: Yes (application data allowed)
1040
 *   0: No (application data not allowed)
1041
 */
1042
int ossl_statem_app_data_allowed(SSL_CONNECTION *s)
1043
7.72k
{
1044
7.72k
    OSSL_STATEM *st = &s->statem;
1045
1046
7.72k
    if (st->state == MSG_FLOW_UNINITED)
1047
0
        return 0;
1048
1049
7.72k
    if (!s->s3.in_read_app_data || (s->s3.total_renegotiations == 0))
1050
3.43k
        return 0;
1051
1052
4.29k
    if (s->server) {
1053
        /*
1054
         * If we're a server and we haven't got as far as writing our
1055
         * ServerHello yet then we allow app data
1056
         */
1057
0
        if (st->hand_state == TLS_ST_BEFORE
1058
0
            || st->hand_state == TLS_ST_SR_CLNT_HELLO)
1059
0
            return 1;
1060
4.29k
    } else {
1061
        /*
1062
         * If we're a client and we haven't read the ServerHello yet then we
1063
         * allow app data
1064
         */
1065
4.29k
        if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
1066
4.25k
            return 1;
1067
4.29k
    }
1068
1069
38
    return 0;
1070
4.29k
}
1071
1072
/*
1073
 * This function returns 1 if TLS exporter is ready to export keying
1074
 * material, or 0 if otherwise.
1075
 */
1076
int ossl_statem_export_allowed(SSL_CONNECTION *s)
1077
0
{
1078
0
    return s->s3.previous_server_finished_len != 0
1079
0
        && s->statem.hand_state != TLS_ST_SW_FINISHED;
1080
0
}
1081
1082
/*
1083
 * Return 1 if early TLS exporter is ready to export keying material,
1084
 * or 0 if otherwise.
1085
 */
1086
int ossl_statem_export_early_allowed(SSL_CONNECTION *s)
1087
0
{
1088
    /*
1089
     * The early exporter secret is only present on the server if we
1090
     * have accepted early_data. It is present on the client as long
1091
     * as we have sent early_data.
1092
     */
1093
0
    return s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
1094
0
        || (!s->server && s->ext.early_data != SSL_EARLY_DATA_NOT_SENT);
1095
0
}