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