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