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