97fd797f7e1dea21ebbf0253a69d649275634aa5
[openssl.git] / ssl / statem / statem.c
1 /*
2  * Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #include <openssl/rand.h>
12 #include "../ssl_locl.h"
13 #include "statem_locl.h"
14
15 /*
16  * This file implements the SSL/TLS/DTLS state machines.
17  *
18  * There are two primary state machines:
19  *
20  * 1) Message flow state machine
21  * 2) Handshake state machine
22  *
23  * The Message flow state machine controls the reading and sending of messages
24  * including handling of non-blocking IO events, flushing of the underlying
25  * write BIO, handling unexpected messages, etc. It is itself broken into two
26  * separate sub-state machines which control reading and writing respectively.
27  *
28  * The Handshake state machine keeps track of the current SSL/TLS handshake
29  * state. Transitions of the handshake state are the result of events that
30  * occur within the Message flow state machine.
31  *
32  * Overall it looks like this:
33  *
34  * ---------------------------------------------            -------------------
35  * |                                           |            |                 |
36  * | Message flow state machine                |            |                 |
37  * |                                           |            |                 |
38  * | -------------------- -------------------- | Transition | Handshake state |
39  * | | MSG_FLOW_READING | | MSG_FLOW_WRITING | | Event      | machine         |
40  * | | sub-state        | | sub-state        | |----------->|                 |
41  * | | machine for      | | machine for      | |            |                 |
42  * | | reading messages | | writing messages | |            |                 |
43  * | -------------------- -------------------- |            |                 |
44  * |                                           |            |                 |
45  * ---------------------------------------------            -------------------
46  *
47  */
48
49 /* Sub state machine return values */
50 typedef enum {
51     /* Something bad happened or NBIO */
52     SUB_STATE_ERROR,
53     /* Sub state finished go to the next sub state */
54     SUB_STATE_FINISHED,
55     /* Sub state finished and handshake was completed */
56     SUB_STATE_END_HANDSHAKE
57 } SUB_STATE_RETURN;
58
59 static int state_machine(SSL *s, int server);
60 static void init_read_state_machine(SSL *s);
61 static SUB_STATE_RETURN read_state_machine(SSL *s);
62 static void init_write_state_machine(SSL *s);
63 static SUB_STATE_RETURN write_state_machine(SSL *s);
64
65 OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl)
66 {
67     return ssl->statem.hand_state;
68 }
69
70 int SSL_in_init(SSL *s)
71 {
72     return s->statem.in_init;
73 }
74
75 int SSL_is_init_finished(SSL *s)
76 {
77     return !(s->statem.in_init) && (s->statem.hand_state == TLS_ST_OK);
78 }
79
80 int SSL_in_before(SSL *s)
81 {
82     /*
83      * Historically being "in before" meant before anything had happened. In the
84      * current code though we remain in the "before" state for a while after we
85      * have started the handshake process (e.g. as a server waiting for the
86      * first message to arrive). There "in before" is taken to mean "in before"
87      * and not started any handshake process yet.
88      */
89     return (s->statem.hand_state == TLS_ST_BEFORE)
90         && (s->statem.state == MSG_FLOW_UNINITED);
91 }
92
93 /*
94  * Clear the state machine state and reset back to MSG_FLOW_UNINITED
95  */
96 void ossl_statem_clear(SSL *s)
97 {
98     s->statem.state = MSG_FLOW_UNINITED;
99     s->statem.hand_state = TLS_ST_BEFORE;
100     s->statem.in_init = 1;
101     s->statem.no_cert_verify = 0;
102 }
103
104 /*
105  * Set the state machine up ready for a renegotiation handshake
106  */
107 void ossl_statem_set_renegotiate(SSL *s)
108 {
109     s->statem.in_init = 1;
110     s->statem.request_state = TLS_ST_SW_HELLO_REQ;
111 }
112
113 /*
114  * Put the state machine into an error state and send an alert if appropriate.
115  * This is a permanent error for the current connection.
116  */
117 void ossl_statem_fatal(SSL *s, int al, int func, int reason, const char *file,
118                        int line)
119 {
120     s->statem.in_init = 1;
121     s->statem.state = MSG_FLOW_ERROR;
122     ERR_put_error(ERR_LIB_SSL, func, reason, file, line);
123     if (al != SSL_AD_NO_ALERT)
124         ssl3_send_alert(s, SSL3_AL_FATAL, al);
125 }
126
127 /*
128  * Discover whether the current connection is in the error state.
129  *
130  * Valid return values are:
131  *   1: Yes
132  *   0: No
133  */
134 int ossl_statem_in_error(const SSL *s)
135 {
136     if (s->statem.state == MSG_FLOW_ERROR)
137         return 1;
138
139     return 0;
140 }
141
142 void ossl_statem_set_in_init(SSL *s, int init)
143 {
144     s->statem.in_init = init;
145 }
146
147 int ossl_statem_get_in_handshake(SSL *s)
148 {
149     return s->statem.in_handshake;
150 }
151
152 void ossl_statem_set_in_handshake(SSL *s, int inhand)
153 {
154     if (inhand)
155         s->statem.in_handshake++;
156     else
157         s->statem.in_handshake--;
158 }
159
160 /* Are we in a sensible state to skip over unreadable early data? */
161 int ossl_statem_skip_early_data(SSL *s)
162 {
163     if (s->ext.early_data != SSL_EARLY_DATA_REJECTED)
164         return 0;
165
166     if (!s->server || s->statem.hand_state != TLS_ST_EARLY_DATA)
167         return 0;
168
169     return 1;
170 }
171
172 /*
173  * Called when we are in SSL_read*(), SSL_write*(), or SSL_accept()
174  * /SSL_connect()/SSL_do_handshake(). Used to test whether we are in an early
175  * data state and whether we should attempt to move the handshake on if so.
176  * |sending| is 1 if we are attempting to send data (SSL_write*()), 0 if we are
177  * attempting to read data (SSL_read*()), or -1 if we are in SSL_do_handshake()
178  * or similar.
179  */
180 void ossl_statem_check_finish_init(SSL *s, int sending)
181 {
182     if (sending == -1) {
183         if (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
184                 || s->statem.hand_state == TLS_ST_EARLY_DATA) {
185             ossl_statem_set_in_init(s, 1);
186             if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY) {
187                 /*
188                  * SSL_connect() or SSL_do_handshake() has been called directly.
189                  * We don't allow any more writing of early data.
190                  */
191                 s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
192             }
193         }
194     } else if (!s->server) {
195         if ((sending && (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
196                       || s->statem.hand_state == TLS_ST_EARLY_DATA)
197                   && s->early_data_state != SSL_EARLY_DATA_WRITING)
198                 || (!sending && s->statem.hand_state == TLS_ST_EARLY_DATA)) {
199             ossl_statem_set_in_init(s, 1);
200             /*
201              * SSL_write() has been called directly. We don't allow any more
202              * writing of early data.
203              */
204             if (sending && s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY)
205                 s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
206         }
207     } else {
208         if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING
209                 && s->statem.hand_state == TLS_ST_EARLY_DATA)
210             ossl_statem_set_in_init(s, 1);
211     }
212 }
213
214 void ossl_statem_set_hello_verify_done(SSL *s)
215 {
216     s->statem.state = MSG_FLOW_UNINITED;
217     s->statem.in_init = 1;
218     /*
219      * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
220      * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
221      * calls to SSL_in_before() will return false. Also calls to
222      * SSL_state_string() and SSL_state_string_long() will return something
223      * sensible.
224      */
225     s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
226 }
227
228 int ossl_statem_connect(SSL *s)
229 {
230     return state_machine(s, 0);
231 }
232
233 int ossl_statem_accept(SSL *s)
234 {
235     return state_machine(s, 1);
236 }
237
238 typedef void (*info_cb) (const SSL *, int, int);
239
240 static info_cb get_callback(SSL *s)
241 {
242     if (s->info_callback != NULL)
243         return s->info_callback;
244     else if (s->ctx->info_callback != NULL)
245         return s->ctx->info_callback;
246
247     return NULL;
248 }
249
250 /*
251  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
252  * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
253  * transitions are as follows:
254  *
255  * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
256  *        |                       |
257  *        +-----------------------+
258  *        v
259  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
260  *        |
261  *        V
262  * MSG_FLOW_FINISHED
263  *        |
264  *        V
265  *    [SUCCESS]
266  *
267  * We may exit at any point due to an error or NBIO event. If an NBIO event
268  * occurs then we restart at the point we left off when we are recalled.
269  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
270  *
271  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
272  * into that state at any point in the event that an irrecoverable error occurs.
273  *
274  * Valid return values are:
275  *   1: Success
276  * <=0: NBIO or error
277  */
278 static int state_machine(SSL *s, int server)
279 {
280     BUF_MEM *buf = NULL;
281     void (*cb) (const SSL *ssl, int type, int val) = NULL;
282     OSSL_STATEM *st = &s->statem;
283     int ret = -1;
284     int ssret;
285
286     if (st->state == MSG_FLOW_ERROR) {
287         /* Shouldn't have been called if we're already in the error state */
288         return -1;
289     }
290
291     ERR_clear_error();
292     clear_sys_error();
293
294     cb = get_callback(s);
295
296     st->in_handshake++;
297     if (!SSL_in_init(s) || SSL_in_before(s)) {
298         if (!SSL_clear(s))
299             return -1;
300     }
301 #ifndef OPENSSL_NO_SCTP
302     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
303         /*
304          * Notify SCTP BIO socket to enter handshake mode and prevent stream
305          * identifier other than 0.
306          */
307         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
308                  st->in_handshake, NULL);
309     }
310 #endif
311
312     /* Initialise state machine */
313     if (st->state == MSG_FLOW_UNINITED
314             || st->state == MSG_FLOW_FINISHED) {
315         if (st->state == MSG_FLOW_UNINITED) {
316             st->hand_state = TLS_ST_BEFORE;
317             st->request_state = TLS_ST_BEFORE;
318         }
319
320         s->server = server;
321         if (cb != NULL)
322             cb(s, SSL_CB_HANDSHAKE_START, 1);
323
324         if (SSL_IS_DTLS(s)) {
325             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
326                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
327                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
328                 goto end;
329             }
330         } else {
331             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
332                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
333                 goto end;
334             }
335         }
336
337         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
338             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
339             goto end;
340         }
341
342         if (s->init_buf == NULL) {
343             if ((buf = BUF_MEM_new()) == NULL) {
344                 goto end;
345             }
346             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
347                 goto end;
348             }
349             s->init_buf = buf;
350             buf = NULL;
351         }
352
353         if (!ssl3_setup_buffers(s)) {
354             goto end;
355         }
356         s->init_num = 0;
357
358         /*
359          * Should have been reset by tls_process_finished, too.
360          */
361         s->s3->change_cipher_spec = 0;
362
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)) {
371                 goto end;
372             }
373
374         if ((SSL_in_before(s))
375                 || s->renegotiate) {
376             if (!tls_setup_handshake(s))
377                 goto end;
378
379             if (SSL_IS_FIRST_HANDSHAKE(s))
380                 st->read_state_first_init = 1;
381         }
382
383         st->state = MSG_FLOW_WRITING;
384         init_write_state_machine(s);
385     }
386
387     while (st->state != MSG_FLOW_FINISHED) {
388         if (st->state == MSG_FLOW_READING) {
389             ssret = read_state_machine(s);
390             if (ssret == SUB_STATE_FINISHED) {
391                 st->state = MSG_FLOW_WRITING;
392                 init_write_state_machine(s);
393             } else {
394                 /* NBIO or error */
395                 goto end;
396             }
397         } else if (st->state == MSG_FLOW_WRITING) {
398             ssret = write_state_machine(s);
399             if (ssret == SUB_STATE_FINISHED) {
400                 st->state = MSG_FLOW_READING;
401                 init_read_state_machine(s);
402             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
403                 st->state = MSG_FLOW_FINISHED;
404             } else {
405                 /* NBIO or error */
406                 goto end;
407             }
408         } else {
409             /* Error */
410             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_STATE_MACHINE,
411                      ERR_R_INTERNAL_ERROR);
412             goto end;
413         }
414     }
415
416     ret = 1;
417
418  end:
419     st->in_handshake--;
420
421 #ifndef OPENSSL_NO_SCTP
422     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
423         /*
424          * Notify SCTP BIO socket to leave handshake mode and allow stream
425          * identifier other than 0.
426          */
427         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
428                  st->in_handshake, NULL);
429     }
430 #endif
431
432     BUF_MEM_free(buf);
433     if (cb != NULL) {
434         if (server)
435             cb(s, SSL_CB_ACCEPT_EXIT, ret);
436         else
437             cb(s, SSL_CB_CONNECT_EXIT, ret);
438     }
439     return ret;
440 }
441
442 /*
443  * Initialise the MSG_FLOW_READING sub-state machine
444  */
445 static void init_read_state_machine(SSL *s)
446 {
447     OSSL_STATEM *st = &s->statem;
448
449     st->read_state = READ_STATE_HEADER;
450 }
451
452 static int grow_init_buf(SSL *s, size_t size) {
453
454     size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
455
456     if (!BUF_MEM_grow_clean(s->init_buf, (int)size))
457         return 0;
458
459     if (size < msg_offset)
460         return 0;
461
462     s->init_msg = s->init_buf->data + msg_offset;
463
464     return 1;
465 }
466
467 /*
468  * This function implements the sub-state machine when the message flow is in
469  * MSG_FLOW_READING. The valid sub-states and transitions are:
470  *
471  * READ_STATE_HEADER <--+<-------------+
472  *        |             |              |
473  *        v             |              |
474  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
475  *        |                            |
476  *        +----------------------------+
477  *        v
478  * [SUB_STATE_FINISHED]
479  *
480  * READ_STATE_HEADER has the responsibility for reading in the message header
481  * and transitioning the state of the handshake state machine.
482  *
483  * READ_STATE_BODY reads in the rest of the message and then subsequently
484  * processes it.
485  *
486  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
487  * processing activity performed on the message may block.
488  *
489  * Any of the above states could result in an NBIO event occurring in which case
490  * control returns to the calling application. When this function is recalled we
491  * will resume in the same state where we left off.
492  */
493 static SUB_STATE_RETURN read_state_machine(SSL *s)
494 {
495     OSSL_STATEM *st = &s->statem;
496     int ret, mt;
497     size_t len = 0;
498     int (*transition) (SSL *s, int mt);
499     PACKET pkt;
500     MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
501     WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
502     size_t (*max_message_size) (SSL *s);
503     void (*cb) (const SSL *ssl, int type, int val) = NULL;
504
505     cb = get_callback(s);
506
507     if (s->server) {
508         transition = ossl_statem_server_read_transition;
509         process_message = ossl_statem_server_process_message;
510         max_message_size = ossl_statem_server_max_message_size;
511         post_process_message = ossl_statem_server_post_process_message;
512     } else {
513         transition = ossl_statem_client_read_transition;
514         process_message = ossl_statem_client_process_message;
515         max_message_size = ossl_statem_client_max_message_size;
516         post_process_message = ossl_statem_client_post_process_message;
517     }
518
519     if (st->read_state_first_init) {
520         s->first_packet = 1;
521         st->read_state_first_init = 0;
522     }
523
524     while (1) {
525         switch (st->read_state) {
526         case READ_STATE_HEADER:
527             /* Get the state the peer wants to move to */
528             if (SSL_IS_DTLS(s)) {
529                 /*
530                  * In DTLS we get the whole message in one go - header and body
531                  */
532                 ret = dtls_get_message(s, &mt, &len);
533             } else {
534                 ret = tls_get_message_header(s, &mt);
535             }
536
537             if (ret == 0) {
538                 /* Could be non-blocking IO */
539                 return SUB_STATE_ERROR;
540             }
541
542             if (cb != NULL) {
543                 /* Notify callback of an impending state change */
544                 if (s->server)
545                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
546                 else
547                     cb(s, SSL_CB_CONNECT_LOOP, 1);
548             }
549             /*
550              * Validate that we are allowed to move to the new state and move
551              * to that state if so
552              */
553             if (!transition(s, mt)) {
554                 return SUB_STATE_ERROR;
555             }
556
557             if (s->s3->tmp.message_size > max_message_size(s)) {
558                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_READ_STATE_MACHINE,
559                          SSL_R_EXCESSIVE_MESSAGE_SIZE);
560                 return SUB_STATE_ERROR;
561             }
562
563             /* dtls_get_message already did this */
564             if (!SSL_IS_DTLS(s)
565                     && s->s3->tmp.message_size > 0
566                     && !grow_init_buf(s, s->s3->tmp.message_size
567                                          + SSL3_HM_HEADER_LENGTH)) {
568                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_READ_STATE_MACHINE,
569                          ERR_R_BUF_LIB);
570                 return SUB_STATE_ERROR;
571             }
572
573             st->read_state = READ_STATE_BODY;
574             /* Fall through */
575
576         case READ_STATE_BODY:
577             if (!SSL_IS_DTLS(s)) {
578                 /* We already got this above for DTLS */
579                 ret = tls_get_message_body(s, &len);
580                 if (ret == 0) {
581                     /* Could be non-blocking IO */
582                     return SUB_STATE_ERROR;
583                 }
584             }
585
586             s->first_packet = 0;
587             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
588                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_READ_STATE_MACHINE,
589                          ERR_R_INTERNAL_ERROR);
590                 return SUB_STATE_ERROR;
591             }
592             ret = process_message(s, &pkt);
593
594             /* Discard the packet data */
595             s->init_num = 0;
596
597             switch (ret) {
598             case MSG_PROCESS_ERROR:
599                 return SUB_STATE_ERROR;
600
601             case MSG_PROCESS_FINISHED_READING:
602                 if (SSL_IS_DTLS(s)) {
603                     dtls1_stop_timer(s);
604                 }
605                 return SUB_STATE_FINISHED;
606
607             case MSG_PROCESS_CONTINUE_PROCESSING:
608                 st->read_state = READ_STATE_POST_PROCESS;
609                 st->read_state_work = WORK_MORE_A;
610                 break;
611
612             default:
613                 st->read_state = READ_STATE_HEADER;
614                 break;
615             }
616             break;
617
618         case READ_STATE_POST_PROCESS:
619             st->read_state_work = post_process_message(s, st->read_state_work);
620             switch (st->read_state_work) {
621             case WORK_ERROR:
622             case WORK_MORE_A:
623             case WORK_MORE_B:
624             case WORK_MORE_C:
625                 return SUB_STATE_ERROR;
626
627             case WORK_FINISHED_CONTINUE:
628                 st->read_state = READ_STATE_HEADER;
629                 break;
630
631             case WORK_FINISHED_STOP:
632                 if (SSL_IS_DTLS(s)) {
633                     dtls1_stop_timer(s);
634                 }
635                 return SUB_STATE_FINISHED;
636             }
637             break;
638
639         default:
640             /* Shouldn't happen */
641             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_READ_STATE_MACHINE,
642                      ERR_R_INTERNAL_ERROR);
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 occurring 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     WRITE_TRAN(*transition) (SSL *s);
712     WORK_STATE(*pre_work) (SSL *s, WORK_STATE wst);
713     WORK_STATE(*post_work) (SSL *s, WORK_STATE wst);
714     int (*get_construct_message_f) (SSL *s, WPACKET *pkt,
715                                     int (**confunc) (SSL *s, WPACKET *pkt),
716                                     int *mt);
717     void (*cb) (const SSL *ssl, int type, int val) = NULL;
718     int (*confunc) (SSL *s, WPACKET *pkt);
719     int mt;
720     WPACKET pkt;
721
722     cb = get_callback(s);
723
724     if (s->server) {
725         transition = ossl_statem_server_write_transition;
726         pre_work = ossl_statem_server_pre_work;
727         post_work = ossl_statem_server_post_work;
728         get_construct_message_f = ossl_statem_server_construct_message;
729     } else {
730         transition = ossl_statem_client_write_transition;
731         pre_work = ossl_statem_client_pre_work;
732         post_work = ossl_statem_client_post_work;
733         get_construct_message_f = ossl_statem_client_construct_message;
734     }
735
736     while (1) {
737         switch (st->write_state) {
738         case WRITE_STATE_TRANSITION:
739             if (cb != NULL) {
740                 /* Notify callback of an impending state change */
741                 if (s->server)
742                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
743                 else
744                     cb(s, SSL_CB_CONNECT_LOOP, 1);
745             }
746             switch (transition(s)) {
747             case WRITE_TRAN_CONTINUE:
748                 st->write_state = WRITE_STATE_PRE_WORK;
749                 st->write_state_work = WORK_MORE_A;
750                 break;
751
752             case WRITE_TRAN_FINISHED:
753                 return SUB_STATE_FINISHED;
754                 break;
755
756             case WRITE_TRAN_ERROR:
757                 return SUB_STATE_ERROR;
758             }
759             break;
760
761         case WRITE_STATE_PRE_WORK:
762             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
763             case WORK_ERROR:
764             case WORK_MORE_A:
765             case WORK_MORE_B:
766             case WORK_MORE_C:
767                 return SUB_STATE_ERROR;
768
769             case WORK_FINISHED_CONTINUE:
770                 st->write_state = WRITE_STATE_SEND;
771                 break;
772
773             case WORK_FINISHED_STOP:
774                 return SUB_STATE_END_HANDSHAKE;
775             }
776             if (!get_construct_message_f(s, &pkt, &confunc, &mt)) {
777                 /* SSLfatal() already called */
778                 return SUB_STATE_ERROR;
779             }
780             if (mt == SSL3_MT_DUMMY) {
781                 /* Skip construction and sending. This isn't a "real" state */
782                 st->write_state = WRITE_STATE_POST_WORK;
783                 st->write_state_work = WORK_MORE_A;
784                 break;
785             }
786             if (!WPACKET_init(&pkt, s->init_buf)
787                     || !ssl_set_handshake_header(s, &pkt, mt)) {
788                 WPACKET_cleanup(&pkt);
789                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_WRITE_STATE_MACHINE,
790                          ERR_R_INTERNAL_ERROR);
791                 return SUB_STATE_ERROR;
792             }
793             if (confunc != NULL && !confunc(s, &pkt)) {
794                 WPACKET_cleanup(&pkt);
795                 /* SSLfatal() already called */
796                 return SUB_STATE_ERROR;
797             }
798             if (!ssl_close_construct_packet(s, &pkt, mt)
799                     || !WPACKET_finish(&pkt)) {
800                 WPACKET_cleanup(&pkt);
801                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_WRITE_STATE_MACHINE,
802                          ERR_R_INTERNAL_ERROR);
803                 return SUB_STATE_ERROR;
804             }
805
806             /* Fall through */
807
808         case WRITE_STATE_SEND:
809             if (SSL_IS_DTLS(s) && st->use_timer) {
810                 dtls1_start_timer(s);
811             }
812             ret = statem_do_write(s);
813             if (ret <= 0) {
814                 return SUB_STATE_ERROR;
815             }
816             st->write_state = WRITE_STATE_POST_WORK;
817             st->write_state_work = WORK_MORE_A;
818             /* Fall through */
819
820         case WRITE_STATE_POST_WORK:
821             switch (st->write_state_work = post_work(s, st->write_state_work)) {
822             case WORK_ERROR:
823             case WORK_MORE_A:
824             case WORK_MORE_B:
825             case WORK_MORE_C:
826                 return SUB_STATE_ERROR;
827
828             case WORK_FINISHED_CONTINUE:
829                 st->write_state = WRITE_STATE_TRANSITION;
830                 break;
831
832             case WORK_FINISHED_STOP:
833                 return SUB_STATE_END_HANDSHAKE;
834             }
835             break;
836
837         default:
838             return SUB_STATE_ERROR;
839         }
840     }
841 }
842
843 /*
844  * Flush the write BIO
845  */
846 int statem_flush(SSL *s)
847 {
848     s->rwstate = SSL_WRITING;
849     if (BIO_flush(s->wbio) <= 0) {
850         return 0;
851     }
852     s->rwstate = SSL_NOTHING;
853
854     return 1;
855 }
856
857 /*
858  * Called by the record layer to determine whether application data is
859  * allowed to be received in the current handshake state or not.
860  *
861  * Return values are:
862  *   1: Yes (application data allowed)
863  *   0: No (application data not allowed)
864  */
865 int ossl_statem_app_data_allowed(SSL *s)
866 {
867     OSSL_STATEM *st = &s->statem;
868
869     if (st->state == MSG_FLOW_UNINITED)
870         return 0;
871
872     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
873         return 0;
874
875     if (s->server) {
876         /*
877          * If we're a server and we haven't got as far as writing our
878          * ServerHello yet then we allow app data
879          */
880         if (st->hand_state == TLS_ST_BEFORE
881             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
882             return 1;
883     } else {
884         /*
885          * If we're a client and we haven't read the ServerHello yet then we
886          * allow app data
887          */
888         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
889             return 1;
890     }
891
892     return 0;
893 }