Coverage Report

Created: 2026-03-09 06:55

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-2025 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)
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
0
    if (sending == -1) {
249
0
        if (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
250
0
            || s->statem.hand_state == TLS_ST_EARLY_DATA) {
251
0
            ossl_statem_set_in_init(s, 1);
252
0
            if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY) {
253
                /*
254
                 * SSL_connect() or SSL_do_handshake() has been called directly.
255
                 * We don't allow any more writing of early data.
256
                 */
257
0
                s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
258
0
            }
259
0
        }
260
0
    } else if (!s->server) {
261
0
        if ((sending && (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END || s->statem.hand_state == TLS_ST_EARLY_DATA)
262
0
                && s->early_data_state != SSL_EARLY_DATA_WRITING)
263
0
            || (!sending && s->statem.hand_state == TLS_ST_EARLY_DATA)) {
264
0
            ossl_statem_set_in_init(s, 1);
265
            /*
266
             * SSL_write() has been called directly. We don't allow any more
267
             * writing of early data.
268
             */
269
0
            if (sending && s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY)
270
0
                s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
271
0
        }
272
0
    } else {
273
0
        if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING
274
0
            && s->statem.hand_state == TLS_ST_EARLY_DATA)
275
0
            ossl_statem_set_in_init(s, 1);
276
0
    }
277
0
    return 1;
278
0
}
279
280
void ossl_statem_set_hello_verify_done(SSL_CONNECTION *s)
281
0
{
282
0
    s->statem.state = MSG_FLOW_UNINITED;
283
0
    ossl_statem_set_in_init(s, 1);
284
    /*
285
     * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
286
     * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
287
     * calls to SSL_in_before() will return false. Also calls to
288
     * SSL_state_string() and SSL_state_string_long() will return something
289
     * sensible.
290
     */
291
0
    s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
292
0
    s->statem.error_state = ERROR_STATE_NOERROR;
293
0
}
294
295
int ossl_statem_connect(SSL *s)
296
0
{
297
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
298
299
0
    if (sc == NULL)
300
0
        return -1;
301
302
0
    return state_machine(sc, 0);
303
0
}
304
305
int ossl_statem_accept(SSL *s)
306
0
{
307
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
308
309
0
    if (sc == NULL)
310
0
        return -1;
311
312
0
    return state_machine(sc, 1);
313
0
}
314
315
typedef void (*info_cb)(const SSL *, int, int);
316
317
static info_cb get_callback(SSL_CONNECTION *s)
318
0
{
319
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
320
321
0
    if (s->info_callback != NULL)
322
0
        return s->info_callback;
323
0
    else if (sctx->info_callback != NULL)
324
0
        return sctx->info_callback;
325
326
0
    return NULL;
327
0
}
328
329
/*
330
 * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
331
 * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
332
 * transitions are as follows:
333
 *
334
 * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
335
 *        |                       |
336
 *        +-----------------------+
337
 *        v
338
 * MSG_FLOW_WRITING <---> MSG_FLOW_READING
339
 *        |
340
 *        V
341
 * MSG_FLOW_FINISHED
342
 *        |
343
 *        V
344
 *    [SUCCESS]
345
 *
346
 * We may exit at any point due to an error or NBIO event. If an NBIO event
347
 * occurs then we restart at the point we left off when we are recalled.
348
 * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
349
 *
350
 * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
351
 * into that state at any point in the event that an irrecoverable error occurs.
352
 *
353
 * Valid return values are:
354
 *   1: Success
355
 * <=0: NBIO or error
356
 */
357
static int state_machine(SSL_CONNECTION *s, int server)
358
0
{
359
0
    BUF_MEM *buf = NULL;
360
0
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
361
0
    OSSL_STATEM *st = &s->statem;
362
0
    int ret = -1;
363
0
    int ssret;
364
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
365
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
366
367
0
    if (st->state == MSG_FLOW_ERROR) {
368
        /* Shouldn't have been called if we're already in the error state */
369
0
        return -1;
370
0
    }
371
372
0
    ERR_clear_error();
373
0
    clear_sys_error();
374
375
0
    cb = get_callback(s);
376
377
0
    st->in_handshake++;
378
0
    if (!SSL_in_init(ssl) || SSL_in_before(ssl)) {
379
        /*
380
         * If we are stateless then we already called SSL_clear() - don't do
381
         * it again and clear the STATELESS flag itself.
382
         */
383
0
        if ((s->s3.flags & TLS1_FLAGS_STATELESS) == 0 && !SSL_clear(ssl))
384
0
            return -1;
385
0
    }
386
#ifndef OPENSSL_NO_SCTP
387
    if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
388
        /*
389
         * Notify SCTP BIO socket to enter handshake mode and prevent stream
390
         * identifier other than 0.
391
         */
392
        BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
393
            st->in_handshake, NULL);
