Coverage Report

Created: 2026-08-31 06:56

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