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