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