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