394
    }
395
#endif
396
397
    /* Initialise state machine */
398
0
    if (st->state == MSG_FLOW_UNINITED
399
0
        || st->state == MSG_FLOW_FINISHED) {
400
0
        if (st->state == MSG_FLOW_UNINITED) {
401
0
            st->hand_state = TLS_ST_BEFORE;
402
0
            st->request_state = TLS_ST_BEFORE;
403
0
        }
404
405
0
        s->server = server;
406
0
        if (cb != NULL) {
407
0
            if (SSL_IS_FIRST_HANDSHAKE(s) || !SSL_CONNECTION_IS_TLS13(s))
408
0
                cb(ussl, SSL_CB_HANDSHAKE_START, 1);
409
0
        }
410
411
        /*
412
         * Fatal errors in this block don't send an alert because we have
413
         * failed to even initialise properly. Sending an alert is probably
414
         * doomed to failure.
415
         */
416
417
0
        if (SSL_CONNECTION_IS_DTLS(s)) {
418
0
            if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) && (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
419
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
420
0
                goto end;
421
0
            }
422
0
        } else {
423
0
            if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
424
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
425
0
                goto end;
426
0
            }
427
0
        }
428
429
0
        if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
430
0
            SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
431
0
            goto end;
432
0
        }
433
434
0
        if (s->init_buf == NULL) {
435
0
            if ((buf = BUF_MEM_new()) == NULL) {
436
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
437
0
                goto end;
438
0
            }
439
0
            if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
440
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
441
0
                goto end;
442
0
            }
443
0
            s->init_buf = buf;
444
0
            buf = NULL;
445
0
        }
446
447
0
        s->init_num = 0;
448
449
        /*
450
         * Should have been reset by tls_process_finished, too.
451
         */
452
0
        s->s3.change_cipher_spec = 0;
453
454
        /*
455
         * Ok, we now need to push on a buffering BIO ...but not with
456
         * SCTP
457
         */
458
#ifndef OPENSSL_NO_SCTP
459
        if (!SSL_CONNECTION_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(ssl)))
460
#endif
461
0
            if (!ssl_init_wbio_buffer(s)) {
462
0
                SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
463
0
                goto end;
464
0
            }
465
466
0
        if ((SSL_in_before(ssl))
467
0
            || s->renegotiate) {
468
0
            if (!tls_setup_handshake(s)) {
469
                /* SSLfatal() already called */
470
0
                goto end;
471
0
            }
472
473
0
            if (SSL_IS_FIRST_HANDSHAKE(s))
474
0
                st->read_state_first_init = 1;
475
0
        }
476
477
0
        st->state = MSG_FLOW_WRITING;
478
0
        init_write_state_machine(s);
479
0
    }
480
481
0
    while (st->state != MSG_FLOW_FINISHED) {
482
0
        if (st->state == MSG_FLOW_READING) {
483
0
            ssret = read_state_machine(s);
484
0
            if (ssret == SUB_STATE_FINISHED) {
485
0
                st->state = MSG_FLOW_WRITING;
486
0
                init_write_state_machine(s);
487
0
            } else {
488
                /* NBIO or error */
489
0
                goto end;
490
0
            }
491
0
        } else if (st->state == MSG_FLOW_WRITING) {
492
0
            ssret = write_state_machine(s);
493
0
            if (ssret == SUB_STATE_FINISHED) {
494
0
                st->state = MSG_FLOW_READING;
495
0
                init_read_state_machine(s);
496
0
            } else if (ssret == SUB_STATE_END_HANDSHAKE) {
497
0
                st->state = MSG_FLOW_FINISHED;
498
0
            } else {
499
                /* NBIO or error */
500
0
                goto end;
501
0
            }
502
0
        } else {
503
            /* Error */
504
0
            check_fatal(s);
505
0
            ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
506
0
            goto end;
507
0
        }
508
0
    }
509
510
0
    ret = 1;
