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