c9ac4fb571831485ee4680b37e7c0f14573dac91
[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 (s->statem.hand_state != TLS_ST_BEFORE
124             && s->statem.hand_state != TLS_ST_CW_CLNT_HELLO) {
125         /*
126          * We only send an alert if we've got as far as actually sending or
127          * receiving a message.
128          */
129         ssl3_send_alert(s, SSL3_AL_FATAL, al);
130     }
131 }
132
133 /*
134  * Discover whether the current connection is in the error state.
135  *
136  * Valid return values are:
137  *   1: Yes
138  *   0: No
139  */
140 int ossl_statem_in_error(const SSL *s)
141 {
142     if (s->statem.state == MSG_FLOW_ERROR)
143         return 1;
144
145     return 0;
146 }
147
148 void ossl_statem_set_in_init(SSL *s, int init)
149 {
150     s->statem.in_init = init;
151 }
152
153 int ossl_statem_get_in_handshake(SSL *s)
154 {
155     return s->statem.in_handshake;
156 }
157
158 void ossl_statem_set_in_handshake(SSL *s, int inhand)
159 {
160     if (inhand)
161         s->statem.in_handshake++;
162     else
163         s->statem.in_handshake--;
164 }
165
166 /* Are we in a sensible state to skip over unreadable early data? */
167 int ossl_statem_skip_early_data(SSL *s)
168 {
169     if (s->ext.early_data != SSL_EARLY_DATA_REJECTED)
170         return 0;
171
172     if (!s->server || s->statem.hand_state != TLS_ST_EARLY_DATA)
173         return 0;
174
175     return 1;
176 }
177
178 /*
179  * Called when we are in SSL_read*(), SSL_write*(), or SSL_accept()
180  * /SSL_connect()/SSL_do_handshake(). Used to test whether we are in an early
181  * data state and whether we should attempt to move the handshake on if so.
182  * |sending| is 1 if we are attempting to send data (SSL_write*()), 0 if we are
183  * attempting to read data (SSL_read*()), or -1 if we are in SSL_do_handshake()
184  * or similar.
185  */
186 void ossl_statem_check_finish_init(SSL *s, int sending)
187 {
188     if (sending == -1) {
189         if (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
190                 || s->statem.hand_state == TLS_ST_EARLY_DATA) {
191             ossl_statem_set_in_init(s, 1);
192             if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY) {
193                 /*
194                  * SSL_connect() or SSL_do_handshake() has been called directly.
195                  * We don't allow any more writing of early data.
196                  */
197                 s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
198             }
199         }
200     } else if (!s->server) {
201         if ((sending && (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
202                       || s->statem.hand_state == TLS_ST_EARLY_DATA)
203                   && s->early_data_state != SSL_EARLY_DATA_WRITING)
204                 || (!sending && s->statem.hand_state == TLS_ST_EARLY_DATA)) {
205             ossl_statem_set_in_init(s, 1);
206             /*
207              * SSL_write() has been called directly. We don't allow any more
208              * writing of early data.
209              */
210             if (sending && s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY)
211                 s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
212         }
213     } else {
214         if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING
215                 && s->statem.hand_state == TLS_ST_EARLY_DATA)
216             ossl_statem_set_in_init(s, 1);
217     }
218 }
219
220 void ossl_statem_set_hello_verify_done(SSL *s)
221 {
222     s->statem.state = MSG_FLOW_UNINITED;
223     s->statem.in_init = 1;
224     /*
225      * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
226      * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
227      * calls to SSL_in_before() will return false. Also calls to
228      * SSL_state_string() and SSL_state_string_long() will return something
229      * sensible.
230      */
231     s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
232 }
233
234 int ossl_statem_connect(SSL *s)
235 {
236     return state_machine(s, 0);
237 }
238
239 int ossl_statem_accept(SSL *s)
240 {
241     return state_machine(s, 1);
242 }
243
244 typedef void (*info_cb) (const SSL *, int, int);
245
246 static info_cb get_callback(SSL *s)
247 {
248     if (s->info_callback != NULL)
249         return s->info_callback;
250     else if (s->ctx->info_callback != NULL)
251         return s->ctx->info_callback;
252
253     return NULL;
254 }
255
256 /*
257  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
258  * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
259  * transitions are as follows:
260  *
261  * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
262  *        |                       |
263  *        +-----------------------+
264  *        v
265  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
266  *        |
267  *        V
268  * MSG_FLOW_FINISHED
269  *        |
270  *        V
271  *    [SUCCESS]
272  *
273  * We may exit at any point due to an error or NBIO event. If an NBIO event
274  * occurs then we restart at the point we left off when we are recalled.
275  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
276  *
277  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
278  * into that state at any point in the event that an irrecoverable error occurs.
279  *
280  * Valid return values are:
281  *   1: Success
282  * <=0: NBIO or error
283  */
284 static int state_machine(SSL *s, int server)
285 {
286     BUF_MEM *buf = NULL;
287     void (*cb) (const SSL *ssl, int type, int val) = NULL;
288     OSSL_STATEM *st = &s->statem;
289     int ret = -1;
290     int ssret;
291
292     if (st->state == MSG_FLOW_ERROR) {
293         /* Shouldn't have been called if we're already in the error state */
294         return -1;
295     }
296
297     ERR_clear_error();
298     clear_sys_error();
299
300     cb = get_callback(s);
301
302     st->in_handshake++;
303     if (!SSL_in_init(s) || SSL_in_before(s)) {
304         if (!SSL_clear(s))
305             return -1;
306     }
307 #ifndef OPENSSL_NO_SCTP
308     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
309         /*
310          * Notify SCTP BIO socket to enter handshake mode and prevent stream
311          * identifier other than 0.
312          */
313         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
314                  st->in_handshake, NULL);
315     }
316 #endif
317
318     /* Initialise state machine */
319     if (st->state == MSG_FLOW_UNINITED
320             || st->state == MSG_FLOW_FINISHED) {
321         if (st->state == MSG_FLOW_UNINITED) {
322             st->hand_state = TLS_ST_BEFORE;
323             st->request_state = TLS_ST_BEFORE;
324         }
325
326         s->server = server;
327         if (cb != NULL)
328             cb(s, SSL_CB_HANDSHAKE_START, 1);
329
330         if (SSL_IS_DTLS(s)) {
331             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
332                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
333                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
334                 goto end;
335             }
336         } else {
337             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
338                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
339                 goto end;
340             }
341         }
342
343         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
344             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
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                 ossl_statem_set_error(s);
561                 return SUB_STATE_ERROR;
562             }
563
564             if (s->s3->tmp.message_size > max_message_size(s)) {
565                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
566                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
567                 return SUB_STATE_ERROR;
568             }
569
570             /* dtls_get_message already did this */
571             if (!SSL_IS_DTLS(s)
572                     && s->s3->tmp.message_size > 0
573                     && !grow_init_buf(s, s->s3->tmp.message_size
574                                          + SSL3_HM_HEADER_LENGTH)) {
575                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
576                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_BUF_LIB);
577                 return SUB_STATE_ERROR;
578             }
579
580             st->read_state = READ_STATE_BODY;
581             /* Fall through */
582
583         case READ_STATE_BODY:
584             if (!SSL_IS_DTLS(s)) {
585                 /* We already got this above for DTLS */
586                 ret = tls_get_message_body(s, &len);
587                 if (ret == 0) {
588                     /* Could be non-blocking IO */
589                     return SUB_STATE_ERROR;
590                 }
591             }
592
593             s->first_packet = 0;
594             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
595                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
596                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
597                 return SUB_STATE_ERROR;
598             }
599             ret = process_message(s, &pkt);
600
601             /* Discard the packet data */
602             s->init_num = 0;
603
604             switch (ret) {
605             case MSG_PROCESS_ERROR:
606                 return SUB_STATE_ERROR;
607
608             case MSG_PROCESS_FINISHED_READING:
609                 if (SSL_IS_DTLS(s)) {
610                     dtls1_stop_timer(s);
611                 }
612                 return SUB_STATE_FINISHED;
613
614             case MSG_PROCESS_CONTINUE_PROCESSING:
615                 st->read_state = READ_STATE_POST_PROCESS;
616                 st->read_state_work = WORK_MORE_A;
617                 break;
618
619             default:
620                 st->read_state = READ_STATE_HEADER;
621                 break;
622             }
623             break;
624
625         case READ_STATE_POST_PROCESS:
626             st->read_state_work = post_process_message(s, st->read_state_work);
627             switch (st->read_state_work) {
628             case WORK_ERROR:
629             case WORK_MORE_A:
630             case WORK_MORE_B:
631             case WORK_MORE_C:
632                 return SUB_STATE_ERROR;
633
634             case WORK_FINISHED_CONTINUE:
635                 st->read_state = READ_STATE_HEADER;
636                 break;
637
638             case WORK_FINISHED_STOP:
639                 if (SSL_IS_DTLS(s)) {
640                     dtls1_stop_timer(s);
641                 }
642                 return SUB_STATE_FINISHED;
643             }
644             break;
645
646         default:
647             /* Shouldn't happen */
648             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
649             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
650             ossl_statem_set_error(s);
651             return SUB_STATE_ERROR;
652         }
653     }
654 }
655
656 /*
657  * Send a previously constructed message to the peer.
658  */
659 static int statem_do_write(SSL *s)
660 {
661     OSSL_STATEM *st = &s->statem;
662
663     if (st->hand_state == TLS_ST_CW_CHANGE
664         || st->hand_state == TLS_ST_SW_CHANGE) {
665         if (SSL_IS_DTLS(s))
666             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
667         else
668             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
669     } else {
670         return ssl_do_write(s);
671     }
672 }
673
674 /*
675  * Initialise the MSG_FLOW_WRITING sub-state machine
676  */
677 static void init_write_state_machine(SSL *s)
678 {
679     OSSL_STATEM *st = &s->statem;
680
681     st->write_state = WRITE_STATE_TRANSITION;
682 }
683
684 /*
685  * This function implements the sub-state machine when the message flow is in
686  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
687  *
688  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
689  * |             |
690  * |             v
691  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
692  * |             |
693  * |             v
694  * |       WRITE_STATE_SEND
695  * |             |
696  * |             v
697  * |     WRITE_STATE_POST_WORK
698  * |             |
699  * +-------------+
700  *
701  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
702
703  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
704  * sending of the message. This could result in an NBIO event occurring in
705  * which case control returns to the calling application. When this function
706  * is recalled we will resume in the same state where we left off.
707  *
708  * WRITE_STATE_SEND sends the message and performs any work to be done after
709  * sending.
710  *
711  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
712  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
713  * result in an NBIO event.
714  */
715 static SUB_STATE_RETURN write_state_machine(SSL *s)
716 {
717     OSSL_STATEM *st = &s->statem;
718     int ret;
719     WRITE_TRAN(*transition) (SSL *s);
720     WORK_STATE(*pre_work) (SSL *s, WORK_STATE wst);
721     WORK_STATE(*post_work) (SSL *s, WORK_STATE wst);
722     int (*get_construct_message_f) (SSL *s, WPACKET *pkt,
723                                     int (**confunc) (SSL *s, WPACKET *pkt),
724                                     int *mt);
725     void (*cb) (const SSL *ssl, int type, int val) = NULL;
726     int (*confunc) (SSL *s, WPACKET *pkt);
727     int mt;
728     WPACKET pkt;
729
730     cb = get_callback(s);
731
732     if (s->server) {
733         transition = ossl_statem_server_write_transition;
734         pre_work = ossl_statem_server_pre_work;
735         post_work = ossl_statem_server_post_work;
736         get_construct_message_f = ossl_statem_server_construct_message;
737     } else {
738         transition = ossl_statem_client_write_transition;
739         pre_work = ossl_statem_client_pre_work;
740         post_work = ossl_statem_client_post_work;
741         get_construct_message_f = ossl_statem_client_construct_message;
742     }
743
744     while (1) {
745         switch (st->write_state) {
746         case WRITE_STATE_TRANSITION:
747             if (cb != NULL) {
748                 /* Notify callback of an impending state change */
749                 if (s->server)
750                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
751                 else
752                     cb(s, SSL_CB_CONNECT_LOOP, 1);
753             }
754             switch (transition(s)) {
755             case WRITE_TRAN_CONTINUE:
756                 st->write_state = WRITE_STATE_PRE_WORK;
757                 st->write_state_work = WORK_MORE_A;
758                 break;
759
760             case WRITE_TRAN_FINISHED:
761                 return SUB_STATE_FINISHED;
762                 break;
763
764             case WRITE_TRAN_ERROR:
765                 return SUB_STATE_ERROR;
766             }
767             break;
768
769         case WRITE_STATE_PRE_WORK:
770             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
771             case WORK_ERROR:
772             case WORK_MORE_A:
773             case WORK_MORE_B:
774             case WORK_MORE_C:
775                 return SUB_STATE_ERROR;
776
777             case WORK_FINISHED_CONTINUE:
778                 st->write_state = WRITE_STATE_SEND;
779                 break;
780
781             case WORK_FINISHED_STOP:
782                 return SUB_STATE_END_HANDSHAKE;
783             }
784             if (!get_construct_message_f(s, &pkt, &confunc, &mt)) {
785                 ossl_statem_set_error(s);
786                 return SUB_STATE_ERROR;
787             }
788             if (mt == SSL3_MT_DUMMY) {
789                 /* Skip construction and sending. This isn't a "real" state */
790                 st->write_state = WRITE_STATE_POST_WORK;
791                 st->write_state_work = WORK_MORE_A;
792                 break;
793             }
794             if (!WPACKET_init(&pkt, s->init_buf)
795                     || !ssl_set_handshake_header(s, &pkt, mt)
796                     || (confunc != NULL && !confunc(s, &pkt))
797                     || !ssl_close_construct_packet(s, &pkt, mt)
798                     || !WPACKET_finish(&pkt)) {
799                 WPACKET_cleanup(&pkt);
800                 ossl_statem_set_error(s);
801                 return SUB_STATE_ERROR;
802             }
803
804             /* Fall through */
805
806         case WRITE_STATE_SEND:
807             if (SSL_IS_DTLS(s) && st->use_timer) {
808                 dtls1_start_timer(s);
809             }
810             ret = statem_do_write(s);
811             if (ret <= 0) {
812                 return SUB_STATE_ERROR;
813             }
814             st->write_state = WRITE_STATE_POST_WORK;
815             st->write_state_work = WORK_MORE_A;
816             /* Fall through */
817
818         case WRITE_STATE_POST_WORK:
819             switch (st->write_state_work = post_work(s, st->write_state_work)) {
820             case WORK_ERROR:
821             case WORK_MORE_A:
822             case WORK_MORE_B:
823             case WORK_MORE_C:
824                 return SUB_STATE_ERROR;
825
826             case WORK_FINISHED_CONTINUE:
827                 st->write_state = WRITE_STATE_TRANSITION;
828                 break;
829
830             case WORK_FINISHED_STOP:
831                 return SUB_STATE_END_HANDSHAKE;
832             }
833             break;
834
835         default:
836             return SUB_STATE_ERROR;
837         }
838     }
839 }
840
841 /*
842  * Flush the write BIO
843  */
844 int statem_flush(SSL *s)
845 {
846     s->rwstate = SSL_WRITING;
847     if (BIO_flush(s->wbio) <= 0) {
848         return 0;
849     }
850     s->rwstate = SSL_NOTHING;
851
852     return 1;
853 }
854
855 /*
856  * Called by the record layer to determine whether application data is
857  * allowed to be received in the current handshake state or not.
858  *
859  * Return values are:
860  *   1: Yes (application data allowed)
861  *   0: No (application data not allowed)
862  */
863 int ossl_statem_app_data_allowed(SSL *s)
864 {
865     OSSL_STATEM *st = &s->statem;
866
867     if (st->state == MSG_FLOW_UNINITED)
868         return 0;
869
870     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
871         return 0;
872
873     if (s->server) {
874         /*
875          * If we're a server and we haven't got as far as writing our
876          * ServerHello yet then we allow app data
877          */
878         if (st->hand_state == TLS_ST_BEFORE
879             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
880             return 1;
881     } else {
882         /*
883          * If we're a client and we haven't read the ServerHello yet then we
884          * allow app data
885          */
886         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
887             return 1;
888     }
889
890     return 0;
891 }