511
512
0
end:
513
0
    st->in_handshake--;
514
515
#ifndef OPENSSL_NO_SCTP
516
    if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
517
        /*
518
         * Notify SCTP BIO socket to leave handshake mode and allow stream
519
         * identifier other than 0.
520
         */
521
        BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
522
            st->in_handshake, NULL);
523
    }
524
#endif
525
526
0
    BUF_MEM_free(buf);
527
0
    if (cb != NULL) {
528
0
        if (server)
529
0
            cb(ussl, SSL_CB_ACCEPT_EXIT, ret);
530
0
        else
531
0
            cb(ussl, SSL_CB_CONNECT_EXIT, ret);
532
0
    }
533
0
    return ret;
534
0
}
535
536
/*
537
 * Initialise the MSG_FLOW_READING sub-state machine
538
 */
539
static void init_read_state_machine(SSL_CONNECTION *s)
540
0
{
541
0
    OSSL_STATEM *st = &s->statem;
542
543
0
    st->read_state = READ_STATE_HEADER;
544
0
}
545
546
static int grow_init_buf(SSL_CONNECTION *s, size_t size)
547
0
{
548
549
0
    size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
550
551
0
    if (!BUF_MEM_grow_clean(s->init_buf, size))
552
0
        return 0;
553
554
0
    if (size < msg_offset)
555
0
        return 0;
556
557
0
    s->init_msg = s->init_buf->data + msg_offset;
558
559
0
    return 1;
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
                /* Could be non-blocking IO */
635
0
                return SUB_STATE_ERROR;
636
0
            }
637
638
0
            if (cb != NULL) {
639
                /* Notify callback of an impending state change */
640
0
                if (s->server)
641
0
                    cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
642
0
                else
643
0
                    cb(ssl, SSL_CB_CONNECT_LOOP, 1);
644
0
            }
645
            /*
646
             * Validate that we are allowed to move to the new state and move
647
             * to that state if so
648
             */
649
0
            if (!transition(s, mt))
650
0
                return SUB_STATE_ERROR;
651
652
0
            if (s->s3.tmp.message_size > max_message_size(s)) {
653
0
                SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
654
0
                    SSL_R_EXCESSIVE_MESSAGE_SIZE);
655
0
                return SUB_STATE_ERROR;
656
0
            }
657
658
            /* dtls_get_message already did this */
659
0
            if (!SSL_CONNECTION_IS_DTLS(s)
660
0
                && s->s3.tmp.message_size > 0
661
0
                && !grow_init_buf(s, s->s3.tmp.message_size + SSL3_HM_HEADER_LENGTH)) {
662
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
663
0
                return SUB_STATE_ERROR;
664
0
            }
665
666
0
            st->read_state = READ_STATE_BODY;
667
            /* Fall through */
668
669
0
        case READ_STATE_BODY:
670
0
            if (SSL_CONNECTION_IS_DTLS(s)) {
671
                /*
672
                 * Actually we already have the body, but we give DTLS the
673
                 * opportunity to do any further processing.
674
                 */
675
0
                ret = dtls_get_message_body(s, &len);
676
0
            } else {
677
0
                ret = tls_get_message_body(s, &len);
678
0
            }
679
0
            if (ret == 0) {
680
                /* Could be non-blocking IO */
681
0
                return SUB_STATE_ERROR;
682
0
            }
683
684
0
            s->first_packet = 0;
685
            /*
686
             * We initialise the buffer including the message header, and
687
             * then skip over header ready to process the message. This
688
             * ensures that calls to PACKET_msg_start() gives us the whole
689
             * message
690
             */
691
0
            headerlen = (char *)s->init_msg - s->init_buf->data;
692
0
            if (!PACKET_buf_init(&pkt, (unsigned char *)s->init_buf->data,
693
0
                    len + headerlen)) {
694
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
695
0
                return SUB_STATE_ERROR;
696
0
            }
697
0
            if (!PACKET_forward(&pkt, headerlen)) {
698
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
699
0
                return SUB_STATE_ERROR;
700
0
            }
701
702
0
            ret = process_message(s, &pkt);
703
704
            /* Discard the packet data */
705
0
            s->init_num = 0;
