3 * Written by Matt Caswell for the OpenSSL project.
5 /* ====================================================================
6 * Copyright (c) 1998-2015 The OpenSSL Project. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * openssl-core@openssl.org.
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
34 * 6. Redistributions of any form whatsoever must retain the following
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
59 #include <openssl/rand.h>
63 * This file implements the SSL/TLS/DTLS state machines.
65 * There are two primary state machines:
67 * 1) Message flow state machine
68 * 2) Handshake state machine
70 * The Message flow state machine controls the reading and sending of messages
71 * including handling of non-blocking IO events, flushing of the underlying
72 * write BIO, handling unexpected messages, etc. It is itself broken into two
73 * separate sub-state machines which control reading and writing respectively.
75 * The Handshake state machine keeps track of the current SSL/TLS handshake
76 * state. Transitions of the handshake state are the result of events that
77 * occur within the Message flow state machine.
79 * Overall it looks like this:
81 * --------------------------------------------- -------------------
83 * | Message flow state machine | | |
85 * | -------------------- -------------------- | Transition | Handshake state |
86 * | | MSG_FLOW_READING | | MSG_FLOW_WRITING | | Event | machine |
87 * | | sub-state | | sub-state | |----------->| |
88 * | | machine for | | machine for | | | |
89 * | | reading messages | | writing messages | | | |
90 * | -------------------- -------------------- | | |
92 * --------------------------------------------- -------------------
96 /* Sub state machine return values */
97 enum SUB_STATE_RETURN {
98 /* Something bad happened or NBIO */
100 /* Sub state finished go to the next sub state */
102 /* Sub state finished and handshake was completed */
103 SUB_STATE_END_HANDSHAKE
106 int state_machine(SSL *s, int server);
107 static void init_read_state_machine(SSL *s);
108 static enum SUB_STATE_RETURN read_state_machine(SSL *s);
109 static void init_write_state_machine(SSL *s);
110 static enum SUB_STATE_RETURN write_state_machine(SSL *s);
113 * Clear the state machine state and reset back to MSG_FLOW_UNINITED
115 void statem_clear(SSL *s)
117 s->statem.state = MSG_FLOW_UNINITED;
121 * Set the state machine up ready for a renegotiation handshake
123 void statem_set_renegotiate(SSL *s)
125 s->statem.state = MSG_FLOW_RENEGOTIATE;
129 * Put the state machine into an error state. This is a permanent error for
130 * the current connection.
132 void statem_set_error(SSL *s)
134 s->statem.state = MSG_FLOW_ERROR;
135 /* TODO: This is temporary - remove me */
136 s->state = SSL_ST_ERR;
140 * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
141 * MSG_FLOW_RENEGOTIATE state and finish in MSG_FLOW_FINISHED. Valid states and
142 * transitions are as follows:
144 * MSG_FLOW_UNINITED MSG_FLOW_RENEGOTIATE
146 * +-----------------------+
148 * MSG_FLOW_WRITING <---> MSG_FLOW_READING
156 * We may exit at any point due to an error or NBIO event. If an NBIO event
157 * occurs then we restart at the point we left off when we are recalled.
158 * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
160 * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
161 * into that state at any point in the event that an irrecoverable error occurs.
163 * Valid return values are:
167 int state_machine(SSL *s, int server) {
169 unsigned long Time = (unsigned long)time(NULL);
170 void (*cb) (const SSL *ssl, int type, int val) = NULL;
171 STATEM *st = &s->statem;
175 if (st->state == MSG_FLOW_ERROR) {
176 /* Shouldn't have been called if we're already in the error state */
180 RAND_add(&Time, sizeof(Time), 0);
184 if (s->info_callback != NULL)
185 cb = s->info_callback;
186 else if (s->ctx->info_callback != NULL)
187 cb = s->ctx->info_callback;
190 if (!SSL_in_init(s) || SSL_in_before(s)) {
195 #ifndef OPENSSL_NO_HEARTBEATS
197 * If we're awaiting a HeartbeatResponse, pretend we already got and
198 * don't await it anymore, because Heartbeats don't make sense during
201 if (s->tlsext_hb_pending) {
204 s->tlsext_hb_pending = 0;
209 /* Initialise state machine */
211 if (st->state == MSG_FLOW_RENEGOTIATE) {
214 s->ctx->stats.sess_connect_renegotiate++;
217 if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE) {
218 /* TODO: Temporary - fix this */
220 s->state = SSL_ST_ACCEPT;
222 s->state = SSL_ST_CONNECT;
224 if (st->state == MSG_FLOW_UNINITED) {
225 st->hand_state = TLS_ST_BEFORE;
230 cb(s, SSL_CB_HANDSHAKE_START, 1);
232 if (SSL_IS_DTLS(s)) {
233 if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
235 || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
236 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
240 if ((s->version >> 8) != SSL3_VERSION_MAJOR
241 && s->version != TLS_ANY_VERSION) {
242 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
247 if (s->version != TLS_ANY_VERSION &&
248 !ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
249 SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
254 s->type = SSL_ST_ACCEPT;
256 s->type = SSL_ST_CONNECT;
258 if (s->init_buf == NULL) {
259 if ((buf = BUF_MEM_new()) == NULL) {
262 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
269 if (!ssl3_setup_buffers(s)) {
275 * Should have been reset by tls_process_finished, too.
277 s->s3->change_cipher_spec = 0;
279 if (!server || st->state != MSG_FLOW_RENEGOTIATE) {
281 * Ok, we now need to push on a buffering BIO ...but not with
284 #ifndef OPENSSL_NO_SCTP
285 if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
287 if (!ssl_init_wbio_buffer(s, server ? 1 : 0)) {
291 ssl3_init_finished_mac(s);
295 if (st->state != MSG_FLOW_RENEGOTIATE) {
296 s->ctx->stats.sess_accept++;
297 } else if (!s->s3->send_connection_binding &&
299 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
301 * Server attempting to renegotiate with client that doesn't
302 * support secure renegotiation.
304 SSLerr(SSL_F_STATE_MACHINE,
305 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
306 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
311 * s->state == SSL_ST_RENEGOTIATE, we will just send a
314 s->ctx->stats.sess_accept_renegotiate++;
317 s->ctx->stats.sess_connect++;
319 /* mark client_random uninitialized */
320 memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
323 s->s3->tmp.cert_request = 0;
325 if (SSL_IS_DTLS(s)) {
330 st->state = MSG_FLOW_WRITING;
331 init_write_state_machine(s);
332 st->read_state_first_init = 1;
335 while(st->state != MSG_FLOW_FINISHED) {
336 if(st->state == MSG_FLOW_READING) {
337 ssret = read_state_machine(s);
338 if (ssret == SUB_STATE_FINISHED) {
339 st->state = MSG_FLOW_WRITING;
340 init_write_state_machine(s);
345 } else if (st->state == MSG_FLOW_WRITING) {
346 ssret = write_state_machine(s);
347 if (ssret == SUB_STATE_FINISHED) {
348 st->state = MSG_FLOW_READING;
349 init_read_state_machine(s);
350 } else if (ssret == SUB_STATE_END_HANDSHAKE) {
351 st->state = MSG_FLOW_FINISHED;
363 st->state = MSG_FLOW_UNINITED;
371 cb(s, SSL_CB_ACCEPT_EXIT, ret);
373 cb(s, SSL_CB_CONNECT_EXIT, ret);
379 * Initialise the MSG_FLOW_READING sub-state machine
381 static void init_read_state_machine(SSL *s)
383 STATEM *st = &s->statem;
385 st->read_state = READ_STATE_HEADER;
389 * This function implements the sub-state machine when the message flow is in
390 * MSG_FLOW_READING. The valid sub-states and transitions are:
392 * READ_STATE_HEADER <--+<-------------+
395 * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
397 * +----------------------------+
399 * [SUB_STATE_FINISHED]
401 * READ_STATE_HEADER has the responsibility for reading in the message header
402 * and transitioning the state of the handshake state machine.
404 * READ_STATE_BODY reads in the rest of the message and then subsequently
407 * READ_STATE_POST_PROCESS is an optional step that may occur if some post
408 * processing activity performed on the message may block.
410 * Any of the above states could result in an NBIO event occuring in which case
411 * control returns to the calling application. When this function is recalled we
412 * will resume in the same state where we left off.
414 static enum SUB_STATE_RETURN read_state_machine(SSL *s) {
415 STATEM *st = &s->statem;
418 int (*transition)(SSL *s, int mt);
419 enum MSG_PROCESS_RETURN (*process_message)(SSL *s, unsigned long n);
420 enum WORK_STATE (*post_process_message)(SSL *s, enum WORK_STATE wst);
421 unsigned long (*max_message_size)(SSL *s);
422 void (*cb) (const SSL *ssl, int type, int val) = NULL;
424 if (s->info_callback != NULL)
425 cb = s->info_callback;
426 else if (s->ctx->info_callback != NULL)
427 cb = s->ctx->info_callback;
430 /* TODO: Fill these in later when we've implemented them */
432 process_message = NULL;
433 post_process_message = NULL;
434 max_message_size = NULL;
436 /* TODO: Fill these in later when we've implemented them */
438 process_message = NULL;
439 post_process_message = NULL;
440 max_message_size = NULL;
443 if (st->read_state_first_init) {
445 st->read_state_first_init = 0;
449 switch(st->read_state) {
450 case READ_STATE_HEADER:
452 /* Get the state the peer wants to move to */
453 ret = tls_get_message_header(s, &mt);
456 /* Could be non-blocking IO */
457 return SUB_STATE_ERROR;
461 /* Notify callback of an impending state change */
463 cb(s, SSL_CB_ACCEPT_LOOP, 1);
465 cb(s, SSL_CB_CONNECT_LOOP, 1);
468 * Validate that we are allowed to move to the new state and move
469 * to that state if so
471 if(!transition(s, mt)) {
472 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
473 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_UNEXPECTED_MESSAGE);
474 return SUB_STATE_ERROR;
477 if (s->s3->tmp.message_size > max_message_size(s)) {
478 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
479 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
480 return SUB_STATE_ERROR;
483 st->read_state = READ_STATE_BODY;
486 case READ_STATE_BODY:
487 if (!SSL_IS_DTLS(s)) {
488 /* We already got this above for DTLS */
489 ret = tls_get_message_body(s, &len);
491 /* Could be non-blocking IO */
492 return SUB_STATE_ERROR;
497 ret = process_message(s, len);
498 if (ret == MSG_PROCESS_ERROR) {
499 return SUB_STATE_ERROR;
502 if (ret == MSG_PROCESS_FINISHED_READING) {
503 if (SSL_IS_DTLS(s)) {
506 return SUB_STATE_FINISHED;
509 if (ret == MSG_PROCESS_CONTINUE_PROCESSING) {
510 st->read_state = READ_STATE_POST_PROCESS;
511 st->read_state_work = WORK_MORE_A;
513 st->read_state = READ_STATE_HEADER;
517 case READ_STATE_POST_PROCESS:
518 st->read_state_work = post_process_message(s, st->read_state_work);
519 switch(st->read_state_work) {
521 return SUB_STATE_ERROR;
523 case WORK_FINISHED_CONTINUE:
524 st->read_state = READ_STATE_HEADER;
527 case WORK_FINISHED_STOP:
528 if (SSL_IS_DTLS(s)) {
531 return SUB_STATE_FINISHED;
536 /* Shouldn't happen */
537 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
538 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
540 return SUB_STATE_ERROR;
546 * Send a previously constructed message to the peer.
548 static int statem_do_write(SSL *s)
550 STATEM *st = &s->statem;
552 if (st->hand_state == TLS_ST_CW_CHANGE
553 || st->hand_state == TLS_ST_SW_CHANGE) {
555 return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
557 return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
559 return ssl_do_write(s);
564 * Initialise the MSG_FLOW_WRITING sub-state machine
566 static void init_write_state_machine(SSL *s)
568 STATEM *st = &s->statem;
570 st->write_state = WRITE_STATE_TRANSITION;
574 * This function implements the sub-state machine when the message flow is in
575 * MSG_FLOW_WRITING. The valid sub-states and transitions are:
577 * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
580 * | WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
586 * | WRITE_STATE_POST_WORK
590 * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
592 * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
593 * sending of the message. This could result in an NBIO event occuring in
594 * which case control returns to the calling application. When this function
595 * is recalled we will resume in the same state where we left off.
597 * WRITE_STATE_SEND sends the message and performs any work to be done after
600 * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
601 * message has been completed. As for WRITE_STATE_PRE_WORK this could also
602 * result in an NBIO event.
604 static enum SUB_STATE_RETURN write_state_machine(SSL *s)
606 STATEM *st = &s->statem;
608 enum WRITE_TRAN (*transition)(SSL *s);
609 enum WORK_STATE (*pre_work)(SSL *s, enum WORK_STATE wst);
610 enum WORK_STATE (*post_work)(SSL *s, enum WORK_STATE wst);
611 int (*construct_message)(SSL *s);
612 void (*cb) (const SSL *ssl, int type, int val) = NULL;
614 if (s->info_callback != NULL)
615 cb = s->info_callback;
616 else if (s->ctx->info_callback != NULL)
617 cb = s->ctx->info_callback;
620 /* TODO: Fill these in later when we've implemented them */
624 construct_message = NULL;
626 /* TODO: Fill these in later when we've implemented them */
630 construct_message = NULL;
634 switch(st->write_state) {
635 case WRITE_STATE_TRANSITION:
637 /* Notify callback of an impending state change */
639 cb(s, SSL_CB_ACCEPT_LOOP, 1);
641 cb(s, SSL_CB_CONNECT_LOOP, 1);
643 switch(transition(s)) {
644 case WRITE_TRAN_CONTINUE:
645 st->write_state = WRITE_STATE_PRE_WORK;
646 st->write_state_work = WORK_MORE_A;
649 case WRITE_TRAN_FINISHED:
650 return SUB_STATE_FINISHED;
654 return SUB_STATE_ERROR;
658 case WRITE_STATE_PRE_WORK:
659 switch(st->write_state_work = pre_work(s, st->write_state_work)) {
661 return SUB_STATE_ERROR;
663 case WORK_FINISHED_CONTINUE:
664 st->write_state = WRITE_STATE_SEND;
667 case WORK_FINISHED_STOP:
668 return SUB_STATE_END_HANDSHAKE;
670 if(construct_message(s) == 0)
671 return SUB_STATE_ERROR;
675 case WRITE_STATE_SEND:
676 if (SSL_IS_DTLS(s) && st->use_timer) {
677 dtls1_start_timer(s);
679 ret = statem_do_write(s);
681 return SUB_STATE_ERROR;
683 st->write_state = WRITE_STATE_POST_WORK;
684 st->write_state_work = WORK_MORE_A;
687 case WRITE_STATE_POST_WORK:
688 switch(st->write_state_work = post_work(s, st->write_state_work)) {
690 return SUB_STATE_ERROR;
692 case WORK_FINISHED_CONTINUE:
693 st->write_state = WRITE_STATE_TRANSITION;
696 case WORK_FINISHED_STOP:
697 return SUB_STATE_END_HANDSHAKE;
702 return SUB_STATE_ERROR;
708 * Called by the record layer to determine whether application data is
709 * allowed to be sent in the current handshake state or not.
712 * 1: Yes (application data allowed)
713 * 0: No (application data not allowed)
715 int statem_client_app_data_allowed(SSL *s)
717 STATEM *st = &s->statem;
719 if(st->hand_state != TLS_ST_BEFORE &&
720 st->hand_state != TLS_ST_OK &&
721 st->hand_state != TLS_ST_CW_CLNT_HELLO)