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