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