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