706
707
0
            switch (ret) {
708
0
            case MSG_PROCESS_ERROR:
709
0
                check_fatal(s);
710
0
                return SUB_STATE_ERROR;
711
712
0
            case MSG_PROCESS_FINISHED_READING:
713
0
                if (SSL_CONNECTION_IS_DTLS(s)) {
714
0
                    dtls1_stop_timer(s);
715
0
                }
716
0
                return SUB_STATE_FINISHED;
717
718
0
            case MSG_PROCESS_CONTINUE_PROCESSING:
719
0
                st->read_state = READ_STATE_POST_PROCESS;
720
0
                st->read_state_work = WORK_MORE_A;
721
0
                break;
722
723
0
            default:
724
0
                st->read_state = READ_STATE_HEADER;
725
0
                break;
726
0
            }
727
0
            break;
728
729
0
        case READ_STATE_POST_PROCESS:
730
0
            st->read_state_work = post_process_message(s, st->read_state_work);
731
0
            switch (st->read_state_work) {
732
0
            case WORK_ERROR:
733
0
                check_fatal(s);
734
                /* Fall through */
735
0
            case WORK_MORE_A:
736
0
            case WORK_MORE_B:
737
0
            case WORK_MORE_C:
738
0
                return SUB_STATE_ERROR;
739
740
0
            case WORK_FINISHED_CONTINUE:
741
0
                st->read_state = READ_STATE_HEADER;
742
0
                break;
743
744
0
            case WORK_FINISHED_SWAP:
745
0
            case WORK_FINISHED_STOP:
746
0
                if (SSL_CONNECTION_IS_DTLS(s)) {
747
0
                    dtls1_stop_timer(s);
748
0
                }
749
0
                return SUB_STATE_FINISHED;
750
0
            }
751
0
            break;
752
753
0
        default:
754
            /* Shouldn't happen */
755
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
756
0
            return SUB_STATE_ERROR;
757
0
        }
758
0
    }
759
0
}
760
761
/*
762
 * Send a previously constructed message to the peer.
763
 */
764
static int statem_do_write(SSL_CONNECTION *s)
765
0
{
766
0
    OSSL_STATEM *st = &s->statem;
767
768
0
    if (st->hand_state == TLS_ST_CW_CHANGE
769
0
        || st->hand_state == TLS_ST_SW_CHANGE) {
770
0
        if (SSL_CONNECTION_IS_DTLS(s))
771
0
            return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
772
0
        else
773
0
            return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
774
0
    } else {
775
0
        return ssl_do_write(s);
776
0
    }
777
0
}
778
779
/*
780
 * Initialise the MSG_FLOW_WRITING sub-state machine
781
 */
782
static void init_write_state_machine(SSL_CONNECTION *s)
783
0
{
784
0
    OSSL_STATEM *st = &s->statem;
785
786
0
    st->write_state = WRITE_STATE_TRANSITION;
787
0
}
788
789
/*
790
 * This function implements the sub-state machine when the message flow is in
791
 * MSG_FLOW_WRITING. The valid sub-states and transitions are:
792
 *
793
 * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
794
 * |             |
795
 * |             v
796
 * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
797
 * |             |
798
 * |             v
799
 * |       WRITE_STATE_SEND
800
 * |             |
801
 * |             v
802
 * |     WRITE_STATE_POST_WORK
803
 * |             |
804
 * +-------------+
805
 *
806
 * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
807
808
 * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
809
 * sending of the message. This could result in an NBIO event occurring in
810
 * which case control returns to the calling application. When this function
811
 * is recalled we will resume in the same state where we left off.
812
 *
813
 * WRITE_STATE_SEND sends the message and performs any work to be done after
814
 * sending.
815
 *
816
 * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
817
 * message has been completed. As for WRITE_STATE_PRE_WORK this could also
818
 * result in an NBIO event.
819
 */
