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