Client TLS state machine rewrite cleanup
[openssl.git] / ssl / statem.c
1 /* ssl/statem.c */
2 /*
3  * Written by Matt Caswell for the OpenSSL project.
4  */
5 /* ====================================================================
6  * Copyright (c) 1998-2015 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
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
18  *    distribution.
19  *
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/)"
24  *
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.
29  *
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.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
38  *
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  * ====================================================================
52  *
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).
56  *
57  */
58
59 #include <openssl/rand.h>
60 #include "ssl_locl.h"
61
62 /*
63  * This file implements the SSL/TLS/DTLS state machines.
64  *
65  * There are two primary state machines:
66  *
67  * 1) Message flow state machine
68  * 2) Handshake state machine
69  *
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.
74  *
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.
78  *
79  * Overall it looks like this:
80  *
81  * ---------------------------------------------            -------------------
82  * |                                           |            |                 |
83  * | Message flow state machine                |            |                 |
84  * |                                           |            |                 |
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  * | -------------------- -------------------- |            |                 |
91  * |                                           |            |                 |
92  * ---------------------------------------------            -------------------
93  *
94  */
95
96 /* Sub state machine return values */
97 enum SUB_STATE_RETURN {
98     /* Something bad happened or NBIO */
99     SUB_STATE_ERROR,
100     /* Sub state finished go to the next sub state */
101     SUB_STATE_FINISHED,
102     /* Sub state finished and handshake was completed */
103     SUB_STATE_END_HANDSHAKE
104 };
105
106 static 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);
111 static inline int cert_req_allowed(SSL *s);
112 static inline int key_exchange_skip_allowed(SSL *s);
113 static int client_read_transition(SSL *s, int mt);
114 static enum WRITE_TRAN client_write_transition(SSL *s);
115 static enum WORK_STATE client_pre_work(SSL *s, enum WORK_STATE wst);
116 static enum WORK_STATE client_post_work(SSL *s, enum WORK_STATE wst);
117 static int client_construct_message(SSL *s);
118 static unsigned long client_max_message_size(SSL *s);
119 static enum MSG_PROCESS_RETURN client_process_message(SSL *s,
120                                                       unsigned long len);
121 static enum WORK_STATE client_post_process_message(SSL *s, enum WORK_STATE wst);
122
123 /*
124  * Clear the state machine state and reset back to MSG_FLOW_UNINITED
125  */
126 void statem_clear(SSL *s)
127 {
128     s->statem.state = MSG_FLOW_UNINITED;
129 }
130
131 /*
132  * Set the state machine up ready for a renegotiation handshake
133  */
134 void statem_set_renegotiate(SSL *s)
135 {
136     s->statem.state = MSG_FLOW_RENEGOTIATE;
137 }
138
139 /*
140  * Put the state machine into an error state. This is a permanent error for
141  * the current connection.
142  */
143 void statem_set_error(SSL *s)
144 {
145     s->statem.state = MSG_FLOW_ERROR;
146     /* TODO: This is temporary - remove me */
147     s->state = SSL_ST_ERR;
148 }
149
150 int ssl3_connect(SSL *s) {
151     return state_machine(s, 0);
152 }
153
154 /*
155  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
156  * MSG_FLOW_RENEGOTIATE state and finish in MSG_FLOW_FINISHED. Valid states and
157  * transitions are as follows:
158  *
159  * MSG_FLOW_UNINITED     MSG_FLOW_RENEGOTIATE
160  *        |                       |
161  *        +-----------------------+
162  *        v
163  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
164  *        |
165  *        V
166  * MSG_FLOW_FINISHED
167  *        |
168  *        V
169  *    [SUCCESS]
170  *
171  * We may exit at any point due to an error or NBIO event. If an NBIO event
172  * occurs then we restart at the point we left off when we are recalled.
173  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
174  *
175  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
176  * into that state at any point in the event that an irrecoverable error occurs.
177  *
178  * Valid return values are:
179  *   1: Success
180  * <=0: NBIO or error
181  */
182 static int state_machine(SSL *s, int server) {
183     BUF_MEM *buf = NULL;
184     unsigned long Time = (unsigned long)time(NULL);
185     void (*cb) (const SSL *ssl, int type, int val) = NULL;
186     STATEM *st = &s->statem;
187     int ret = -1;
188     int ssret;
189
190     if (st->state == MSG_FLOW_ERROR) {
191         /* Shouldn't have been called if we're already in the error state */
192         return -1;
193     }
194
195     RAND_add(&Time, sizeof(Time), 0);
196     ERR_clear_error();
197     clear_sys_error();
198
199     if (s->info_callback != NULL)
200         cb = s->info_callback;
201     else if (s->ctx->info_callback != NULL)
202         cb = s->ctx->info_callback;
203
204     s->in_handshake++;
205     if (!SSL_in_init(s) || SSL_in_before(s)) {
206         if (!SSL_clear(s))
207             return -1;
208     }
209
210 #ifndef OPENSSL_NO_HEARTBEATS
211     /*
212      * If we're awaiting a HeartbeatResponse, pretend we already got and
213      * don't await it anymore, because Heartbeats don't make sense during
214      * handshakes anyway.
215      */
216     if (s->tlsext_hb_pending) {
217         if (SSL_IS_DTLS(s))
218             dtls1_stop_timer(s);
219         s->tlsext_hb_pending = 0;
220         s->tlsext_hb_seq++;
221     }
222 #endif
223
224     /* Initialise state machine */
225
226     if (st->state == MSG_FLOW_RENEGOTIATE) {
227         s->renegotiate = 1;
228         if (!server)
229             s->ctx->stats.sess_connect_renegotiate++;
230     }
231
232     if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE) {
233         /* TODO: Temporary - fix this */
234         if (server)
235             s->state = SSL_ST_ACCEPT;
236         else
237             s->state = SSL_ST_CONNECT;
238
239         if (st->state == MSG_FLOW_UNINITED) {
240             st->hand_state = TLS_ST_BEFORE;
241         }
242
243         s->server = server;
244         if (cb != NULL)
245             cb(s, SSL_CB_HANDSHAKE_START, 1);
246
247         if (SSL_IS_DTLS(s)) {
248             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
249                     (server
250                     || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
251                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
252                 goto end;
253             }
254         } else {
255             if ((s->version >> 8) != SSL3_VERSION_MAJOR
256                     && s->version != TLS_ANY_VERSION) {
257                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
258                 goto end;
259             }
260         }
261
262         if (s->version != TLS_ANY_VERSION &&
263                 !ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
264             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
265             goto end;
266         }
267
268         if (server)
269             s->type = SSL_ST_ACCEPT;
270         else
271             s->type = SSL_ST_CONNECT;
272
273         if (s->init_buf == NULL) {
274             if ((buf = BUF_MEM_new()) == NULL) {
275                 goto end;
276             }
277             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
278                 goto end;
279             }
280             s->init_buf = buf;
281             buf = NULL;
282         }
283
284         if (!ssl3_setup_buffers(s)) {
285             goto end;
286         }
287         s->init_num = 0;
288
289         /*
290          * Should have been reset by tls_process_finished, too.
291          */
292         s->s3->change_cipher_spec = 0;
293
294         if (!server || st->state != MSG_FLOW_RENEGOTIATE) {
295                 /*
296                  * Ok, we now need to push on a buffering BIO ...but not with
297                  * SCTP
298                  */
299 #ifndef OPENSSL_NO_SCTP
300                 if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
301 #endif
302                     if (!ssl_init_wbio_buffer(s, server ? 1 : 0)) {
303                         goto end;
304                     }
305
306             ssl3_init_finished_mac(s);
307         }
308
309         if (server) {
310             if (st->state != MSG_FLOW_RENEGOTIATE) {
311                 s->ctx->stats.sess_accept++;
312             } else if (!s->s3->send_connection_binding &&
313                        !(s->options &
314                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
315                 /*
316                  * Server attempting to renegotiate with client that doesn't
317                  * support secure renegotiation.
318                  */
319                 SSLerr(SSL_F_STATE_MACHINE,
320                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
321                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
322                 statem_set_error(s);
323                 goto end;
324             } else {
325                 /*
326                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
327                  * HelloRequest
328                  */
329                 s->ctx->stats.sess_accept_renegotiate++;
330             }
331         } else {
332             s->ctx->stats.sess_connect++;
333
334             /* mark client_random uninitialized */
335             memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
336             s->hit = 0;
337
338             s->s3->tmp.cert_request = 0;
339
340             if (SSL_IS_DTLS(s)) {
341                 st->use_timer = 1;
342             }
343         }
344
345         st->state = MSG_FLOW_WRITING;
346         init_write_state_machine(s);
347         st->read_state_first_init = 1;
348     }
349
350     while(st->state != MSG_FLOW_FINISHED) {
351         if(st->state == MSG_FLOW_READING) {
352             ssret = read_state_machine(s);
353             if (ssret == SUB_STATE_FINISHED) {
354                 st->state = MSG_FLOW_WRITING;
355                 init_write_state_machine(s);
356             } else {
357                 /* NBIO or error */
358                 goto end;
359             }
360         } else if (st->state == MSG_FLOW_WRITING) {
361             ssret = write_state_machine(s);
362             if (ssret == SUB_STATE_FINISHED) {
363                 st->state = MSG_FLOW_READING;
364                 init_read_state_machine(s);
365             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
366                 st->state = MSG_FLOW_FINISHED;
367             } else {
368                 /* NBIO or error */
369                 goto end;
370             }
371         } else {
372             /* Error */
373             statem_set_error(s);
374             goto end;
375         }
376     }
377
378     st->state = MSG_FLOW_UNINITED;
379     ret = 1;
380
381  end:
382     s->in_handshake--;
383     BUF_MEM_free(buf);
384     if (cb != NULL) {
385         if (server)
386             cb(s, SSL_CB_ACCEPT_EXIT, ret);
387         else
388             cb(s, SSL_CB_CONNECT_EXIT, ret);
389     }
390     return ret;
391 }
392
393 /*
394  * Initialise the MSG_FLOW_READING sub-state machine
395  */
396 static void init_read_state_machine(SSL *s)
397 {
398     STATEM *st = &s->statem;
399
400     st->read_state = READ_STATE_HEADER;
401 }
402
403 /*
404  * This function implements the sub-state machine when the message flow is in
405  * MSG_FLOW_READING. The valid sub-states and transitions are:
406  *
407  * READ_STATE_HEADER <--+<-------------+
408  *        |             |              |
409  *        v             |              |
410  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
411  *        |                            |
412  *        +----------------------------+
413  *        v
414  * [SUB_STATE_FINISHED]
415  *
416  * READ_STATE_HEADER has the responsibility for reading in the message header
417  * and transitioning the state of the handshake state machine.
418  *
419  * READ_STATE_BODY reads in the rest of the message and then subsequently
420  * processes it.
421  *
422  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
423  * processing activity performed on the message may block.
424  *
425  * Any of the above states could result in an NBIO event occuring in which case
426  * control returns to the calling application. When this function is recalled we
427  * will resume in the same state where we left off.
428  */
429 static enum SUB_STATE_RETURN read_state_machine(SSL *s) {
430     STATEM *st = &s->statem;
431     int ret, mt;
432     unsigned long len;
433     int (*transition)(SSL *s, int mt);
434     enum MSG_PROCESS_RETURN (*process_message)(SSL *s, unsigned long n);
435     enum WORK_STATE (*post_process_message)(SSL *s, enum WORK_STATE wst);
436     unsigned long (*max_message_size)(SSL *s);
437     void (*cb) (const SSL *ssl, int type, int val) = NULL;
438
439     if (s->info_callback != NULL)
440         cb = s->info_callback;
441     else if (s->ctx->info_callback != NULL)
442         cb = s->ctx->info_callback;
443
444     if(s->server) {
445         /* TODO: Fill these in later when we've implemented them */
446         transition = NULL;
447         process_message = NULL;
448         post_process_message = NULL;
449         max_message_size = NULL;
450     } else {
451         transition = client_read_transition;
452         process_message = client_process_message;
453         max_message_size = client_max_message_size;
454         post_process_message = client_post_process_message;
455     }
456
457     if (st->read_state_first_init) {
458         s->first_packet = 1;
459         st->read_state_first_init = 0;
460     }
461
462     while(1) {
463         switch(st->read_state) {
464         case READ_STATE_HEADER:
465             s->init_num = 0;
466             /* Get the state the peer wants to move to */
467             ret = tls_get_message_header(s, &mt);
468
469             if (ret == 0) {
470                 /* Could be non-blocking IO */
471                 return SUB_STATE_ERROR;
472             }
473
474             if (cb != NULL) {
475                 /* Notify callback of an impending state change */
476                 if (s->server)
477                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
478                 else
479                     cb(s, SSL_CB_CONNECT_LOOP, 1);
480             }
481             /*
482              * Validate that we are allowed to move to the new state and move
483              * to that state if so
484              */
485             if(!transition(s, mt)) {
486                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
487                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_UNEXPECTED_MESSAGE);
488                 return SUB_STATE_ERROR;
489             }
490
491             if (s->s3->tmp.message_size > max_message_size(s)) {
492                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
493                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
494                 return SUB_STATE_ERROR;
495             }
496
497             st->read_state = READ_STATE_BODY;
498             /* Fall through */
499
500         case READ_STATE_BODY:
501             if (!SSL_IS_DTLS(s)) {
502                 /* We already got this above for DTLS */
503                 ret = tls_get_message_body(s, &len);
504                 if (ret == 0) {
505                     /* Could be non-blocking IO */
506                     return SUB_STATE_ERROR;
507                 }
508             }
509
510             s->first_packet = 0;
511             ret = process_message(s, len);
512             if (ret == MSG_PROCESS_ERROR) {
513                 return SUB_STATE_ERROR;
514             }
515
516             if (ret == MSG_PROCESS_FINISHED_READING) {
517                 if (SSL_IS_DTLS(s)) {
518                     dtls1_stop_timer(s);
519                 }
520                 return SUB_STATE_FINISHED;
521             }
522
523             if (ret == MSG_PROCESS_CONTINUE_PROCESSING) {
524                 st->read_state = READ_STATE_POST_PROCESS;
525                 st->read_state_work = WORK_MORE_A;
526             } else {
527                 st->read_state = READ_STATE_HEADER;
528             }
529             break;
530
531         case READ_STATE_POST_PROCESS:
532             st->read_state_work = post_process_message(s, st->read_state_work);
533             switch(st->read_state_work) {
534             default:
535                 return SUB_STATE_ERROR;
536
537             case WORK_FINISHED_CONTINUE:
538                 st->read_state = READ_STATE_HEADER;
539                 break;
540
541             case WORK_FINISHED_STOP:
542                 if (SSL_IS_DTLS(s)) {
543                     dtls1_stop_timer(s);
544                 }
545                 return SUB_STATE_FINISHED;
546             }
547             break;
548
549         default:
550             /* Shouldn't happen */
551             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
552             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
553             statem_set_error(s);
554             return SUB_STATE_ERROR;
555         }
556     }
557 }
558
559 /*
560  * Send a previously constructed message to the peer.
561  */
562 static int statem_do_write(SSL *s)
563 {
564     STATEM *st = &s->statem;
565
566     if (st->hand_state == TLS_ST_CW_CHANGE
567             || st->hand_state == TLS_ST_SW_CHANGE) {
568         if (SSL_IS_DTLS(s))
569             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
570         else
571             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
572     } else {
573         return ssl_do_write(s);
574     }
575 }
576
577 /*
578  * Initialise the MSG_FLOW_WRITING sub-state machine
579  */
580 static void init_write_state_machine(SSL *s)
581 {
582     STATEM *st = &s->statem;
583
584     st->write_state = WRITE_STATE_TRANSITION;
585 }
586
587 /*
588  * This function implements the sub-state machine when the message flow is in
589  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
590  *
591  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
592  * |             |
593  * |             v
594  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
595  * |             |
596  * |             v
597  * |       WRITE_STATE_SEND
598  * |             |
599  * |             v
600  * |     WRITE_STATE_POST_WORK
601  * |             |
602  * +-------------+
603  *
604  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
605
606  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
607  * sending of the message. This could result in an NBIO event occuring in
608  * which case control returns to the calling application. When this function
609  * is recalled we will resume in the same state where we left off.
610  *
611  * WRITE_STATE_SEND sends the message and performs any work to be done after
612  * sending.
613  *
614  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
615  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
616  * result in an NBIO event.
617  */
618 static enum SUB_STATE_RETURN write_state_machine(SSL *s)
619 {
620     STATEM *st = &s->statem;
621     int ret;
622     enum WRITE_TRAN (*transition)(SSL *s);
623     enum WORK_STATE (*pre_work)(SSL *s, enum WORK_STATE wst);
624     enum WORK_STATE (*post_work)(SSL *s, enum WORK_STATE wst);
625     int (*construct_message)(SSL *s);
626     void (*cb) (const SSL *ssl, int type, int val) = NULL;
627
628     if (s->info_callback != NULL)
629         cb = s->info_callback;
630     else if (s->ctx->info_callback != NULL)
631         cb = s->ctx->info_callback;
632
633     if(s->server) {
634         /* TODO: Fill these in later when we've implemented them */
635         transition = NULL;
636         pre_work = NULL;
637         post_work = NULL;
638         construct_message = NULL;
639     } else {
640         transition = client_write_transition;
641         pre_work = client_pre_work;
642         post_work = client_post_work;
643         construct_message = client_construct_message;
644     }
645
646     while(1) {
647         switch(st->write_state) {
648         case WRITE_STATE_TRANSITION:
649             if (cb != NULL) {
650                 /* Notify callback of an impending state change */
651                 if (s->server)
652                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
653                 else
654                     cb(s, SSL_CB_CONNECT_LOOP, 1);
655             }
656             switch(transition(s)) {
657             case WRITE_TRAN_CONTINUE:
658                 st->write_state = WRITE_STATE_PRE_WORK;
659                 st->write_state_work = WORK_MORE_A;
660                 break;
661
662             case WRITE_TRAN_FINISHED:
663                 return SUB_STATE_FINISHED;
664                 break;
665
666             default:
667                 return SUB_STATE_ERROR;
668             }
669             break;
670
671         case WRITE_STATE_PRE_WORK:
672             switch(st->write_state_work = pre_work(s, st->write_state_work)) {
673             default:
674                 return SUB_STATE_ERROR;
675
676             case WORK_FINISHED_CONTINUE:
677                 st->write_state = WRITE_STATE_SEND;
678                 break;
679
680             case WORK_FINISHED_STOP:
681                 return SUB_STATE_END_HANDSHAKE;
682             }
683             if(construct_message(s) == 0)
684                 return SUB_STATE_ERROR;
685
686             /* Fall through */
687
688         case WRITE_STATE_SEND:
689             if (SSL_IS_DTLS(s) && st->use_timer) {
690                 dtls1_start_timer(s);
691             }
692             ret = statem_do_write(s);
693             if (ret <= 0) {
694                 return SUB_STATE_ERROR;
695             }
696             st->write_state = WRITE_STATE_POST_WORK;
697             st->write_state_work = WORK_MORE_A;
698             /* Fall through */
699
700         case WRITE_STATE_POST_WORK:
701             switch(st->write_state_work = post_work(s, st->write_state_work)) {
702             default:
703                 return SUB_STATE_ERROR;
704
705             case WORK_FINISHED_CONTINUE:
706                 st->write_state = WRITE_STATE_TRANSITION;
707                 break;
708
709             case WORK_FINISHED_STOP:
710                 return SUB_STATE_END_HANDSHAKE;
711             }
712             break;
713
714         default:
715             return SUB_STATE_ERROR;
716         }
717     }
718 }
719
720 /*
721  * Flush the write BIO
722  */
723 static int statem_flush(SSL *s)
724 {
725     s->rwstate = SSL_WRITING;
726     if (BIO_flush(s->wbio) <= 0) {
727         return 0;
728     }
729     s->rwstate = SSL_NOTHING;
730
731     return 1;
732 }
733
734 /*
735  * Called by the record layer to determine whether application data is
736  * allowed to be sent in the current handshake state or not.
737  *
738  * Return values are:
739  *   1: Yes (application data allowed)
740  *   0: No (application data not allowed)
741  */
742 int statem_app_data_allowed(SSL *s)
743 {
744     STATEM *st = &s->statem;
745
746     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
747         return 0;
748
749     if (!s->server) {
750         if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE)
751             return 0;
752
753         if(st->hand_state == TLS_ST_CW_CLNT_HELLO)
754             return 1;
755
756         return 0;
757     }
758
759     /*
760      * This is the old check for code still using the old state machine. This
761      * will be removed by later commits
762      */
763     if (((s->state & SSL_ST_CONNECT) && SSL_IS_DTLS(s) &&
764           (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
765           (s->state <= SSL3_ST_CR_SRVR_HELLO_A)) ||
766          ((s->state & SSL_ST_ACCEPT) &&
767                (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
768                (s->state >= SSL3_ST_SR_CLNT_HELLO_A))
769         )
770         return 1;
771
772     return 0;
773 }
774
775
776 #ifndef OPENSSL_NO_SCTP
777 /*
778  * Set flag used by SCTP to determine whether we are in the read sock state
779  */
780 void statem_set_sctp_read_sock(SSL *s, int read_sock)
781 {
782     s->statem.in_sctp_read_sock = read_sock;
783 }
784
785 /*
786  * Called by the record layer to determine whether we are in the read sock
787  * state or not.
788  *
789  * Return values are:
790  *   1: Yes (we are in the read sock state)
791  *   0: No (we are not in the read sock state)
792  */
793 int statem_in_sctp_read_sock(SSL *s)
794 {
795     return s->statem.in_sctp_read_sock;
796 }
797 #endif
798
799 /*
800  * Is a CertificateRequest message allowed at the moment or not?
801  *
802  *  Return values are:
803  *  1: Yes
804  *  0: No
805  */
806 static inline int cert_req_allowed(SSL *s)
807 {
808     /* TLS does not like anon-DH with client cert */
809     if (s->version > SSL3_VERSION
810             && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL))
811         return 0;
812
813     return 1;
814 }
815
816 /*
817  * Are we allowed to skip the ServerKeyExchange message?
818  *
819  *  Return values are:
820  *  1: Yes
821  *  0: No
822  */
823 static inline int key_exchange_skip_allowed(SSL *s)
824 {
825     long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
826
827     /*
828      * Can't skip server key exchange if this is an ephemeral
829      * ciphersuite.
830      */
831     if (alg_k & (SSL_kDHE | SSL_kECDHE)) {
832         return 0;
833     }
834
835     return 1;
836 }
837
838 /*
839  * client_read_transition() encapsulates the logic for the allowed handshake
840  * state transitions when the client is reading messages from the server. The
841  * message type that the server has sent is provided in |mt|. The current state
842  * is in |s->statem.hand_state|.
843  *
844  *  Return values are:
845  *  1: Success (transition allowed)
846  *  0: Error (transition not allowed)
847  */
848 static int client_read_transition(SSL *s, int mt)
849 {
850     STATEM *st = &s->statem;
851
852     switch(st->hand_state) {
853     case TLS_ST_CW_CLNT_HELLO:
854         if (mt == SSL3_MT_SERVER_HELLO) {
855             st->hand_state = TLS_ST_CR_SRVR_HELLO;
856             return 1;
857         }
858
859         if (SSL_IS_DTLS(s)) {
860             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
861                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
862                 return 1;
863             }
864         }
865         break;
866
867     case TLS_ST_CR_SRVR_HELLO:
868         if (s->hit) {
869             if (s->tlsext_ticket_expected) {
870                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
871                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
872                     return 1;
873                 }
874             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
875                 st->hand_state = TLS_ST_CR_CHANGE;
876                 return 1;
877             }
878         } else {
879             if (!(s->s3->tmp.new_cipher->algorithm_auth
880                         & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
881                 if (mt == SSL3_MT_CERTIFICATE) {
882                     st->hand_state = TLS_ST_CR_CERT;
883                     return 1;
884                 }
885             } else {
886                 if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
887                     st->hand_state = TLS_ST_CR_KEY_EXCH;
888                     return 1;
889                 } else if (key_exchange_skip_allowed(s)) {
890                     if (mt == SSL3_MT_CERTIFICATE_REQUEST
891                             && cert_req_allowed(s)) {
892                         st->hand_state = TLS_ST_CR_CERT_REQ;
893                         return 1;
894                     } else if (mt == SSL3_MT_SERVER_DONE) {
895                         st->hand_state = TLS_ST_CR_SRVR_DONE;
896                         return 1;
897                     }
898                 }
899             }
900         }
901         break;
902
903     case TLS_ST_CR_CERT:
904         if (s->tlsext_status_expected) {
905             if (mt == SSL3_MT_CERTIFICATE_STATUS) {
906                 st->hand_state = TLS_ST_CR_CERT_STATUS;
907                 return 1;
908             }
909         } else {
910             if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
911                 st->hand_state = TLS_ST_CR_KEY_EXCH;
912                 return 1;
913             } else if (key_exchange_skip_allowed(s)) {
914                 if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
915                     st->hand_state = TLS_ST_CR_CERT_REQ;
916                     return 1;
917                 } else if (mt == SSL3_MT_SERVER_DONE) {
918                     st->hand_state = TLS_ST_CR_SRVR_DONE;
919                     return 1;
920                 }
921             }
922         }
923         break;
924
925     case TLS_ST_CR_CERT_STATUS:
926         if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
927             st->hand_state = TLS_ST_CR_KEY_EXCH;
928             return 1;
929         } else if (key_exchange_skip_allowed(s)) {
930             if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
931                 st->hand_state = TLS_ST_CR_CERT_REQ;
932                 return 1;
933             } else if (mt == SSL3_MT_SERVER_DONE) {
934                 st->hand_state = TLS_ST_CR_SRVR_DONE;
935                 return 1;
936             }
937         }
938         break;
939
940     case TLS_ST_CR_KEY_EXCH:
941         if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
942             st->hand_state = TLS_ST_CR_CERT_REQ;
943             return 1;
944         } else if (mt == SSL3_MT_SERVER_DONE) {
945             st->hand_state = TLS_ST_CR_SRVR_DONE;
946             return 1;
947         }
948         break;
949
950     case TLS_ST_CR_CERT_REQ:
951         if (mt == SSL3_MT_SERVER_DONE) {
952             st->hand_state = TLS_ST_CR_SRVR_DONE;
953             return 1;
954         }
955         break;
956
957     case TLS_ST_CW_FINISHED:
958         if (mt == SSL3_MT_NEWSESSION_TICKET && s->tlsext_ticket_expected) {
959             st->hand_state = TLS_ST_CR_SESSION_TICKET;
960             return 1;
961         } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
962             st->hand_state = TLS_ST_CR_CHANGE;
963             return 1;
964         }
965         break;
966
967     case TLS_ST_CR_SESSION_TICKET:
968         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
969             st->hand_state = TLS_ST_CR_CHANGE;
970             return 1;
971         }
972         break;
973
974     case TLS_ST_CR_CHANGE:
975         if (mt == SSL3_MT_FINISHED) {
976             st->hand_state = TLS_ST_CR_FINISHED;
977             return 1;
978         }
979         break;
980
981     default:
982         break;
983     }
984
985     /* No valid transition found */
986     return 0;
987 }
988
989 /*
990  * client_write_transition() works out what handshake state to move to next
991  * when the client is writing messages to be sent to the server.
992  */
993 static enum WRITE_TRAN client_write_transition(SSL *s)
994 {
995     STATEM *st = &s->statem;
996
997     switch(st->hand_state) {
998         case TLS_ST_OK:
999             /* Renegotiation - fall through */
1000         case TLS_ST_BEFORE:
1001             st->hand_state = TLS_ST_CW_CLNT_HELLO;
1002             return WRITE_TRAN_CONTINUE;
1003
1004         case TLS_ST_CW_CLNT_HELLO:
1005             /*
1006              * No transition at the end of writing because we don't know what
1007              * we will be sent
1008              */
1009             return WRITE_TRAN_FINISHED;
1010
1011         case TLS_ST_CR_SRVR_DONE:
1012             if (s->s3->tmp.cert_req)
1013                 st->hand_state = TLS_ST_CW_CERT;
1014             else
1015                 st->hand_state = TLS_ST_CW_KEY_EXCH;
1016             return WRITE_TRAN_CONTINUE;
1017
1018         case TLS_ST_CW_CERT:
1019             st->hand_state = TLS_ST_CW_KEY_EXCH;
1020             return WRITE_TRAN_CONTINUE;
1021
1022         case TLS_ST_CW_KEY_EXCH:
1023             /*
1024              * For TLS, cert_req is set to 2, so a cert chain of nothing is
1025              * sent, but no verify packet is sent
1026              */
1027             /*
1028              * XXX: For now, we do not support client authentication in ECDH
1029              * cipher suites with ECDH (rather than ECDSA) certificates. We
1030              * need to skip the certificate verify message when client's
1031              * ECDH public key is sent inside the client certificate.
1032              */
1033             if (s->s3->tmp.cert_req == 1) {
1034                 st->hand_state = TLS_ST_CW_CERT_VRFY;
1035             } else {
1036                 st->hand_state = TLS_ST_CW_CHANGE;
1037             }
1038             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
1039                 st->hand_state = TLS_ST_CW_CHANGE;
1040             }
1041             return WRITE_TRAN_CONTINUE;
1042
1043         case TLS_ST_CW_CERT_VRFY:
1044             st->hand_state = TLS_ST_CW_CHANGE;
1045             return WRITE_TRAN_CONTINUE;
1046
1047         case TLS_ST_CW_CHANGE:
1048 #if defined(OPENSSL_NO_NEXTPROTONEG)
1049             st->hand_state = TLS_ST_CW_FINISHED;
1050 #else
1051             if (s->s3->next_proto_neg_seen)
1052                 st->hand_state = TLS_ST_CW_NEXT_PROTO;
1053             else
1054                 st->hand_state = TLS_ST_CW_FINISHED;
1055 #endif
1056             return WRITE_TRAN_CONTINUE;
1057
1058 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1059         case TLS_ST_CW_NEXT_PROTO:
1060             st->hand_state = TLS_ST_CW_FINISHED;
1061             return WRITE_TRAN_CONTINUE;
1062 #endif
1063
1064         case TLS_ST_CW_FINISHED:
1065             if (s->hit) {
1066                 st->hand_state = TLS_ST_OK;
1067                 /* TODO: This needs removing */
1068                 s->state = SSL_ST_OK;
1069                 return WRITE_TRAN_CONTINUE;
1070             } else {
1071                 return WRITE_TRAN_FINISHED;
1072             }
1073
1074         case TLS_ST_CR_FINISHED:
1075             if (s->hit) {
1076                 st->hand_state = TLS_ST_CW_CHANGE;
1077                 return WRITE_TRAN_CONTINUE;
1078             } else {
1079                 st->hand_state = TLS_ST_OK;
1080                 /* TODO: This needs removing */
1081                 s->state = SSL_ST_OK;
1082                 return WRITE_TRAN_CONTINUE;
1083             }
1084
1085         default:
1086             /* Shouldn't happen */
1087             return WRITE_TRAN_ERROR;
1088     }
1089 }
1090
1091 /*
1092  * Perform any pre work that needs to be done prior to sending a message from
1093  * the client to the server.
1094  */
1095 static enum WORK_STATE client_pre_work(SSL *s, enum WORK_STATE wst)
1096 {
1097     STATEM *st = &s->statem;
1098
1099     switch(st->hand_state) {
1100     case TLS_ST_CW_CLNT_HELLO:
1101         s->shutdown = 0;
1102         break;
1103
1104     case TLS_ST_CW_CERT:
1105         return tls_prepare_client_certificate(s, wst);
1106
1107     case TLS_ST_OK:
1108         return tls_finish_handshake(s, wst);
1109
1110     default:
1111         /* No pre work to be done */
1112         break;
1113     }
1114
1115     return WORK_FINISHED_CONTINUE;
1116 }
1117
1118 /*
1119  * Perform any work that needs to be done after sending a message from the
1120  * client to the server.
1121  */
1122 static enum WORK_STATE client_post_work(SSL *s, enum WORK_STATE wst)
1123 {
1124     STATEM *st = &s->statem;
1125
1126     s->init_num = 0;
1127
1128     switch(st->hand_state) {
1129     case TLS_ST_CW_CLNT_HELLO:
1130         /* turn on buffering for the next lot of output */
1131         if (s->bbio != s->wbio)
1132             s->wbio = BIO_push(s->bbio, s->wbio);
1133         break;
1134
1135     case TLS_ST_CW_KEY_EXCH:
1136         if (tls_client_key_exchange_post_work(s) == 0)
1137             return WORK_ERROR;
1138         break;
1139
1140     case TLS_ST_CW_CHANGE:
1141         s->session->cipher = s->s3->tmp.new_cipher;
1142 #ifdef OPENSSL_NO_COMP
1143         s->session->compress_meth = 0;
1144 #else
1145         if (s->s3->tmp.new_compression == NULL)
1146             s->session->compress_meth = 0;
1147         else
1148             s->session->compress_meth = s->s3->tmp.new_compression->id;
1149 #endif
1150         if (!s->method->ssl3_enc->setup_key_block(s))
1151             return WORK_ERROR;
1152
1153         if (!s->method->ssl3_enc->change_cipher_state(s,
1154                                                       SSL3_CHANGE_CIPHER_CLIENT_WRITE))
1155             return WORK_ERROR;
1156
1157         if (SSL_IS_DTLS(s)) {
1158 #ifndef OPENSSL_NO_SCTP
1159             if (s->hit) {
1160                 /*
1161                  * Change to new shared key of SCTP-Auth, will be ignored if
1162                  * no SCTP used.
1163                  */
1164                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1165                          0, NULL);
1166             }
1167 #endif
1168
1169             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
1170         }
1171         break;
1172
1173     case TLS_ST_CW_FINISHED:
1174 #ifndef OPENSSL_NO_SCTP
1175         if (SSL_IS_DTLS(s) && s->hit == 0) {
1176             /*
1177              * Change to new shared key of SCTP-Auth, will be ignored if
1178              * no SCTP used.
1179              */
1180             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1181                      0, NULL);
1182         }
1183 #endif
1184         if (statem_flush(s) != 1)
1185             return WORK_MORE_B;
1186
1187         if (s->hit && tls_finish_handshake(s, WORK_MORE_A) != 1)
1188                 return WORK_ERROR;
1189         break;
1190
1191     default:
1192         /* No post work to be done */
1193         break;
1194     }
1195
1196     return WORK_FINISHED_CONTINUE;
1197 }
1198
1199 /*
1200  * Construct a message to be sent from the client to the server.
1201  *
1202  * Valid return values are:
1203  *   1: Success
1204  *   0: Error
1205  */
1206 static int client_construct_message(SSL *s)
1207 {
1208     STATEM *st = &s->statem;
1209
1210     switch(st->hand_state) {
1211     case TLS_ST_CW_CLNT_HELLO:
1212         return tls_construct_client_hello(s);
1213
1214     case TLS_ST_CW_CERT:
1215         return tls_construct_client_certificate(s);
1216
1217     case TLS_ST_CW_KEY_EXCH:
1218         return tls_construct_client_key_exchange(s);
1219
1220     case TLS_ST_CW_CERT_VRFY:
1221         return tls_construct_client_verify(s);
1222
1223     case TLS_ST_CW_CHANGE:
1224         return tls_construct_change_cipher_spec(s);
1225
1226 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1227     case TLS_ST_CW_NEXT_PROTO:
1228         return tls_construct_next_proto(s);
1229 #endif
1230     case TLS_ST_CW_FINISHED:
1231         return tls_construct_finished(s,
1232                                       s->method->
1233                                       ssl3_enc->client_finished_label,
1234                                       s->method->
1235                                       ssl3_enc->client_finished_label_len);
1236
1237     default:
1238         /* Shouldn't happen */
1239         break;
1240     }
1241
1242     return 0;
1243 }
1244
1245 /* The spec allows for a longer length than this, but we limit it */
1246 #define SERVER_HELLO_MAX_LENGTH         20000
1247 #define SERVER_KEY_EXCH_MAX_LENGTH      102400
1248 #define SERVER_HELLO_DONE_MAX_LENGTH    0
1249 #define CCS_MAX_LENGTH                  1
1250 /* Max should actually be 36 but we are generous */
1251 #define FINISHED_MAX_LENGTH             64
1252
1253 /*
1254  * Returns the maximum allowed length for the current message that we are
1255  * reading. Excludes the message header.
1256  */
1257 static unsigned long client_max_message_size(SSL *s)
1258 {
1259     STATEM *st = &s->statem;
1260
1261     switch(st->hand_state) {
1262         case TLS_ST_CR_SRVR_HELLO:
1263             return SERVER_HELLO_MAX_LENGTH;
1264
1265         case TLS_ST_CR_CERT:
1266             return s->max_cert_list;
1267
1268         case TLS_ST_CR_CERT_STATUS:
1269             return SSL3_RT_MAX_PLAIN_LENGTH;
1270
1271         case TLS_ST_CR_KEY_EXCH:
1272             return SERVER_KEY_EXCH_MAX_LENGTH;
1273
1274         case TLS_ST_CR_CERT_REQ:
1275             return SSL3_RT_MAX_PLAIN_LENGTH;
1276
1277         case TLS_ST_CR_SRVR_DONE:
1278             return SERVER_HELLO_DONE_MAX_LENGTH;
1279
1280         case TLS_ST_CR_CHANGE:
1281             return CCS_MAX_LENGTH;
1282
1283         case TLS_ST_CR_SESSION_TICKET:
1284             return SSL3_RT_MAX_PLAIN_LENGTH;
1285
1286         case TLS_ST_CR_FINISHED:
1287             return FINISHED_MAX_LENGTH;
1288
1289         default:
1290             /* Shouldn't happen */
1291             break;
1292     }
1293
1294     return 0;
1295 }
1296
1297 /*
1298  * Process a message that the client has been received from the server.
1299  */
1300 static enum MSG_PROCESS_RETURN client_process_message(SSL *s, unsigned long len)
1301 {
1302     STATEM *st = &s->statem;
1303
1304     switch(st->hand_state) {
1305         case TLS_ST_CR_SRVR_HELLO:
1306             return tls_process_server_hello(s, len);
1307
1308         case TLS_ST_CR_CERT:
1309             return tls_process_server_certificate(s, len);
1310
1311         case TLS_ST_CR_CERT_STATUS:
1312             return tls_process_cert_status(s, len);
1313
1314         case TLS_ST_CR_KEY_EXCH:
1315             return tls_process_key_exchange(s, len);
1316
1317         case TLS_ST_CR_CERT_REQ:
1318             return tls_process_certificate_request(s, len);
1319
1320         case TLS_ST_CR_SRVR_DONE:
1321             return tls_process_server_done(s, len);
1322
1323         case TLS_ST_CR_CHANGE:
1324             return tls_process_change_cipher_spec(s, len);
1325
1326         case TLS_ST_CR_SESSION_TICKET:
1327             return tls_process_new_session_ticket(s, len);
1328
1329         case TLS_ST_CR_FINISHED:
1330             return tls_process_finished(s, len);
1331
1332         default:
1333             /* Shouldn't happen */
1334             break;
1335     }
1336
1337     return MSG_PROCESS_ERROR;
1338 }
1339
1340 /*
1341  * Perform any further processing required following the receipt of a message
1342  * from the server
1343  */
1344 static enum WORK_STATE client_post_process_message(SSL *s, enum WORK_STATE wst)
1345 {
1346     STATEM *st = &s->statem;
1347
1348     switch(st->hand_state) {
1349 #ifndef OPENSSL_NO_SCTP
1350     case TLS_ST_CR_SRVR_DONE:
1351         /* We only get here if we are using SCTP and we are renegotiating */
1352         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1353             s->s3->in_read_app_data = 2;
1354             s->rwstate = SSL_READING;
1355             BIO_clear_retry_flags(SSL_get_rbio(s));
1356             BIO_set_retry_read(SSL_get_rbio(s));
1357             statem_set_sctp_read_sock(s, 1);
1358             return WORK_MORE_A;
1359         }
1360         statem_set_sctp_read_sock(s, 0);
1361         return WORK_FINISHED_STOP;
1362 #endif
1363
1364     case TLS_ST_CR_FINISHED:
1365         if (!s->hit)
1366             return tls_finish_handshake(s, wst);
1367         else
1368             return WORK_FINISHED_STOP;
1369     default:
1370         break;
1371     }
1372
1373     /* Shouldn't happen */
1374     return WORK_ERROR;
1375 }