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