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