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