820
static SUB_STATE_RETURN write_state_machine(SSL_CONNECTION *s)
821
0
{
822
0
    OSSL_STATEM *st = &s->statem;
823
0
    int ret;
824
0
    WRITE_TRAN (*transition)(SSL_CONNECTION *s);
825
0
    WORK_STATE (*pre_work)(SSL_CONNECTION *s, WORK_STATE wst);
826
0
    WORK_STATE (*post_work)(SSL_CONNECTION *s, WORK_STATE wst);
827
0
    int (*get_construct_message_f)(SSL_CONNECTION *s,
828
0
        CON_FUNC_RETURN (**confunc)(SSL_CONNECTION *s,
829
0
            WPACKET *pkt),
830
0
        int *mt);
831
0
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
832
0
    CON_FUNC_RETURN (*confunc)(SSL_CONNECTION *s, WPACKET *pkt);
833
0
    int mt;
834
0
    WPACKET pkt;
835
0
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
836
837
0
    cb = get_callback(s);
838
839
0
    if (s->server) {
840
0
        transition = ossl_statem_server_write_transition;
841
0
        pre_work = ossl_statem_server_pre_work;
842
0
        post_work = ossl_statem_server_post_work;
843
0
        get_construct_message_f = ossl_statem_server_construct_message;
844
0
    } else {
845
0
        transition = ossl_statem_client_write_transition;
846
0
        pre_work = ossl_statem_client_pre_work;
847
0
        post_work = ossl_statem_client_post_work;
848
0
        get_construct_message_f = ossl_statem_client_construct_message;
849
0
    }
850
851
0
    while (1) {
852
0
        switch (st->write_state) {
853
0
        case WRITE_STATE_TRANSITION:
854
0
            if (cb != NULL) {
855
                /* Notify callback of an impending state change */
856
0
                if (s->server)
857
0
                    cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
858
0
                else
859
0
                    cb(ssl, SSL_CB_CONNECT_LOOP, 1);
860
0
            }
861
0
            switch (transition(s)) {
862
0
            case WRITE_TRAN_CONTINUE:
863
0
                st->write_state = WRITE_STATE_PRE_WORK;
864
0
                st->write_state_work = WORK_MORE_A;
865
0
                break;
866
867
0
            case WRITE_TRAN_FINISHED:
868
0
                return SUB_STATE_FINISHED;
869
870
0
            case WRITE_TRAN_ERROR:
871
0
                check_fatal(s);
872
0
                return SUB_STATE_ERROR;
873
0
            }
874
0
            break;
875
876
0
        case WRITE_STATE_PRE_WORK:
877
0
            switch (st->write_state_work = pre_work(s, st->write_state_work)) {
878
0
            case WORK_ERROR:
879
0
                check_fatal(s);
880
                /* Fall through */
881
0
            case WORK_MORE_A:
882
0
            case WORK_MORE_B:
883
0
            case WORK_MORE_C:
884
0
                return SUB_STATE_ERROR;
885
886
0
            case WORK_FINISHED_CONTINUE:
887
0
                st->write_state = WRITE_STATE_SEND;
888
0
                break;
889
890
0
            case WORK_FINISHED_SWAP:
891
0
                return SUB_STATE_FINISHED;
892
893
0
            case WORK_FINISHED_STOP:
894
0
                return SUB_STATE_END_HANDSHAKE;
895
0
            }
896
0
            if (!get_construct_message_f(s, &confunc, &mt)) {
897
                /* SSLfatal() already called */
898
0
                return SUB_STATE_ERROR;
899
0
            }
900
0
            if (mt == SSL3_MT_DUMMY) {
901
                /* Skip construction and sending. This isn't a "real" state */
902
0
                st->write_state = WRITE_STATE_POST_WORK;
903
0
                st->write_state_work = WORK_MORE_A;
904
0
                break;
905
0
            }
906
0
            if (!WPACKET_init(&pkt, s->init_buf)
907
0
                || !ssl_set_handshake_header(s, &pkt, mt)) {
908
0
                WPACKET_cleanup(&pkt);
909
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
910
0
                return SUB_STATE_ERROR;
911
0
            }
912
0
            if (confunc != NULL) {
913
0
                CON_FUNC_RETURN tmpret;
914
915
0
                tmpret = confunc(s, &pkt);
916
0
                if (tmpret == CON_FUNC_ERROR) {
917
0
                    WPACKET_cleanup(&pkt);
918
0
                    check_fatal(s);
919
0
                    return SUB_STATE_ERROR;
920
0
                } else if (tmpret == CON_FUNC_DONT_SEND) {
921
                    /*
922
                     * The construction function decided not to construct the
923
                     * message after all and continue. Skip sending.
924
                     */
925
0
                    WPACKET_cleanup(&pkt);
926
0
                    st->write_state = WRITE_STATE_POST_WORK;
927
0
                    st->write_state_work = WORK_MORE_A;
928
0
                    break;
929
0
                } /* else success */
930
0
            }
931
0
            if (!ssl_close_construct_packet(s, &pkt, mt)
932
0
                || !WPACKET_finish(&pkt)) {
933
0
                WPACKET_cleanup(&pkt);
934
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
935
0
                return SUB_STATE_ERROR;
936
0
            }
937
938
            /* Fall through */
939
940
0
        case WRITE_STATE_SEND:
941
0
            if (SSL_CONNECTION_IS_DTLS(s) && st->use_timer) {
942
0
                dtls1_start_timer(s);
943
0
            }
944
0
            ret = statem_do_write(s);
945
0
            if (ret <= 0) {
946
0
                return SUB_STATE_ERROR;
947
0
            }
948
0
            st->write_state = WRITE_STATE_POST_WORK;
949
0
            st->write_state_work = WORK_MORE_A;
950
            /* Fall through */
951
952
0
        case WRITE_STATE_POST_WORK:
953
0
            switch (st->write_state_work = post_work(s, st->write_state_work)) {
954
0
            case WORK_ERROR:
955
0
                check_fatal(s);
956
                /* Fall through */
957
0
            case WORK_MORE_A:
958
0
            case WORK_MORE_B:
959
0
            case WORK_MORE_C:
960
0
                return SUB_STATE_ERROR;
961
962
0
            case WORK_FINISHED_CONTINUE:
963
0
                st->write_state = WRITE_STATE_TRANSITION;
964
0
                break;
965
966
0
            case WORK_FINISHED_SWAP:
967
0
                return SUB_STATE_FINISHED;
968
969
0
            case WORK_FINISHED_STOP:
970
0
                return SUB_STATE_END_HANDSHAKE;
971
0
            }
972
0
            break;
973
974
0
        default:
975
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
976
0
            return SUB_STATE_ERROR;
977
0
        }
978
0
    }
979
0
}
980
981
/*
982
 * Flush the write BIO
983
 */
