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