xref: /openssl/ssl/statem/statem.c (revision dc84829c)
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     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
363 
364     if (st->state == MSG_FLOW_ERROR) {
365         /* Shouldn't have been called if we're already in the error state */
366         return -1;
367     }
368 
369     ERR_clear_error();
370     clear_sys_error();
371 
372     cb = get_callback(s);
373 
374     st->in_handshake++;
375     if (!SSL_in_init(ssl) || SSL_in_before(ssl)) {
376         /*
377          * If we are stateless then we already called SSL_clear() - don't do
378          * it again and clear the STATELESS flag itself.
379          */
380         if ((s->s3.flags & TLS1_FLAGS_STATELESS) == 0 && !SSL_clear(ssl))
381             return -1;
382     }
383 #ifndef OPENSSL_NO_SCTP
384     if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
385         /*
386          * Notify SCTP BIO socket to enter handshake mode and prevent stream
387          * identifier other than 0.
388          */
389         BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
390                  st->in_handshake, NULL);
391     }
392 #endif
393 
394     /* Initialise state machine */
395     if (st->state == MSG_FLOW_UNINITED
396             || st->state == MSG_FLOW_FINISHED) {
397         if (st->state == MSG_FLOW_UNINITED) {
398             st->hand_state = TLS_ST_BEFORE;
399             st->request_state = TLS_ST_BEFORE;
400         }
401 
402         s->server = server;
403         if (cb != NULL) {
404             if (SSL_IS_FIRST_HANDSHAKE(s) || !SSL_CONNECTION_IS_TLS13(s))
405                 cb(ussl, SSL_CB_HANDSHAKE_START, 1);
406         }
407 
408         /*
409          * Fatal errors in this block don't send an alert because we have
410          * failed to even initialise properly. Sending an alert is probably
411          * doomed to failure.
412          */
413 
414         if (SSL_CONNECTION_IS_DTLS(s)) {
415             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
416                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
417                 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
418                 goto end;
419             }
420         } else {
421             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
422                 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
423                 goto end;
424             }
425         }
426 
427         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
428             SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
429             goto end;
430         }
431 
432         if (s->init_buf == NULL) {
433             if ((buf = BUF_MEM_new()) == NULL) {
434                 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
435                 goto end;
436             }
437             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
438                 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
439                 goto end;
440             }
441             s->init_buf = buf;
442             buf = NULL;
443         }
444 
445         s->init_num = 0;
446 
447         /*
448          * Should have been reset by tls_process_finished, too.
449          */
450         s->s3.change_cipher_spec = 0;
451 
452         /*
453          * Ok, we now need to push on a buffering BIO ...but not with
454          * SCTP
455          */
456 #ifndef OPENSSL_NO_SCTP
457         if (!SSL_CONNECTION_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(ssl)))
458 #endif
459             if (!ssl_init_wbio_buffer(s)) {
460                 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
461                 goto end;
462             }
463 
464         if ((SSL_in_before(ssl))
465                 || s->renegotiate) {
466             if (!tls_setup_handshake(s)) {
467                 /* SSLfatal() already called */
468                 goto end;
469             }
470 
471             if (SSL_IS_FIRST_HANDSHAKE(s))
472                 st->read_state_first_init = 1;
473         }
474 
475         st->state = MSG_FLOW_WRITING;
476         init_write_state_machine(s);
477     }
478 
479     while (st->state != MSG_FLOW_FINISHED) {
480         if (st->state == MSG_FLOW_READING) {
481             ssret = read_state_machine(s);
482             if (ssret == SUB_STATE_FINISHED) {
483                 st->state = MSG_FLOW_WRITING;
484                 init_write_state_machine(s);
485             } else {
486                 /* NBIO or error */
487                 goto end;
488             }
489         } else if (st->state == MSG_FLOW_WRITING) {
490             ssret = write_state_machine(s);
491             if (ssret == SUB_STATE_FINISHED) {
492                 st->state = MSG_FLOW_READING;
493                 init_read_state_machine(s);
494             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
495                 st->state = MSG_FLOW_FINISHED;
496             } else {
497                 /* NBIO or error */
498                 goto end;
499             }
500         } else {
501             /* Error */
502             check_fatal(s);
503             ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
504             goto end;
505         }
506     }
507 
508     ret = 1;
509 
510  end:
511     st->in_handshake--;
512 
513 #ifndef OPENSSL_NO_SCTP
514     if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
515         /*
516          * Notify SCTP BIO socket to leave handshake mode and allow stream
517          * identifier other than 0.
518          */
519         BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
520                  st->in_handshake, NULL);
521     }
522 #endif
523 
524     BUF_MEM_free(buf);
525     if (cb != NULL) {
526         if (server)
527             cb(ussl, SSL_CB_ACCEPT_EXIT, ret);
528         else
529             cb(ussl, SSL_CB_CONNECT_EXIT, ret);
530     }
531     return ret;
532 }
533 
534 /*
535  * Initialise the MSG_FLOW_READING sub-state machine
536  */
init_read_state_machine(SSL_CONNECTION * s)537 static void init_read_state_machine(SSL_CONNECTION *s)
538 {
539     OSSL_STATEM *st = &s->statem;
540 
541     st->read_state = READ_STATE_HEADER;
542 }
543 
grow_init_buf(SSL_CONNECTION * s,size_t size)544 static int grow_init_buf(SSL_CONNECTION *s, size_t size) {
545 
546     size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
547 
548     if (!BUF_MEM_grow_clean(s->init_buf, (int)size))
549         return 0;
550 
551     if (size < msg_offset)
552         return 0;
553 
554     s->init_msg = s->init_buf->data + msg_offset;
555 
556     return 1;
557 }
558 
559 /*
560  * This function implements the sub-state machine when the message flow is in
561  * MSG_FLOW_READING. The valid sub-states and transitions are:
562  *
563  * READ_STATE_HEADER <--+<-------------+
564  *        |             |              |
565  *        v             |              |
566  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
567  *        |                            |
568  *        +----------------------------+
569  *        v
570  * [SUB_STATE_FINISHED]
571  *
572  * READ_STATE_HEADER has the responsibility for reading in the message header
573  * and transitioning the state of the handshake state machine.
574  *
575  * READ_STATE_BODY reads in the rest of the message and then subsequently
576  * processes it.
577  *
578  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
579  * processing activity performed on the message may block.
580  *
581  * Any of the above states could result in an NBIO event occurring in which case
582  * control returns to the calling application. When this function is recalled we
583  * will resume in the same state where we left off.
584  */
read_state_machine(SSL_CONNECTION * s)585 static SUB_STATE_RETURN read_state_machine(SSL_CONNECTION *s)
586 {
587     OSSL_STATEM *st = &s->statem;
588     int ret, mt;
589     size_t len = 0;
590     int (*transition) (SSL_CONNECTION *s, int mt);
591     PACKET pkt;
592     MSG_PROCESS_RETURN(*process_message) (SSL_CONNECTION *s, PACKET *pkt);
593     WORK_STATE(*post_process_message) (SSL_CONNECTION *s, WORK_STATE wst);
594     size_t (*max_message_size) (SSL_CONNECTION *s);
595     void (*cb) (const SSL *ssl, int type, int val) = NULL;
596     SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
597 
598     cb = get_callback(s);
599 
600     if (s->server) {
601         transition = ossl_statem_server_read_transition;
602         process_message = ossl_statem_server_process_message;
603         max_message_size = ossl_statem_server_max_message_size;
604         post_process_message = ossl_statem_server_post_process_message;
605     } else {
606         transition = ossl_statem_client_read_transition;
607         process_message = ossl_statem_client_process_message;
608         max_message_size = ossl_statem_client_max_message_size;
609         post_process_message = ossl_statem_client_post_process_message;
610     }
611 
612     if (st->read_state_first_init) {
613         s->first_packet = 1;
614         st->read_state_first_init = 0;
615     }
616 
617     while (1) {
618         switch (st->read_state) {
619         case READ_STATE_HEADER:
620             /* Get the state the peer wants to move to */
621             if (SSL_CONNECTION_IS_DTLS(s)) {
622                 /*
623                  * In DTLS we get the whole message in one go - header and body
624                  */
625                 ret = dtls_get_message(s, &mt);
626             } else {
627                 ret = tls_get_message_header(s, &mt);
628             }
629 
630             if (ret == 0) {
631                 /* Could be non-blocking IO */
632                 return SUB_STATE_ERROR;
633             }
634 
635             if (cb != NULL) {
636                 /* Notify callback of an impending state change */
637                 if (s->server)
638                     cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
639                 else
640                     cb(ssl, SSL_CB_CONNECT_LOOP, 1);
641             }
642             /*
643              * Validate that we are allowed to move to the new state and move
644              * to that state if so
645              */
646             if (!transition(s, mt))
647                 return SUB_STATE_ERROR;
648 
649             if (s->s3.tmp.message_size > max_message_size(s)) {
650                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
651                          SSL_R_EXCESSIVE_MESSAGE_SIZE);
652                 return SUB_STATE_ERROR;
653             }
654 
655             /* dtls_get_message already did this */
656             if (!SSL_CONNECTION_IS_DTLS(s)
657                     && s->s3.tmp.message_size > 0
658                     && !grow_init_buf(s, s->s3.tmp.message_size
659                                          + SSL3_HM_HEADER_LENGTH)) {
660                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
661                 return SUB_STATE_ERROR;
662             }
663 
664             st->read_state = READ_STATE_BODY;
665             /* Fall through */
666 
667         case READ_STATE_BODY:
668             if (SSL_CONNECTION_IS_DTLS(s)) {
669                 /*
670                  * Actually we already have the body, but we give DTLS the
671                  * opportunity to do any further processing.
672                  */
673                 ret = dtls_get_message_body(s, &len);
674             } else {
675                 ret = tls_get_message_body(s, &len);
676             }
677             if (ret == 0) {
678                 /* Could be non-blocking IO */
679                 return SUB_STATE_ERROR;
680             }
681 
682             s->first_packet = 0;
683             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
684                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
685                 return SUB_STATE_ERROR;
686             }
687             ret = process_message(s, &pkt);
688 
689             /* Discard the packet data */
690             s->init_num = 0;
691 
692             switch (ret) {
693             case MSG_PROCESS_ERROR:
694                 check_fatal(s);
695                 return SUB_STATE_ERROR;
696 
697             case MSG_PROCESS_FINISHED_READING:
698                 if (SSL_CONNECTION_IS_DTLS(s)) {
699                     dtls1_stop_timer(s);
700                 }
701                 return SUB_STATE_FINISHED;
702 
703             case MSG_PROCESS_CONTINUE_PROCESSING:
704                 st->read_state = READ_STATE_POST_PROCESS;
705                 st->read_state_work = WORK_MORE_A;
706                 break;
707 
708             default:
709                 st->read_state = READ_STATE_HEADER;
710                 break;
711             }
712             break;
713 
714         case READ_STATE_POST_PROCESS:
715             st->read_state_work = post_process_message(s, st->read_state_work);
716             switch (st->read_state_work) {
717             case WORK_ERROR:
718                 check_fatal(s);
719                 /* Fall through */
720             case WORK_MORE_A:
721             case WORK_MORE_B:
722             case WORK_MORE_C:
723                 return SUB_STATE_ERROR;
724 
725             case WORK_FINISHED_CONTINUE:
726                 st->read_state = READ_STATE_HEADER;
727                 break;
728 
729             case WORK_FINISHED_STOP:
730                 if (SSL_CONNECTION_IS_DTLS(s)) {
731                     dtls1_stop_timer(s);
732                 }
733                 return SUB_STATE_FINISHED;
734             }
735             break;
736 
737         default:
738             /* Shouldn't happen */
739             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
740             return SUB_STATE_ERROR;
741         }
742     }
743 }
744 
745 /*
746  * Send a previously constructed message to the peer.
747  */
statem_do_write(SSL_CONNECTION * s)748 static int statem_do_write(SSL_CONNECTION *s)
749 {
750     OSSL_STATEM *st = &s->statem;
751 
752     if (st->hand_state == TLS_ST_CW_CHANGE
753         || st->hand_state == TLS_ST_SW_CHANGE) {
754         if (SSL_CONNECTION_IS_DTLS(s))
755             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
756         else
757             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
758     } else {
759         return ssl_do_write(s);
760     }
761 }
762 
763 /*
764  * Initialise the MSG_FLOW_WRITING sub-state machine
765  */
init_write_state_machine(SSL_CONNECTION * s)766 static void init_write_state_machine(SSL_CONNECTION *s)
767 {
768     OSSL_STATEM *st = &s->statem;
769 
770     st->write_state = WRITE_STATE_TRANSITION;
771 }
772 
773 /*
774  * This function implements the sub-state machine when the message flow is in
775  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
776  *
777  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
778  * |             |
779  * |             v
780  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
781  * |             |
782  * |             v
783  * |       WRITE_STATE_SEND
784  * |             |
785  * |             v
786  * |     WRITE_STATE_POST_WORK
787  * |             |
788  * +-------------+
789  *
790  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
791 
792  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
793  * sending of the message. This could result in an NBIO event occurring in
794  * which case control returns to the calling application. When this function
795  * is recalled we will resume in the same state where we left off.
796  *
797  * WRITE_STATE_SEND sends the message and performs any work to be done after
798  * sending.
799  *
800  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
801  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
802  * result in an NBIO event.
803  */
write_state_machine(SSL_CONNECTION * s)804 static SUB_STATE_RETURN write_state_machine(SSL_CONNECTION *s)
805 {
806     OSSL_STATEM *st = &s->statem;
807     int ret;
808     WRITE_TRAN(*transition) (SSL_CONNECTION *s);
809     WORK_STATE(*pre_work) (SSL_CONNECTION *s, WORK_STATE wst);
810     WORK_STATE(*post_work) (SSL_CONNECTION *s, WORK_STATE wst);
811     int (*get_construct_message_f) (SSL_CONNECTION *s,
812                                     CON_FUNC_RETURN (**confunc) (SSL_CONNECTION *s,
813                                                                  WPACKET *pkt),
814                                     int *mt);
815     void (*cb) (const SSL *ssl, int type, int val) = NULL;
816     CON_FUNC_RETURN (*confunc) (SSL_CONNECTION *s, WPACKET *pkt);
817     int mt;
818     WPACKET pkt;
819     SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
820 
821     cb = get_callback(s);
822 
823     if (s->server) {
824         transition = ossl_statem_server_write_transition;
825         pre_work = ossl_statem_server_pre_work;
826         post_work = ossl_statem_server_post_work;
827         get_construct_message_f = ossl_statem_server_construct_message;
828     } else {
829         transition = ossl_statem_client_write_transition;
830         pre_work = ossl_statem_client_pre_work;
831         post_work = ossl_statem_client_post_work;
832         get_construct_message_f = ossl_statem_client_construct_message;
833     }
834 
835     while (1) {
836         switch (st->write_state) {
837         case WRITE_STATE_TRANSITION:
838             if (cb != NULL) {
839                 /* Notify callback of an impending state change */
840                 if (s->server)
841                     cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
842                 else
843                     cb(ssl, SSL_CB_CONNECT_LOOP, 1);
844             }
845             switch (transition(s)) {
846             case WRITE_TRAN_CONTINUE:
847                 st->write_state = WRITE_STATE_PRE_WORK;
848                 st->write_state_work = WORK_MORE_A;
849                 break;
850 
851             case WRITE_TRAN_FINISHED:
852                 return SUB_STATE_FINISHED;
853                 break;
854 
855             case WRITE_TRAN_ERROR:
856                 check_fatal(s);
857                 return SUB_STATE_ERROR;
858             }
859             break;
860 
861         case WRITE_STATE_PRE_WORK:
862             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
863             case WORK_ERROR:
864                 check_fatal(s);
865                 /* Fall through */
866             case WORK_MORE_A:
867             case WORK_MORE_B:
868             case WORK_MORE_C:
869                 return SUB_STATE_ERROR;
870 
871             case WORK_FINISHED_CONTINUE:
872                 st->write_state = WRITE_STATE_SEND;
873                 break;
874 
875             case WORK_FINISHED_STOP:
876                 return SUB_STATE_END_HANDSHAKE;
877             }
878             if (!get_construct_message_f(s, &confunc, &mt)) {
879                 /* SSLfatal() already called */
880                 return SUB_STATE_ERROR;
881             }
882             if (mt == SSL3_MT_DUMMY) {
883                 /* Skip construction and sending. This isn't a "real" state */
884                 st->write_state = WRITE_STATE_POST_WORK;
885                 st->write_state_work = WORK_MORE_A;
886                 break;
887             }
888             if (!WPACKET_init(&pkt, s->init_buf)
889                     || !ssl_set_handshake_header(s, &pkt, mt)) {
890                 WPACKET_cleanup(&pkt);
891                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
892                 return SUB_STATE_ERROR;
893             }
894             if (confunc != NULL) {
895                 CON_FUNC_RETURN tmpret;
896 
897                 tmpret = confunc(s, &pkt);
898                 if (tmpret == CON_FUNC_ERROR) {
899                     WPACKET_cleanup(&pkt);
900                     check_fatal(s);
901                     return SUB_STATE_ERROR;
902                 } else if (tmpret == CON_FUNC_DONT_SEND) {
903                     /*
904                      * The construction function decided not to construct the
905                      * message after all and continue. Skip sending.
906                      */
907                     WPACKET_cleanup(&pkt);
908                     st->write_state = WRITE_STATE_POST_WORK;
909                     st->write_state_work = WORK_MORE_A;
910                     break;
911                 } /* else success */
912             }
913             if (!ssl_close_construct_packet(s, &pkt, mt)
914                     || !WPACKET_finish(&pkt)) {
915                 WPACKET_cleanup(&pkt);
916                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
917                 return SUB_STATE_ERROR;
918             }
919 
920             /* Fall through */
921 
922         case WRITE_STATE_SEND:
923             if (SSL_CONNECTION_IS_DTLS(s) && st->use_timer) {
924                 dtls1_start_timer(s);
925             }
926             ret = statem_do_write(s);
927             if (ret <= 0) {
928                 return SUB_STATE_ERROR;
929             }
930             st->write_state = WRITE_STATE_POST_WORK;
931             st->write_state_work = WORK_MORE_A;
932             /* Fall through */
933 
934         case WRITE_STATE_POST_WORK:
935             switch (st->write_state_work = post_work(s, st->write_state_work)) {
936             case WORK_ERROR:
937                 check_fatal(s);
938                 /* Fall through */
939             case WORK_MORE_A:
940             case WORK_MORE_B:
941             case WORK_MORE_C:
942                 return SUB_STATE_ERROR;
943 
944             case WORK_FINISHED_CONTINUE:
945                 st->write_state = WRITE_STATE_TRANSITION;
946                 break;
947 
948             case WORK_FINISHED_STOP:
949                 return SUB_STATE_END_HANDSHAKE;
950             }
951             break;
952 
953         default:
954             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
955             return SUB_STATE_ERROR;
956         }
957     }
958 }
959 
960 /*
961  * Flush the write BIO
962  */
statem_flush(SSL_CONNECTION * s)963 int statem_flush(SSL_CONNECTION *s)
964 {
965     s->rwstate = SSL_WRITING;
966     if (BIO_flush(s->wbio) <= 0) {
967         return 0;
968     }
969     s->rwstate = SSL_NOTHING;
970 
971     return 1;
972 }
973 
974 /*
975  * Called by the record layer to determine whether application data is
976  * allowed to be received in the current handshake state or not.
977  *
978  * Return values are:
979  *   1: Yes (application data allowed)
980  *   0: No (application data not allowed)
981  */
ossl_statem_app_data_allowed(SSL_CONNECTION * s)982 int ossl_statem_app_data_allowed(SSL_CONNECTION *s)
983 {
984     OSSL_STATEM *st = &s->statem;
985 
986     if (st->state == MSG_FLOW_UNINITED)
987         return 0;
988 
989     if (!s->s3.in_read_app_data || (s->s3.total_renegotiations == 0))
990         return 0;
991 
992     if (s->server) {
993         /*
994          * If we're a server and we haven't got as far as writing our
995          * ServerHello yet then we allow app data
996          */
997         if (st->hand_state == TLS_ST_BEFORE
998             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
999             return 1;
1000     } else {
1001         /*
1002          * If we're a client and we haven't read the ServerHello yet then we
1003          * allow app data
1004          */
1005         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
1006             return 1;
1007     }
1008 
1009     return 0;
1010 }
1011 
1012 /*
1013  * This function returns 1 if TLS exporter is ready to export keying
1014  * material, or 0 if otherwise.
1015  */
ossl_statem_export_allowed(SSL_CONNECTION * s)1016 int ossl_statem_export_allowed(SSL_CONNECTION *s)
1017 {
1018     return s->s3.previous_server_finished_len != 0
1019            && s->statem.hand_state != TLS_ST_SW_FINISHED;
1020 }
1021 
1022 /*
1023  * Return 1 if early TLS exporter is ready to export keying material,
1024  * or 0 if otherwise.
1025  */
ossl_statem_export_early_allowed(SSL_CONNECTION * s)1026 int ossl_statem_export_early_allowed(SSL_CONNECTION *s)
1027 {
1028     /*
1029      * The early exporter secret is only present on the server if we
1030      * have accepted early_data. It is present on the client as long
1031      * as we have sent early_data.
1032      */
1033     return s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
1034            || (!s->server && s->ext.early_data != SSL_EARLY_DATA_NOT_SENT);
1035 }
1036