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