984
int statem_flush(SSL_CONNECTION *s)
985
0
{
986
0
    s->rwstate = SSL_WRITING;
987
0
    if (BIO_flush(s->wbio) <= 0) {
988
0
        return 0;
989
0
    }
990
0
    s->rwstate = SSL_NOTHING;
991
992
0
    return 1;
993
0
}
994
995
/*
996
 * Called by the record layer to determine whether application data is
997
 * allowed to be received in the current handshake state or not.
998
 *
999
 * Return values are:
1000
 *   1: Yes (application data allowed)
1001
 *   0: No (application data not allowed)
1002
 */
1003
int ossl_statem_app_data_allowed(SSL_CONNECTION *s)
1004
0
{
1005
0
    OSSL_STATEM *st = &s->statem;
1006
1007
0
    if (st->state == MSG_FLOW_UNINITED)
1008
0
        return 0;
1009
1010
0
    if (!s->s3.in_read_app_data || (s->s3.total_renegotiations == 0))
1011
0
        return 0;
1012
1013
0
    if (s->server) {
1014
        /*
1015
         * If we're a server and we haven't got as far as writing our
1016
         * ServerHello yet then we allow app data
1017
         */
1018
0
        if (st->hand_state == TLS_ST_BEFORE
1019
0
            || st->hand_state == TLS_ST_SR_CLNT_HELLO)
1020
0
            return 1;
1021
0
    } else {
1022
        /*
1023
         * If we're a client and we haven't read the ServerHello yet then we
1024
         * allow app data
1025
         */
1026
0
        if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
1027
0
            return 1;
1028
0
    }
1029
1030
0
    return 0;
1031
0
}
1032
1033
/*
1034
 * This function returns 1 if TLS exporter is ready to export keying
1035
 * material, or 0 if otherwise.
1036
 */
1037
int ossl_statem_export_allowed(SSL_CONNECTION *s)
1038
0
{
1039
0
    return s->s3.previous_server_finished_len != 0
1040
0
        && s->statem.hand_state != TLS_ST_SW_FINISHED;
1041
0
}
1042
1043
/*
1044
 * Return 1 if early TLS exporter is ready to export keying material,
1045
 * or 0 if otherwise.
1046
 */
1047
int ossl_statem_export_early_allowed(SSL_CONNECTION *s)
1048
0
{
1049
    /*
1050
     * The early exporter secret is only present on the server if we
1051
     * have accepted early_data. It is present on the client as long
1052
     * as we have sent early_data.
1053
     */
1054
0
    return s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
1055
0
        || (!s->server && s->ext.early_data != SSL_EARLY_DATA_NOT_SENT);
1056
0
}