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