Stop server from expecting Certificate message when not requested
[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.state = MSG_FLOW_RENEGOTIATE;
109     s->statem.in_init = 1;
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 void ossl_statem_set_hello_verify_done(SSL *s)
155 {
156     s->statem.state = MSG_FLOW_UNINITED;
157     s->statem.in_init = 1;
158     /*
159      * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
160      * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
161      * calls to SSL_in_before() will return false. Also calls to
162      * SSL_state_string() and SSL_state_string_long() will return something
163      * sensible.
164      */
165     s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
166 }
167
168 int ossl_statem_connect(SSL *s)
169 {
170     return state_machine(s, 0);
171 }
172
173 int ossl_statem_accept(SSL *s)
174 {
175     return state_machine(s, 1);
176 }
177
178 typedef void (*info_cb) (const SSL *, int, int);
179
180 static info_cb get_callback(SSL *s)
181 {
182     if (s->info_callback != NULL)
183         return s->info_callback;
184     else if (s->ctx->info_callback != NULL)
185         return s->ctx->info_callback;
186
187     return NULL;
188 }
189
190 /*
191  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
192  * MSG_FLOW_RENEGOTIATE state and finish in MSG_FLOW_FINISHED. Valid states and
193  * transitions are as follows:
194  *
195  * MSG_FLOW_UNINITED     MSG_FLOW_RENEGOTIATE
196  *        |                       |
197  *        +-----------------------+
198  *        v
199  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
200  *        |
201  *        V
202  * MSG_FLOW_FINISHED
203  *        |
204  *        V
205  *    [SUCCESS]
206  *
207  * We may exit at any point due to an error or NBIO event. If an NBIO event
208  * occurs then we restart at the point we left off when we are recalled.
209  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
210  *
211  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
212  * into that state at any point in the event that an irrecoverable error occurs.
213  *
214  * Valid return values are:
215  *   1: Success
216  * <=0: NBIO or error
217  */
218 static int state_machine(SSL *s, int server)
219 {
220     BUF_MEM *buf = NULL;
221     unsigned long Time = (unsigned long)time(NULL);
222     void (*cb) (const SSL *ssl, int type, int val) = NULL;
223     OSSL_STATEM *st = &s->statem;
224     int ret = -1;
225     int ssret;
226
227     if (st->state == MSG_FLOW_ERROR) {
228         /* Shouldn't have been called if we're already in the error state */
229         return -1;
230     }
231
232     RAND_add(&Time, sizeof(Time), 0);
233     ERR_clear_error();
234     clear_sys_error();
235
236     cb = get_callback(s);
237
238     st->in_handshake++;
239     if (!SSL_in_init(s) || SSL_in_before(s)) {
240         if (!SSL_clear(s))
241             return -1;
242     }
243 #ifndef OPENSSL_NO_SCTP
244     if (SSL_IS_DTLS(s)) {
245         /*
246          * Notify SCTP BIO socket to enter handshake mode and prevent stream
247          * identifier other than 0. Will be ignored if no SCTP is used.
248          */
249         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
250                  st->in_handshake, NULL);
251     }
252 #endif
253
254     /* Initialise state machine */
255
256     if (st->state == MSG_FLOW_RENEGOTIATE) {
257         s->renegotiate = 1;
258         if (!server)
259             s->ctx->stats.sess_connect_renegotiate++;
260     }
261
262     if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE) {
263         if (st->state == MSG_FLOW_UNINITED) {
264             st->hand_state = TLS_ST_BEFORE;
265         }
266
267         s->server = server;
268         if (cb != NULL)
269             cb(s, SSL_CB_HANDSHAKE_START, 1);
270
271         if (SSL_IS_DTLS(s)) {
272             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
273                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
274                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
275                 goto end;
276             }
277         } else {
278             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
279                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
280                 goto end;
281             }
282         }
283
284         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
285             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
286             goto end;
287         }
288
289         if (s->init_buf == NULL) {
290             if ((buf = BUF_MEM_new()) == NULL) {
291                 goto end;
292             }
293             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
294                 goto end;
295             }
296             s->init_buf = buf;
297             buf = NULL;
298         }
299
300         if (!ssl3_setup_buffers(s)) {
301             goto end;
302         }
303         s->init_num = 0;
304
305         /*
306          * Should have been reset by tls_process_finished, too.
307          */
308         s->s3->change_cipher_spec = 0;
309
310         /*
311          * Ok, we now need to push on a buffering BIO ...but not with
312          * SCTP
313          */
314 #ifndef OPENSSL_NO_SCTP
315         if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
316 #endif
317             if (!ssl_init_wbio_buffer(s)) {
318                 goto end;
319             }
320
321         if (!server || st->state != MSG_FLOW_RENEGOTIATE) {
322             if (!ssl3_init_finished_mac(s)) {
323                 ossl_statem_set_error(s);
324                 goto end;
325             }
326         }
327
328         if (server) {
329             if (st->state != MSG_FLOW_RENEGOTIATE) {
330                 s->ctx->stats.sess_accept++;
331             } else if (!s->s3->send_connection_binding &&
332                        !(s->options &
333                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
334                 /*
335                  * Server attempting to renegotiate with client that doesn't
336                  * support secure renegotiation.
337                  */
338                 SSLerr(SSL_F_STATE_MACHINE,
339                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
340                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
341                 ossl_statem_set_error(s);
342                 goto end;
343             } else {
344                 /*
345                  * st->state == MSG_FLOW_RENEGOTIATE, we will just send a
346                  * HelloRequest
347                  */
348                 s->ctx->stats.sess_accept_renegotiate++;
349             }
350
351             s->s3->tmp.cert_request = 0;
352         } else {
353             s->ctx->stats.sess_connect++;
354
355             /* mark client_random uninitialized */
356             memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
357             s->hit = 0;
358
359             s->s3->tmp.cert_req = 0;
360
361             if (SSL_IS_DTLS(s)) {
362                 st->use_timer = 1;
363             }
364         }
365
366         st->state = MSG_FLOW_WRITING;
367         init_write_state_machine(s);
368         st->read_state_first_init = 1;
369     }
370
371     while (st->state != MSG_FLOW_FINISHED) {
372         if (st->state == MSG_FLOW_READING) {
373             ssret = read_state_machine(s);
374             if (ssret == SUB_STATE_FINISHED) {
375                 st->state = MSG_FLOW_WRITING;
376                 init_write_state_machine(s);
377             } else {
378                 /* NBIO or error */
379                 goto end;
380             }
381         } else if (st->state == MSG_FLOW_WRITING) {
382             ssret = write_state_machine(s);
383             if (ssret == SUB_STATE_FINISHED) {
384                 st->state = MSG_FLOW_READING;
385                 init_read_state_machine(s);
386             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
387                 st->state = MSG_FLOW_FINISHED;
388             } else {
389                 /* NBIO or error */
390                 goto end;
391             }
392         } else {
393             /* Error */
394             ossl_statem_set_error(s);
395             goto end;
396         }
397     }
398
399     st->state = MSG_FLOW_UNINITED;
400     ret = 1;
401
402  end:
403     st->in_handshake--;
404
405 #ifndef OPENSSL_NO_SCTP
406     if (SSL_IS_DTLS(s)) {
407         /*
408          * Notify SCTP BIO socket to leave handshake mode and allow stream
409          * identifier other than 0. Will be ignored if no SCTP is used.
410          */
411         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
412                  st->in_handshake, NULL);
413     }
414 #endif
415
416     BUF_MEM_free(buf);
417     if (cb != NULL) {
418         if (server)
419             cb(s, SSL_CB_ACCEPT_EXIT, ret);
420         else
421             cb(s, SSL_CB_CONNECT_EXIT, ret);
422     }
423     return ret;
424 }
425
426 /*
427  * Initialise the MSG_FLOW_READING sub-state machine
428  */
429 static void init_read_state_machine(SSL *s)
430 {
431     OSSL_STATEM *st = &s->statem;
432
433     st->read_state = READ_STATE_HEADER;
434 }
435
436 static int grow_init_buf(SSL *s, size_t size) {
437
438     size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
439
440     if (!BUF_MEM_grow_clean(s->init_buf, (int)size))
441         return 0;
442
443     if (size < msg_offset)
444         return 0;
445
446     s->init_msg = s->init_buf->data + msg_offset;
447
448     return 1;
449 }
450
451 /*
452  * This function implements the sub-state machine when the message flow is in
453  * MSG_FLOW_READING. The valid sub-states and transitions are:
454  *
455  * READ_STATE_HEADER <--+<-------------+
456  *        |             |              |
457  *        v             |              |
458  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
459  *        |                            |
460  *        +----------------------------+
461  *        v
462  * [SUB_STATE_FINISHED]
463  *
464  * READ_STATE_HEADER has the responsibility for reading in the message header
465  * and transitioning the state of the handshake state machine.
466  *
467  * READ_STATE_BODY reads in the rest of the message and then subsequently
468  * processes it.
469  *
470  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
471  * processing activity performed on the message may block.
472  *
473  * Any of the above states could result in an NBIO event occurring in which case
474  * control returns to the calling application. When this function is recalled we
475  * will resume in the same state where we left off.
476  */
477 static SUB_STATE_RETURN read_state_machine(SSL *s)
478 {
479     OSSL_STATEM *st = &s->statem;
480     int ret, mt;
481     size_t len = 0;
482     int (*transition) (SSL *s, int mt);
483     PACKET pkt;
484     MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
485     WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
486     size_t (*max_message_size) (SSL *s);
487     void (*cb) (const SSL *ssl, int type, int val) = NULL;
488
489     cb = get_callback(s);
490
491     if (s->server) {
492         transition = ossl_statem_server_read_transition;
493         process_message = ossl_statem_server_process_message;
494         max_message_size = ossl_statem_server_max_message_size;
495         post_process_message = ossl_statem_server_post_process_message;
496     } else {
497         transition = ossl_statem_client_read_transition;
498         process_message = ossl_statem_client_process_message;
499         max_message_size = ossl_statem_client_max_message_size;
500         post_process_message = ossl_statem_client_post_process_message;
501     }
502
503     if (st->read_state_first_init) {
504         s->first_packet = 1;
505         st->read_state_first_init = 0;
506     }
507
508     while (1) {
509         switch (st->read_state) {
510         case READ_STATE_HEADER:
511             /* Get the state the peer wants to move to */
512             if (SSL_IS_DTLS(s)) {
513                 /*
514                  * In DTLS we get the whole message in one go - header and body
515                  */
516                 ret = dtls_get_message(s, &mt, &len);
517             } else {
518                 ret = tls_get_message_header(s, &mt);
519             }
520
521             if (ret == 0) {
522                 /* Could be non-blocking IO */
523                 return SUB_STATE_ERROR;
524             }
525
526             if (cb != NULL) {
527                 /* Notify callback of an impending state change */
528                 if (s->server)
529                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
530                 else
531                     cb(s, SSL_CB_CONNECT_LOOP, 1);
532             }
533             /*
534              * Validate that we are allowed to move to the new state and move
535              * to that state if so
536              */
537             if (!transition(s, mt)) {
538                 ossl_statem_set_error(s);
539                 return SUB_STATE_ERROR;
540             }
541
542             if (s->s3->tmp.message_size > max_message_size(s)) {
543                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
544                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
545                 return SUB_STATE_ERROR;
546             }
547
548             /* dtls_get_message already did this */
549             if (!SSL_IS_DTLS(s)
550                     && s->s3->tmp.message_size > 0
551                     && !grow_init_buf(s, s->s3->tmp.message_size
552                                          + SSL3_HM_HEADER_LENGTH)) {
553                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
554                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_BUF_LIB);
555                 return SUB_STATE_ERROR;
556             }
557
558             st->read_state = READ_STATE_BODY;
559             /* Fall through */
560
561         case READ_STATE_BODY:
562             if (!SSL_IS_DTLS(s)) {
563                 /* We already got this above for DTLS */
564                 ret = tls_get_message_body(s, &len);
565                 if (ret == 0) {
566                     /* Could be non-blocking IO */
567                     return SUB_STATE_ERROR;
568                 }
569             }
570
571             s->first_packet = 0;
572             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
573                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
574                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
575                 return SUB_STATE_ERROR;
576             }
577             ret = process_message(s, &pkt);
578
579             /* Discard the packet data */
580             s->init_num = 0;
581
582             switch (ret) {
583             case MSG_PROCESS_ERROR:
584                 return SUB_STATE_ERROR;
585
586             case MSG_PROCESS_FINISHED_READING:
587                 if (SSL_IS_DTLS(s)) {
588                     dtls1_stop_timer(s);
589                 }
590                 return SUB_STATE_FINISHED;
591
592             case MSG_PROCESS_CONTINUE_PROCESSING:
593                 st->read_state = READ_STATE_POST_PROCESS;
594                 st->read_state_work = WORK_MORE_A;
595                 break;
596
597             default:
598                 st->read_state = READ_STATE_HEADER;
599                 break;
600             }
601             break;
602
603         case READ_STATE_POST_PROCESS:
604             st->read_state_work = post_process_message(s, st->read_state_work);
605             switch (st->read_state_work) {
606             case WORK_ERROR:
607             case WORK_MORE_A:
608             case WORK_MORE_B:
609                 return SUB_STATE_ERROR;
610
611             case WORK_FINISHED_CONTINUE:
612                 st->read_state = READ_STATE_HEADER;
613                 break;
614
615             case WORK_FINISHED_STOP:
616                 if (SSL_IS_DTLS(s)) {
617                     dtls1_stop_timer(s);
618                 }
619                 return SUB_STATE_FINISHED;
620             }
621             break;
622
623         default:
624             /* Shouldn't happen */
625             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
626             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
627             ossl_statem_set_error(s);
628             return SUB_STATE_ERROR;
629         }
630     }
631 }
632
633 /*
634  * Send a previously constructed message to the peer.
635  */
636 static int statem_do_write(SSL *s)
637 {
638     OSSL_STATEM *st = &s->statem;
639
640     if (st->hand_state == TLS_ST_CW_CHANGE
641         || st->hand_state == TLS_ST_SW_CHANGE) {
642         if (SSL_IS_DTLS(s))
643             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
644         else
645             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
646     } else {
647         return ssl_do_write(s);
648     }
649 }
650
651 /*
652  * Initialise the MSG_FLOW_WRITING sub-state machine
653  */
654 static void init_write_state_machine(SSL *s)
655 {
656     OSSL_STATEM *st = &s->statem;
657
658     st->write_state = WRITE_STATE_TRANSITION;
659 }
660
661 /*
662  * This function implements the sub-state machine when the message flow is in
663  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
664  *
665  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
666  * |             |
667  * |             v
668  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
669  * |             |
670  * |             v
671  * |       WRITE_STATE_SEND
672  * |             |
673  * |             v
674  * |     WRITE_STATE_POST_WORK
675  * |             |
676  * +-------------+
677  *
678  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
679
680  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
681  * sending of the message. This could result in an NBIO event occurring in
682  * which case control returns to the calling application. When this function
683  * is recalled we will resume in the same state where we left off.
684  *
685  * WRITE_STATE_SEND sends the message and performs any work to be done after
686  * sending.
687  *
688  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
689  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
690  * result in an NBIO event.
691  */
692 static SUB_STATE_RETURN write_state_machine(SSL *s)
693 {
694     OSSL_STATEM *st = &s->statem;
695     int ret;
696     WRITE_TRAN(*transition) (SSL *s);
697     WORK_STATE(*pre_work) (SSL *s, WORK_STATE wst);
698     WORK_STATE(*post_work) (SSL *s, WORK_STATE wst);
699     int (*get_construct_message_f) (SSL *s, WPACKET *pkt,
700                                     int (**confunc) (SSL *s, WPACKET *pkt),
701                                     int *mt);
702     void (*cb) (const SSL *ssl, int type, int val) = NULL;
703     int (*confunc) (SSL *s, WPACKET *pkt);
704     int mt;
705     WPACKET pkt;
706
707     cb = get_callback(s);
708
709     if (s->server) {
710         transition = ossl_statem_server_write_transition;
711         pre_work = ossl_statem_server_pre_work;
712         post_work = ossl_statem_server_post_work;
713         get_construct_message_f = ossl_statem_server_construct_message;
714     } else {
715         transition = ossl_statem_client_write_transition;
716         pre_work = ossl_statem_client_pre_work;
717         post_work = ossl_statem_client_post_work;
718         get_construct_message_f = ossl_statem_client_construct_message;
719     }
720
721     while (1) {
722         switch (st->write_state) {
723         case WRITE_STATE_TRANSITION:
724             if (cb != NULL) {
725                 /* Notify callback of an impending state change */
726                 if (s->server)
727                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
728                 else
729                     cb(s, SSL_CB_CONNECT_LOOP, 1);
730             }
731             switch (transition(s)) {
732             case WRITE_TRAN_CONTINUE:
733                 st->write_state = WRITE_STATE_PRE_WORK;
734                 st->write_state_work = WORK_MORE_A;
735                 break;
736
737             case WRITE_TRAN_FINISHED:
738                 return SUB_STATE_FINISHED;
739                 break;
740
741             case WRITE_TRAN_ERROR:
742                 return SUB_STATE_ERROR;
743             }
744             break;
745
746         case WRITE_STATE_PRE_WORK:
747             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
748             case WORK_ERROR:
749             case WORK_MORE_A:
750             case WORK_MORE_B:
751                 return SUB_STATE_ERROR;
752
753             case WORK_FINISHED_CONTINUE:
754                 st->write_state = WRITE_STATE_SEND;
755                 break;
756
757             case WORK_FINISHED_STOP:
758                 return SUB_STATE_END_HANDSHAKE;
759             }
760             if (!WPACKET_init(&pkt, s->init_buf)
761                     || !get_construct_message_f(s, &pkt, &confunc, &mt)
762                     || !ssl_set_handshake_header(s, &pkt, mt)
763                     || (confunc != NULL && !confunc(s, &pkt))
764                     || !ssl_close_construct_packet(s, &pkt, mt)
765                     || !WPACKET_finish(&pkt)) {
766                 WPACKET_cleanup(&pkt);
767                 ossl_statem_set_error(s);
768                 return SUB_STATE_ERROR;
769             }
770
771             /* Fall through */
772
773         case WRITE_STATE_SEND:
774             if (SSL_IS_DTLS(s) && st->use_timer) {
775                 dtls1_start_timer(s);
776             }
777             ret = statem_do_write(s);
778             if (ret <= 0) {
779                 return SUB_STATE_ERROR;
780             }
781             st->write_state = WRITE_STATE_POST_WORK;
782             st->write_state_work = WORK_MORE_A;
783             /* Fall through */
784
785         case WRITE_STATE_POST_WORK:
786             switch (st->write_state_work = post_work(s, st->write_state_work)) {
787             case WORK_ERROR:
788             case WORK_MORE_A:
789             case WORK_MORE_B:
790                 return SUB_STATE_ERROR;
791
792             case WORK_FINISHED_CONTINUE:
793                 st->write_state = WRITE_STATE_TRANSITION;
794                 break;
795
796             case WORK_FINISHED_STOP:
797                 return SUB_STATE_END_HANDSHAKE;
798             }
799             break;
800
801         default:
802             return SUB_STATE_ERROR;
803         }
804     }
805 }
806
807 /*
808  * Flush the write BIO
809  */
810 int statem_flush(SSL *s)
811 {
812     s->rwstate = SSL_WRITING;
813     if (BIO_flush(s->wbio) <= 0) {
814         return 0;
815     }
816     s->rwstate = SSL_NOTHING;
817
818     return 1;
819 }
820
821 /*
822  * Called by the record layer to determine whether application data is
823  * allowed to be sent in the current handshake state or not.
824  *
825  * Return values are:
826  *   1: Yes (application data allowed)
827  *   0: No (application data not allowed)
828  */
829 int ossl_statem_app_data_allowed(SSL *s)
830 {
831     OSSL_STATEM *st = &s->statem;
832
833     if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE)
834         return 0;
835
836     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
837         return 0;
838
839     if (s->server) {
840         /*
841          * If we're a server and we haven't got as far as writing our
842          * ServerHello yet then we allow app data
843          */
844         if (st->hand_state == TLS_ST_BEFORE
845             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
846             return 1;
847     } else {
848         /*
849          * If we're a client and we haven't read the ServerHello yet then we
850          * allow app data
851          */
852         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
853             return 1;
854     }
855
856     return 0;
857 }
858
859 #ifndef OPENSSL_NO_SCTP
860 /*
861  * Set flag used by SCTP to determine whether we are in the read sock state
862  */
863 void ossl_statem_set_sctp_read_sock(SSL *s, int read_sock)
864 {
865     s->statem.in_sctp_read_sock = read_sock;
866 }
867
868 /*
869  * Called by the record layer to determine whether we are in the read sock
870  * state or not.
871  *
872  * Return values are:
873  *   1: Yes (we are in the read sock state)
874  *   0: No (we are not in the read sock state)
875  */
876 int ossl_statem_in_sctp_read_sock(SSL *s)
877 {
878     return s->statem.in_sctp_read_sock;
879 }
880 #endif