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