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