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