Coverage Report

Created: 2026-11-16 07:12

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