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