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