Remove the type variable
[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 static int server_read_transition(SSL *s, int mt);
123 static inline int send_server_key_exchange(SSL *s);
124 static inline int send_certificate_request(SSL *s);
125 static enum WRITE_TRAN server_write_transition(SSL *s);
126 static enum WORK_STATE server_pre_work(SSL *s, enum WORK_STATE wst);
127 static enum WORK_STATE server_post_work(SSL *s, enum WORK_STATE wst);
128 static int server_construct_message(SSL *s);
129 static unsigned long server_max_message_size(SSL *s);
130 static enum MSG_PROCESS_RETURN server_process_message(SSL *s, unsigned long len);
131 static enum WORK_STATE server_post_process_message(SSL *s, enum WORK_STATE wst);
132
133
134 enum HANDSHAKE_STATE SSL_state(const SSL *ssl)
135 {
136     return ssl->statem.hand_state;
137 }
138
139 void SSL_set_state(SSL *ssl, enum HANDSHAKE_STATE state)
140 {
141     /*
142      * This function seems like a really bad idea. Should we remove it
143      * completely?
144      */
145     ssl->statem.hand_state = state;
146 }
147
148 int SSL_in_init(SSL *s)
149 {
150     return s->statem.in_init;
151 }
152
153 int SSL_is_init_finished(SSL *s)
154 {
155     return !(s->statem.in_init) && (s->statem.hand_state == TLS_ST_OK);
156 }
157
158 int SSL_in_before(SSL *s)
159 {
160     /*
161      * Historically being "in before" meant before anything had happened. In the
162      * current code though we remain in the "before" state for a while after we
163      * have started the handshake process (e.g. as a server waiting for the
164      * first message to arrive). There "in before" is taken to mean "in before"
165      * and not started any handshake process yet.
166      */
167     return (s->statem.hand_state == TLS_ST_BEFORE)
168         && (s->statem.state == MSG_FLOW_UNINITED);
169 }
170
171 /*
172  * Clear the state machine state and reset back to MSG_FLOW_UNINITED
173  */
174 void statem_clear(SSL *s)
175 {
176     s->statem.state = MSG_FLOW_UNINITED;
177     s->statem.hand_state = TLS_ST_BEFORE;
178     s->statem.in_init = 1;
179 }
180
181 /*
182  * Set the state machine up ready for a renegotiation handshake
183  */
184 void statem_set_renegotiate(SSL *s)
185 {
186     s->statem.state = MSG_FLOW_RENEGOTIATE;
187     s->statem.in_init = 1;
188 }
189
190 /*
191  * Put the state machine into an error state. This is a permanent error for
192  * the current connection.
193  */
194 void statem_set_error(SSL *s)
195 {
196     s->statem.state = MSG_FLOW_ERROR;
197 }
198
199 /*
200  * Discover whether the current connection is in the error state.
201  *
202  * Valid return values are:
203  *   1: Yes
204  *   0: No
205  */
206 int statem_in_error(const SSL *s)
207 {
208     if (s->statem.state == MSG_FLOW_ERROR)
209         return 1;
210
211     return 0;
212 }
213
214 void statem_set_in_init(SSL *s, int init)
215 {
216     s->statem.in_init = init;
217 }
218
219 int ssl3_connect(SSL *s) {
220     return state_machine(s, 0);
221 }
222
223 int dtls1_connect(SSL *s)
224 {
225     return state_machine(s, 0);
226 }
227
228 int ssl3_accept(SSL *s)
229 {
230     return state_machine(s, 1);
231 }
232
233 int dtls1_accept(SSL *s)
234 {
235     return state_machine(s, 1);
236 }
237
238 /*
239  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
240  * MSG_FLOW_RENEGOTIATE state and finish in MSG_FLOW_FINISHED. Valid states and
241  * transitions are as follows:
242  *
243  * MSG_FLOW_UNINITED     MSG_FLOW_RENEGOTIATE
244  *        |                       |
245  *        +-----------------------+
246  *        v
247  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
248  *        |
249  *        V
250  * MSG_FLOW_FINISHED
251  *        |
252  *        V
253  *    [SUCCESS]
254  *
255  * We may exit at any point due to an error or NBIO event. If an NBIO event
256  * occurs then we restart at the point we left off when we are recalled.
257  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
258  *
259  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
260  * into that state at any point in the event that an irrecoverable error occurs.
261  *
262  * Valid return values are:
263  *   1: Success
264  * <=0: NBIO or error
265  */
266 static int state_machine(SSL *s, int server) {
267     BUF_MEM *buf = NULL;
268     unsigned long Time = (unsigned long)time(NULL);
269     void (*cb) (const SSL *ssl, int type, int val) = NULL;
270     STATEM *st = &s->statem;
271     int ret = -1;
272     int ssret;
273
274     if (st->state == MSG_FLOW_ERROR) {
275         /* Shouldn't have been called if we're already in the error state */
276         return -1;
277     }
278
279     RAND_add(&Time, sizeof(Time), 0);
280     ERR_clear_error();
281     clear_sys_error();
282
283     if (s->info_callback != NULL)
284         cb = s->info_callback;
285     else if (s->ctx->info_callback != NULL)
286         cb = s->ctx->info_callback;
287
288     s->in_handshake++;
289     if (!SSL_in_init(s) || SSL_in_before(s)) {
290         if (!SSL_clear(s))
291             return -1;
292     }
293
294 #ifndef OPENSSL_NO_SCTP
295     if (SSL_IS_DTLS(s)) {
296         /*
297          * Notify SCTP BIO socket to enter handshake mode and prevent stream
298          * identifier other than 0. Will be ignored if no SCTP is used.
299          */
300         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
301                  s->in_handshake, NULL);
302     }
303 #endif
304
305 #ifndef OPENSSL_NO_HEARTBEATS
306     /*
307      * If we're awaiting a HeartbeatResponse, pretend we already got and
308      * don't await it anymore, because Heartbeats don't make sense during
309      * handshakes anyway.
310      */
311     if (s->tlsext_hb_pending) {
312         if (SSL_IS_DTLS(s))
313             dtls1_stop_timer(s);
314         s->tlsext_hb_pending = 0;
315         s->tlsext_hb_seq++;
316     }
317 #endif
318
319     /* Initialise state machine */
320
321     if (st->state == MSG_FLOW_RENEGOTIATE) {
322         s->renegotiate = 1;
323         if (!server)
324             s->ctx->stats.sess_connect_renegotiate++;
325     }
326
327     if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE) {
328         if (st->state == MSG_FLOW_UNINITED) {
329             st->hand_state = TLS_ST_BEFORE;
330         }
331
332         s->server = server;
333         if (cb != NULL)
334             cb(s, SSL_CB_HANDSHAKE_START, 1);
335
336         if (SSL_IS_DTLS(s)) {
337             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
338                     (server
339                     || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
340                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
341                 goto end;
342             }
343         } else {
344             if ((s->version >> 8) != SSL3_VERSION_MAJOR
345                     && s->version != TLS_ANY_VERSION) {
346                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
347                 goto end;
348             }
349         }
350
351         if (!SSL_IS_DTLS(s)) {
352             if (s->version != TLS_ANY_VERSION &&
353                     !ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
354                 SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
355                 goto end;
356             }
357         }
358
359         if (s->init_buf == NULL) {
360             if ((buf = BUF_MEM_new()) == NULL) {
361                 goto end;
362             }
363             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
364                 goto end;
365             }
366             s->init_buf = buf;
367             buf = NULL;
368         }
369
370         if (!ssl3_setup_buffers(s)) {
371             goto end;
372         }
373         s->init_num = 0;
374
375         /*
376          * Should have been reset by tls_process_finished, too.
377          */
378         s->s3->change_cipher_spec = 0;
379
380         if (!server || st->state != MSG_FLOW_RENEGOTIATE) {
381                 /*
382                  * Ok, we now need to push on a buffering BIO ...but not with
383                  * SCTP
384                  */
385 #ifndef OPENSSL_NO_SCTP
386                 if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
387 #endif
388                     if (!ssl_init_wbio_buffer(s, server ? 1 : 0)) {
389                         goto end;
390                     }
391
392             ssl3_init_finished_mac(s);
393         }
394
395         if (server) {
396             if (st->state != MSG_FLOW_RENEGOTIATE) {
397                 s->ctx->stats.sess_accept++;
398             } else if (!s->s3->send_connection_binding &&
399                        !(s->options &
400                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
401                 /*
402                  * Server attempting to renegotiate with client that doesn't
403                  * support secure renegotiation.
404                  */
405                 SSLerr(SSL_F_STATE_MACHINE,
406                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
407                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
408                 statem_set_error(s);
409                 goto end;
410             } else {
411                 /*
412                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
413                  * HelloRequest
414                  */
415                 s->ctx->stats.sess_accept_renegotiate++;
416             }
417         } else {
418             s->ctx->stats.sess_connect++;
419
420             /* mark client_random uninitialized */
421             memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
422             s->hit = 0;
423
424             s->s3->tmp.cert_request = 0;
425
426             if (SSL_IS_DTLS(s)) {
427                 st->use_timer = 1;
428             }
429         }
430
431         st->state = MSG_FLOW_WRITING;
432         init_write_state_machine(s);
433         st->read_state_first_init = 1;
434     }
435
436     while(st->state != MSG_FLOW_FINISHED) {
437         if(st->state == MSG_FLOW_READING) {
438             ssret = read_state_machine(s);
439             if (ssret == SUB_STATE_FINISHED) {
440                 st->state = MSG_FLOW_WRITING;
441                 init_write_state_machine(s);
442             } else {
443                 /* NBIO or error */
444                 goto end;
445             }
446         } else if (st->state == MSG_FLOW_WRITING) {
447             ssret = write_state_machine(s);
448             if (ssret == SUB_STATE_FINISHED) {
449                 st->state = MSG_FLOW_READING;
450                 init_read_state_machine(s);
451             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
452                 st->state = MSG_FLOW_FINISHED;
453             } else {
454                 /* NBIO or error */
455                 goto end;
456             }
457         } else {
458             /* Error */
459             statem_set_error(s);
460             goto end;
461         }
462     }
463
464     st->state = MSG_FLOW_UNINITED;
465     ret = 1;
466
467  end:
468     s->in_handshake--;
469
470 #ifndef OPENSSL_NO_SCTP
471     if (SSL_IS_DTLS(s)) {
472         /*
473          * Notify SCTP BIO socket to leave handshake mode and allow stream
474          * identifier other than 0. Will be ignored if no SCTP is used.
475          */
476         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
477                  s->in_handshake, NULL);
478     }
479 #endif
480
481     BUF_MEM_free(buf);
482     if (cb != NULL) {
483         if (server)
484             cb(s, SSL_CB_ACCEPT_EXIT, ret);
485         else
486             cb(s, SSL_CB_CONNECT_EXIT, ret);
487     }
488     return ret;
489 }
490
491 /*
492  * Initialise the MSG_FLOW_READING sub-state machine
493  */
494 static void init_read_state_machine(SSL *s)
495 {
496     STATEM *st = &s->statem;
497
498     st->read_state = READ_STATE_HEADER;
499 }
500
501 /*
502  * This function implements the sub-state machine when the message flow is in
503  * MSG_FLOW_READING. The valid sub-states and transitions are:
504  *
505  * READ_STATE_HEADER <--+<-------------+
506  *        |             |              |
507  *        v             |              |
508  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
509  *        |                            |
510  *        +----------------------------+
511  *        v
512  * [SUB_STATE_FINISHED]
513  *
514  * READ_STATE_HEADER has the responsibility for reading in the message header
515  * and transitioning the state of the handshake state machine.
516  *
517  * READ_STATE_BODY reads in the rest of the message and then subsequently
518  * processes it.
519  *
520  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
521  * processing activity performed on the message may block.
522  *
523  * Any of the above states could result in an NBIO event occuring in which case
524  * control returns to the calling application. When this function is recalled we
525  * will resume in the same state where we left off.
526  */
527 static enum SUB_STATE_RETURN read_state_machine(SSL *s) {
528     STATEM *st = &s->statem;
529     int ret, mt;
530     unsigned long len;
531     int (*transition)(SSL *s, int mt);
532     enum MSG_PROCESS_RETURN (*process_message)(SSL *s, unsigned long n);
533     enum WORK_STATE (*post_process_message)(SSL *s, enum WORK_STATE wst);
534     unsigned long (*max_message_size)(SSL *s);
535     void (*cb) (const SSL *ssl, int type, int val) = NULL;
536
537     if (s->info_callback != NULL)
538         cb = s->info_callback;
539     else if (s->ctx->info_callback != NULL)
540         cb = s->ctx->info_callback;
541
542     if(s->server) {
543         transition = server_read_transition;
544         process_message = server_process_message;
545         max_message_size = server_max_message_size;
546         post_process_message = server_post_process_message;
547     } else {
548         transition = client_read_transition;
549         process_message = client_process_message;
550         max_message_size = client_max_message_size;
551         post_process_message = client_post_process_message;
552     }
553
554     if (st->read_state_first_init) {
555         s->first_packet = 1;
556         st->read_state_first_init = 0;
557     }
558
559     while(1) {
560         switch(st->read_state) {
561         case READ_STATE_HEADER:
562             s->init_num = 0;
563             /* Get the state the peer wants to move to */
564             if (SSL_IS_DTLS(s)) {
565                 /*
566                  * In DTLS we get the whole message in one go - header and body
567                  */
568                 ret = dtls_get_message(s, &mt, &len);
569             } else {
570                 ret = tls_get_message_header(s, &mt);
571             }
572
573             if (ret == 0) {
574                 /* Could be non-blocking IO */
575                 return SUB_STATE_ERROR;
576             }
577
578             if (cb != NULL) {
579                 /* Notify callback of an impending state change */
580                 if (s->server)
581                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
582                 else
583                     cb(s, SSL_CB_CONNECT_LOOP, 1);
584             }
585             /*
586              * Validate that we are allowed to move to the new state and move
587              * to that state if so
588              */
589             if(!transition(s, mt)) {
590                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
591                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_UNEXPECTED_MESSAGE);
592                 return SUB_STATE_ERROR;
593             }
594
595             if (s->s3->tmp.message_size > max_message_size(s)) {
596                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
597                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
598                 return SUB_STATE_ERROR;
599             }
600
601             st->read_state = READ_STATE_BODY;
602             /* Fall through */
603
604         case READ_STATE_BODY:
605             if (!SSL_IS_DTLS(s)) {
606                 /* We already got this above for DTLS */
607                 ret = tls_get_message_body(s, &len);
608                 if (ret == 0) {
609                     /* Could be non-blocking IO */
610                     return SUB_STATE_ERROR;
611                 }
612             }
613
614             s->first_packet = 0;
615             ret = process_message(s, len);
616             if (ret == MSG_PROCESS_ERROR) {
617                 return SUB_STATE_ERROR;
618             }
619
620             if (ret == MSG_PROCESS_FINISHED_READING) {
621                 if (SSL_IS_DTLS(s)) {
622                     dtls1_stop_timer(s);
623                 }
624                 return SUB_STATE_FINISHED;
625             }
626
627             if (ret == MSG_PROCESS_CONTINUE_PROCESSING) {
628                 st->read_state = READ_STATE_POST_PROCESS;
629                 st->read_state_work = WORK_MORE_A;
630             } else {
631                 st->read_state = READ_STATE_HEADER;
632             }
633             break;
634
635         case READ_STATE_POST_PROCESS:
636             st->read_state_work = post_process_message(s, st->read_state_work);
637             switch(st->read_state_work) {
638             default:
639                 return SUB_STATE_ERROR;
640
641             case WORK_FINISHED_CONTINUE:
642                 st->read_state = READ_STATE_HEADER;
643                 break;
644
645             case WORK_FINISHED_STOP:
646                 if (SSL_IS_DTLS(s)) {
647                     dtls1_stop_timer(s);
648                 }
649                 return SUB_STATE_FINISHED;
650             }
651             break;
652
653         default:
654             /* Shouldn't happen */
655             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
656             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
657             statem_set_error(s);
658             return SUB_STATE_ERROR;
659         }
660     }
661 }
662
663 /*
664  * Send a previously constructed message to the peer.
665  */
666 static int statem_do_write(SSL *s)
667 {
668     STATEM *st = &s->statem;
669
670     if (st->hand_state == TLS_ST_CW_CHANGE
671             || st->hand_state == TLS_ST_SW_CHANGE) {
672         if (SSL_IS_DTLS(s))
673             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
674         else
675             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
676     } else {
677         return ssl_do_write(s);
678     }
679 }
680
681 /*
682  * Initialise the MSG_FLOW_WRITING sub-state machine
683  */
684 static void init_write_state_machine(SSL *s)
685 {
686     STATEM *st = &s->statem;
687
688     st->write_state = WRITE_STATE_TRANSITION;
689 }
690
691 /*
692  * This function implements the sub-state machine when the message flow is in
693  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
694  *
695  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
696  * |             |
697  * |             v
698  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
699  * |             |
700  * |             v
701  * |       WRITE_STATE_SEND
702  * |             |
703  * |             v
704  * |     WRITE_STATE_POST_WORK
705  * |             |
706  * +-------------+
707  *
708  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
709
710  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
711  * sending of the message. This could result in an NBIO event occuring in
712  * which case control returns to the calling application. When this function
713  * is recalled we will resume in the same state where we left off.
714  *
715  * WRITE_STATE_SEND sends the message and performs any work to be done after
716  * sending.
717  *
718  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
719  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
720  * result in an NBIO event.
721  */
722 static enum SUB_STATE_RETURN write_state_machine(SSL *s)
723 {
724     STATEM *st = &s->statem;
725     int ret;
726     enum WRITE_TRAN (*transition)(SSL *s);
727     enum WORK_STATE (*pre_work)(SSL *s, enum WORK_STATE wst);
728     enum WORK_STATE (*post_work)(SSL *s, enum WORK_STATE wst);
729     int (*construct_message)(SSL *s);
730     void (*cb) (const SSL *ssl, int type, int val) = NULL;
731
732     if (s->info_callback != NULL)
733         cb = s->info_callback;
734     else if (s->ctx->info_callback != NULL)
735         cb = s->ctx->info_callback;
736
737     if(s->server) {
738         transition = server_write_transition;
739         pre_work = server_pre_work;
740         post_work = server_post_work;
741         construct_message = server_construct_message;
742     } else {
743         transition = client_write_transition;
744         pre_work = client_pre_work;
745         post_work = client_post_work;
746         construct_message = client_construct_message;
747     }
748
749     while(1) {
750         switch(st->write_state) {
751         case WRITE_STATE_TRANSITION:
752             if (cb != NULL) {
753                 /* Notify callback of an impending state change */
754                 if (s->server)
755                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
756                 else
757                     cb(s, SSL_CB_CONNECT_LOOP, 1);
758             }
759             switch(transition(s)) {
760             case WRITE_TRAN_CONTINUE:
761                 st->write_state = WRITE_STATE_PRE_WORK;
762                 st->write_state_work = WORK_MORE_A;
763                 break;
764
765             case WRITE_TRAN_FINISHED:
766                 return SUB_STATE_FINISHED;
767                 break;
768
769             default:
770                 return SUB_STATE_ERROR;
771             }
772             break;
773
774         case WRITE_STATE_PRE_WORK:
775             switch(st->write_state_work = pre_work(s, st->write_state_work)) {
776             default:
777                 return SUB_STATE_ERROR;
778
779             case WORK_FINISHED_CONTINUE:
780                 st->write_state = WRITE_STATE_SEND;
781                 break;
782
783             case WORK_FINISHED_STOP:
784                 return SUB_STATE_END_HANDSHAKE;
785             }
786             if(construct_message(s) == 0)
787                 return SUB_STATE_ERROR;
788
789             /* Fall through */
790
791         case WRITE_STATE_SEND:
792             if (SSL_IS_DTLS(s) && st->use_timer) {
793                 dtls1_start_timer(s);
794             }
795             ret = statem_do_write(s);
796             if (ret <= 0) {
797                 return SUB_STATE_ERROR;
798             }
799             st->write_state = WRITE_STATE_POST_WORK;
800             st->write_state_work = WORK_MORE_A;
801             /* Fall through */
802
803         case WRITE_STATE_POST_WORK:
804             switch(st->write_state_work = post_work(s, st->write_state_work)) {
805             default:
806                 return SUB_STATE_ERROR;
807
808             case WORK_FINISHED_CONTINUE:
809                 st->write_state = WRITE_STATE_TRANSITION;
810                 break;
811
812             case WORK_FINISHED_STOP:
813                 return SUB_STATE_END_HANDSHAKE;
814             }
815             break;
816
817         default:
818             return SUB_STATE_ERROR;
819         }
820     }
821 }
822
823 /*
824  * Flush the write BIO
825  */
826 static int statem_flush(SSL *s)
827 {
828     s->rwstate = SSL_WRITING;
829     if (BIO_flush(s->wbio) <= 0) {
830         return 0;
831     }
832     s->rwstate = SSL_NOTHING;
833
834     return 1;
835 }
836
837 /*
838  * Called by the record layer to determine whether application data is
839  * allowed to be sent in the current handshake state or not.
840  *
841  * Return values are:
842  *   1: Yes (application data allowed)
843  *   0: No (application data not allowed)
844  */
845 int statem_app_data_allowed(SSL *s)
846 {
847     STATEM *st = &s->statem;
848
849     if (st->state == MSG_FLOW_UNINITED || st->state == MSG_FLOW_RENEGOTIATE)
850         return 0;
851
852     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
853         return 0;
854
855     if (s->server) {
856         /*
857          * If we're a server and we haven't got as far as writing our
858          * ServerHello yet then we allow app data
859          */
860         if (st->hand_state == TLS_ST_BEFORE
861                 || st->hand_state == TLS_ST_SR_CLNT_HELLO)
862             return 1;
863     } else {
864         /*
865          * If we're a client and we haven't read the ServerHello yet then we
866          * allow app data
867          */
868         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
869             return 1;
870     }
871
872     return 0;
873 }
874
875
876 #ifndef OPENSSL_NO_SCTP
877 /*
878  * Set flag used by SCTP to determine whether we are in the read sock state
879  */
880 void statem_set_sctp_read_sock(SSL *s, int read_sock)
881 {
882     s->statem.in_sctp_read_sock = read_sock;
883 }
884
885 /*
886  * Called by the record layer to determine whether we are in the read sock
887  * state or not.
888  *
889  * Return values are:
890  *   1: Yes (we are in the read sock state)
891  *   0: No (we are not in the read sock state)
892  */
893 int statem_in_sctp_read_sock(SSL *s)
894 {
895     return s->statem.in_sctp_read_sock;
896 }
897 #endif
898
899 /*
900  * Is a CertificateRequest message allowed at the moment or not?
901  *
902  *  Return values are:
903  *  1: Yes
904  *  0: No
905  */
906 static inline int cert_req_allowed(SSL *s)
907 {
908     /* TLS does not like anon-DH with client cert */
909     if (s->version > SSL3_VERSION
910             && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL))
911         return 0;
912
913     return 1;
914 }
915
916 /*
917  * Are we allowed to skip the ServerKeyExchange message?
918  *
919  *  Return values are:
920  *  1: Yes
921  *  0: No
922  */
923 static inline int key_exchange_skip_allowed(SSL *s)
924 {
925     long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
926
927     /*
928      * Can't skip server key exchange if this is an ephemeral
929      * ciphersuite.
930      */
931     if (alg_k & (SSL_kDHE | SSL_kECDHE)) {
932         return 0;
933     }
934
935     return 1;
936 }
937
938 /*
939  * client_read_transition() encapsulates the logic for the allowed handshake
940  * state transitions when the client is reading messages from the server. The
941  * message type that the server has sent is provided in |mt|. The current state
942  * is in |s->statem.hand_state|.
943  *
944  *  Return values are:
945  *  1: Success (transition allowed)
946  *  0: Error (transition not allowed)
947  */
948 static int client_read_transition(SSL *s, int mt)
949 {
950     STATEM *st = &s->statem;
951
952     switch(st->hand_state) {
953     case TLS_ST_CW_CLNT_HELLO:
954         if (mt == SSL3_MT_SERVER_HELLO) {
955             st->hand_state = TLS_ST_CR_SRVR_HELLO;
956             return 1;
957         }
958
959         if (SSL_IS_DTLS(s)) {
960             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
961                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
962                 return 1;
963             }
964         }
965         break;
966
967     case TLS_ST_CR_SRVR_HELLO:
968         if (s->hit) {
969             if (s->tlsext_ticket_expected) {
970                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
971                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
972                     return 1;
973                 }
974             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
975                 st->hand_state = TLS_ST_CR_CHANGE;
976                 return 1;
977             }
978         } else {
979             if (SSL_IS_DTLS(s) && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
980                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
981                 return 1;
982             } else if (!(s->s3->tmp.new_cipher->algorithm_auth
983                         & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
984                 if (mt == SSL3_MT_CERTIFICATE) {
985                     st->hand_state = TLS_ST_CR_CERT;
986                     return 1;
987                 }
988             } else {
989                 if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
990                     st->hand_state = TLS_ST_CR_KEY_EXCH;
991                     return 1;
992                 } else if (key_exchange_skip_allowed(s)) {
993                     if (mt == SSL3_MT_CERTIFICATE_REQUEST
994                             && cert_req_allowed(s)) {
995                         st->hand_state = TLS_ST_CR_CERT_REQ;
996                         return 1;
997                     } else if (mt == SSL3_MT_SERVER_DONE) {
998                         st->hand_state = TLS_ST_CR_SRVR_DONE;
999                         return 1;
1000                     }
1001                 }
1002             }
1003         }
1004         break;
1005
1006     case TLS_ST_CR_CERT:
1007         if (s->tlsext_status_expected) {
1008             if (mt == SSL3_MT_CERTIFICATE_STATUS) {
1009                 st->hand_state = TLS_ST_CR_CERT_STATUS;
1010                 return 1;
1011             }
1012         } else {
1013             if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
1014                 st->hand_state = TLS_ST_CR_KEY_EXCH;
1015                 return 1;
1016             } else if (key_exchange_skip_allowed(s)) {
1017                 if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
1018                     st->hand_state = TLS_ST_CR_CERT_REQ;
1019                     return 1;
1020                 } else if (mt == SSL3_MT_SERVER_DONE) {
1021                     st->hand_state = TLS_ST_CR_SRVR_DONE;
1022                     return 1;
1023                 }
1024             }
1025         }
1026         break;
1027
1028     case TLS_ST_CR_CERT_STATUS:
1029         if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
1030             st->hand_state = TLS_ST_CR_KEY_EXCH;
1031             return 1;
1032         } else if (key_exchange_skip_allowed(s)) {
1033             if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
1034                 st->hand_state = TLS_ST_CR_CERT_REQ;
1035                 return 1;
1036             } else if (mt == SSL3_MT_SERVER_DONE) {
1037                 st->hand_state = TLS_ST_CR_SRVR_DONE;
1038                 return 1;
1039             }
1040         }
1041         break;
1042
1043     case TLS_ST_CR_KEY_EXCH:
1044         if (mt == SSL3_MT_CERTIFICATE_REQUEST && cert_req_allowed(s)) {
1045             st->hand_state = TLS_ST_CR_CERT_REQ;
1046             return 1;
1047         } else if (mt == SSL3_MT_SERVER_DONE) {
1048             st->hand_state = TLS_ST_CR_SRVR_DONE;
1049             return 1;
1050         }
1051         break;
1052
1053     case TLS_ST_CR_CERT_REQ:
1054         if (mt == SSL3_MT_SERVER_DONE) {
1055             st->hand_state = TLS_ST_CR_SRVR_DONE;
1056             return 1;
1057         }
1058         break;
1059
1060     case TLS_ST_CW_FINISHED:
1061         if (mt == SSL3_MT_NEWSESSION_TICKET && s->tlsext_ticket_expected) {
1062             st->hand_state = TLS_ST_CR_SESSION_TICKET;
1063             return 1;
1064         } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
1065             st->hand_state = TLS_ST_CR_CHANGE;
1066             return 1;
1067         }
1068         break;
1069
1070     case TLS_ST_CR_SESSION_TICKET:
1071         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
1072             st->hand_state = TLS_ST_CR_CHANGE;
1073             return 1;
1074         }
1075         break;
1076
1077     case TLS_ST_CR_CHANGE:
1078         if (mt == SSL3_MT_FINISHED) {
1079             st->hand_state = TLS_ST_CR_FINISHED;
1080             return 1;
1081         }
1082         break;
1083
1084     default:
1085         break;
1086     }
1087
1088     /* No valid transition found */
1089     return 0;
1090 }
1091
1092 /*
1093  * client_write_transition() works out what handshake state to move to next
1094  * when the client is writing messages to be sent to the server.
1095  */
1096 static enum WRITE_TRAN client_write_transition(SSL *s)
1097 {
1098     STATEM *st = &s->statem;
1099
1100     switch(st->hand_state) {
1101         case TLS_ST_OK:
1102             /* Renegotiation - fall through */
1103         case TLS_ST_BEFORE:
1104             st->hand_state = TLS_ST_CW_CLNT_HELLO;
1105             return WRITE_TRAN_CONTINUE;
1106
1107         case TLS_ST_CW_CLNT_HELLO:
1108             /*
1109              * No transition at the end of writing because we don't know what
1110              * we will be sent
1111              */
1112             return WRITE_TRAN_FINISHED;
1113
1114         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1115             st->hand_state = TLS_ST_CW_CLNT_HELLO;
1116             return WRITE_TRAN_CONTINUE;
1117
1118         case TLS_ST_CR_SRVR_DONE:
1119             if (s->s3->tmp.cert_req)
1120                 st->hand_state = TLS_ST_CW_CERT;
1121             else
1122                 st->hand_state = TLS_ST_CW_KEY_EXCH;
1123             return WRITE_TRAN_CONTINUE;
1124
1125         case TLS_ST_CW_CERT:
1126             st->hand_state = TLS_ST_CW_KEY_EXCH;
1127             return WRITE_TRAN_CONTINUE;
1128
1129         case TLS_ST_CW_KEY_EXCH:
1130             /*
1131              * For TLS, cert_req is set to 2, so a cert chain of nothing is
1132              * sent, but no verify packet is sent
1133              */
1134             /*
1135              * XXX: For now, we do not support client authentication in ECDH
1136              * cipher suites with ECDH (rather than ECDSA) certificates. We
1137              * need to skip the certificate verify message when client's
1138              * ECDH public key is sent inside the client certificate.
1139              */
1140             if (s->s3->tmp.cert_req == 1) {
1141                 st->hand_state = TLS_ST_CW_CERT_VRFY;
1142             } else {
1143                 st->hand_state = TLS_ST_CW_CHANGE;
1144             }
1145             if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
1146                 st->hand_state = TLS_ST_CW_CHANGE;
1147             }
1148             return WRITE_TRAN_CONTINUE;
1149
1150         case TLS_ST_CW_CERT_VRFY:
1151             st->hand_state = TLS_ST_CW_CHANGE;
1152             return WRITE_TRAN_CONTINUE;
1153
1154         case TLS_ST_CW_CHANGE:
1155 #if defined(OPENSSL_NO_NEXTPROTONEG)
1156             st->hand_state = TLS_ST_CW_FINISHED;
1157 #else
1158             if (!SSL_IS_DTLS(s) && s->s3->next_proto_neg_seen)
1159                 st->hand_state = TLS_ST_CW_NEXT_PROTO;
1160             else
1161                 st->hand_state = TLS_ST_CW_FINISHED;
1162 #endif
1163             return WRITE_TRAN_CONTINUE;
1164
1165 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1166         case TLS_ST_CW_NEXT_PROTO:
1167             st->hand_state = TLS_ST_CW_FINISHED;
1168             return WRITE_TRAN_CONTINUE;
1169 #endif
1170
1171         case TLS_ST_CW_FINISHED:
1172             if (s->hit) {
1173                 st->hand_state = TLS_ST_OK;
1174                 statem_set_in_init(s, 0);
1175                 return WRITE_TRAN_CONTINUE;
1176             } else {
1177                 return WRITE_TRAN_FINISHED;
1178             }
1179
1180         case TLS_ST_CR_FINISHED:
1181             if (s->hit) {
1182                 st->hand_state = TLS_ST_CW_CHANGE;
1183                 return WRITE_TRAN_CONTINUE;
1184             } else {
1185                 st->hand_state = TLS_ST_OK;
1186                 statem_set_in_init(s, 0);
1187                 return WRITE_TRAN_CONTINUE;
1188             }
1189
1190         default:
1191             /* Shouldn't happen */
1192             return WRITE_TRAN_ERROR;
1193     }
1194 }
1195
1196 /*
1197  * Perform any pre work that needs to be done prior to sending a message from
1198  * the client to the server.
1199  */
1200 static enum WORK_STATE client_pre_work(SSL *s, enum WORK_STATE wst)
1201 {
1202     STATEM *st = &s->statem;
1203
1204     switch(st->hand_state) {
1205     case TLS_ST_CW_CLNT_HELLO:
1206         s->shutdown = 0;
1207         if (SSL_IS_DTLS(s)) {
1208             /* every DTLS ClientHello resets Finished MAC */
1209             ssl3_init_finished_mac(s);
1210         }
1211         break;
1212
1213     case TLS_ST_CW_CERT:
1214         return tls_prepare_client_certificate(s, wst);
1215
1216     case TLS_ST_CW_CHANGE:
1217         if (SSL_IS_DTLS(s)) {
1218             if (s->hit) {
1219                 /*
1220                  * We're into the last flight so we don't retransmit these
1221                  * messages unless we need to.
1222                  */
1223                 st->use_timer = 0;
1224             }
1225 #ifndef OPENSSL_NO_SCTP
1226             if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
1227                 return dtls_wait_for_dry(s);
1228 #endif
1229         }
1230         return WORK_FINISHED_CONTINUE;
1231
1232     case TLS_ST_OK:
1233         return tls_finish_handshake(s, wst);
1234
1235     default:
1236         /* No pre work to be done */
1237         break;
1238     }
1239
1240     return WORK_FINISHED_CONTINUE;
1241 }
1242
1243 /*
1244  * Perform any work that needs to be done after sending a message from the
1245  * client to the server.
1246  */
1247 static enum WORK_STATE client_post_work(SSL *s, enum WORK_STATE wst)
1248 {
1249     STATEM *st = &s->statem;
1250
1251     s->init_num = 0;
1252
1253     switch(st->hand_state) {
1254     case TLS_ST_CW_CLNT_HELLO:
1255         if (SSL_IS_DTLS(s) && s->d1->cookie_len > 0 && statem_flush(s) != 1)
1256             return WORK_MORE_A;
1257 #ifndef OPENSSL_NO_SCTP
1258         /* Disable buffering for SCTP */
1259         if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s))) {
1260 #endif
1261             /*
1262              * turn on buffering for the next lot of output
1263              */
1264             if (s->bbio != s->wbio)
1265                 s->wbio = BIO_push(s->bbio, s->wbio);
1266 #ifndef OPENSSL_NO_SCTP
1267             }
1268 #endif
1269         if (SSL_IS_DTLS(s)) {
1270             /* Treat the next message as the first packet */
1271             s->first_packet = 1;
1272         }
1273         break;
1274
1275     case TLS_ST_CW_KEY_EXCH:
1276         if (tls_client_key_exchange_post_work(s) == 0)
1277             return WORK_ERROR;
1278         break;
1279
1280     case TLS_ST_CW_CHANGE:
1281         s->session->cipher = s->s3->tmp.new_cipher;
1282 #ifdef OPENSSL_NO_COMP
1283         s->session->compress_meth = 0;
1284 #else
1285         if (s->s3->tmp.new_compression == NULL)
1286             s->session->compress_meth = 0;
1287         else
1288             s->session->compress_meth = s->s3->tmp.new_compression->id;
1289 #endif
1290         if (!s->method->ssl3_enc->setup_key_block(s))
1291             return WORK_ERROR;
1292
1293         if (!s->method->ssl3_enc->change_cipher_state(s,
1294                                                       SSL3_CHANGE_CIPHER_CLIENT_WRITE))
1295             return WORK_ERROR;
1296
1297         if (SSL_IS_DTLS(s)) {
1298 #ifndef OPENSSL_NO_SCTP
1299             if (s->hit) {
1300                 /*
1301                  * Change to new shared key of SCTP-Auth, will be ignored if
1302                  * no SCTP used.
1303                  */
1304                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1305                          0, NULL);
1306             }
1307 #endif
1308
1309             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
1310         }
1311         break;
1312
1313     case TLS_ST_CW_FINISHED:
1314 #ifndef OPENSSL_NO_SCTP
1315         if (wst == WORK_MORE_A && SSL_IS_DTLS(s) && s->hit == 0) {
1316             /*
1317              * Change to new shared key of SCTP-Auth, will be ignored if
1318              * no SCTP used.
1319              */
1320             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1321                      0, NULL);
1322         }
1323 #endif
1324         if (statem_flush(s) != 1)
1325             return WORK_MORE_B;
1326
1327         if (s->hit && tls_finish_handshake(s, WORK_MORE_A) != 1)
1328                 return WORK_ERROR;
1329         break;
1330
1331     default:
1332         /* No post work to be done */
1333         break;
1334     }
1335
1336     return WORK_FINISHED_CONTINUE;
1337 }
1338
1339 /*
1340  * Construct a message to be sent from the client to the server.
1341  *
1342  * Valid return values are:
1343  *   1: Success
1344  *   0: Error
1345  */
1346 static int client_construct_message(SSL *s)
1347 {
1348     STATEM *st = &s->statem;
1349
1350     switch(st->hand_state) {
1351     case TLS_ST_CW_CLNT_HELLO:
1352         return tls_construct_client_hello(s);
1353
1354     case TLS_ST_CW_CERT:
1355         return tls_construct_client_certificate(s);
1356
1357     case TLS_ST_CW_KEY_EXCH:
1358         return tls_construct_client_key_exchange(s);
1359
1360     case TLS_ST_CW_CERT_VRFY:
1361         return tls_construct_client_verify(s);
1362
1363     case TLS_ST_CW_CHANGE:
1364         if (SSL_IS_DTLS(s))
1365             return dtls_construct_change_cipher_spec(s);
1366         else
1367             return tls_construct_change_cipher_spec(s);
1368
1369 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1370     case TLS_ST_CW_NEXT_PROTO:
1371         return tls_construct_next_proto(s);
1372 #endif
1373     case TLS_ST_CW_FINISHED:
1374         return tls_construct_finished(s,
1375                                       s->method->
1376                                       ssl3_enc->client_finished_label,
1377                                       s->method->
1378                                       ssl3_enc->client_finished_label_len);
1379
1380     default:
1381         /* Shouldn't happen */
1382         break;
1383     }
1384
1385     return 0;
1386 }
1387
1388 /* The spec allows for a longer length than this, but we limit it */
1389 #define HELLO_VERIFY_REQUEST_MAX_LENGTH 258
1390 #define SERVER_HELLO_MAX_LENGTH         20000
1391 #define SERVER_KEY_EXCH_MAX_LENGTH      102400
1392 #define SERVER_HELLO_DONE_MAX_LENGTH    0
1393 #define CCS_MAX_LENGTH                  1
1394 /* Max should actually be 36 but we are generous */
1395 #define FINISHED_MAX_LENGTH             64
1396
1397 /*
1398  * Returns the maximum allowed length for the current message that we are
1399  * reading. Excludes the message header.
1400  */
1401 static unsigned long client_max_message_size(SSL *s)
1402 {
1403     STATEM *st = &s->statem;
1404
1405     switch(st->hand_state) {
1406         case TLS_ST_CR_SRVR_HELLO:
1407             return SERVER_HELLO_MAX_LENGTH;
1408
1409         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1410             return HELLO_VERIFY_REQUEST_MAX_LENGTH;
1411
1412         case TLS_ST_CR_CERT:
1413             return s->max_cert_list;
1414
1415         case TLS_ST_CR_CERT_STATUS:
1416             return SSL3_RT_MAX_PLAIN_LENGTH;
1417
1418         case TLS_ST_CR_KEY_EXCH:
1419             return SERVER_KEY_EXCH_MAX_LENGTH;
1420
1421         case TLS_ST_CR_CERT_REQ:
1422             return SSL3_RT_MAX_PLAIN_LENGTH;
1423
1424         case TLS_ST_CR_SRVR_DONE:
1425             return SERVER_HELLO_DONE_MAX_LENGTH;
1426
1427         case TLS_ST_CR_CHANGE:
1428             return CCS_MAX_LENGTH;
1429
1430         case TLS_ST_CR_SESSION_TICKET:
1431             return SSL3_RT_MAX_PLAIN_LENGTH;
1432
1433         case TLS_ST_CR_FINISHED:
1434             return FINISHED_MAX_LENGTH;
1435
1436         default:
1437             /* Shouldn't happen */
1438             break;
1439     }
1440
1441     return 0;
1442 }
1443
1444 /*
1445  * Process a message that the client has been received from the server.
1446  */
1447 static enum MSG_PROCESS_RETURN client_process_message(SSL *s, unsigned long len)
1448 {
1449     STATEM *st = &s->statem;
1450
1451     switch(st->hand_state) {
1452         case TLS_ST_CR_SRVR_HELLO:
1453             return tls_process_server_hello(s, len);
1454
1455         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1456             return dtls_process_hello_verify(s, len);
1457
1458         case TLS_ST_CR_CERT:
1459             return tls_process_server_certificate(s, len);
1460
1461         case TLS_ST_CR_CERT_STATUS:
1462             return tls_process_cert_status(s, len);
1463
1464         case TLS_ST_CR_KEY_EXCH:
1465             return tls_process_key_exchange(s, len);
1466
1467         case TLS_ST_CR_CERT_REQ:
1468             return tls_process_certificate_request(s, len);
1469
1470         case TLS_ST_CR_SRVR_DONE:
1471             return tls_process_server_done(s, len);
1472
1473         case TLS_ST_CR_CHANGE:
1474             return tls_process_change_cipher_spec(s, len);
1475
1476         case TLS_ST_CR_SESSION_TICKET:
1477             return tls_process_new_session_ticket(s, len);
1478
1479         case TLS_ST_CR_FINISHED:
1480             return tls_process_finished(s, len);
1481
1482         default:
1483             /* Shouldn't happen */
1484             break;
1485     }
1486
1487     return MSG_PROCESS_ERROR;
1488 }
1489
1490 /*
1491  * Perform any further processing required following the receipt of a message
1492  * from the server
1493  */
1494 static enum WORK_STATE client_post_process_message(SSL *s, enum WORK_STATE wst)
1495 {
1496     STATEM *st = &s->statem;
1497
1498     switch(st->hand_state) {
1499 #ifndef OPENSSL_NO_SCTP
1500     case TLS_ST_CR_SRVR_DONE:
1501         /* We only get here if we are using SCTP and we are renegotiating */
1502         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1503             s->s3->in_read_app_data = 2;
1504             s->rwstate = SSL_READING;
1505             BIO_clear_retry_flags(SSL_get_rbio(s));
1506             BIO_set_retry_read(SSL_get_rbio(s));
1507             statem_set_sctp_read_sock(s, 1);
1508             return WORK_MORE_A;
1509         }
1510         statem_set_sctp_read_sock(s, 0);
1511         return WORK_FINISHED_STOP;
1512 #endif
1513
1514     case TLS_ST_CR_FINISHED:
1515         if (!s->hit)
1516             return tls_finish_handshake(s, wst);
1517         else
1518             return WORK_FINISHED_STOP;
1519     default:
1520         break;
1521     }
1522
1523     /* Shouldn't happen */
1524     return WORK_ERROR;
1525 }
1526
1527
1528 /*
1529  * server_read_transition() encapsulates the logic for the allowed handshake
1530  * state transitions when the server is reading messages from the client. The
1531  * message type that the client has sent is provided in |mt|. The current state
1532  * is in |s->statem.hand_state|.
1533  *
1534  *  Valid return values are:
1535  *  1: Success (transition allowed)
1536  *  0: Error (transition not allowed)
1537  */
1538 static int server_read_transition(SSL *s, int mt)
1539 {
1540     STATEM *st = &s->statem;
1541
1542     switch(st->hand_state) {
1543     case TLS_ST_BEFORE:
1544     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1545         if (mt == SSL3_MT_CLIENT_HELLO) {
1546             st->hand_state = TLS_ST_SR_CLNT_HELLO;
1547             return 1;
1548         }
1549         break;
1550
1551     case TLS_ST_SW_SRVR_DONE:
1552         /*
1553          * If we get a CKE message after a ServerDone then either
1554          * 1) We didn't request a Certificate
1555          * OR
1556          * 2) If we did request one then
1557          *      a) We allow no Certificate to be returned
1558          *      AND
1559          *      b) We are running SSL3 (in TLS1.0+ the client must return a 0
1560          *         list if we requested a certificate)
1561          */
1562         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
1563                 && (!s->s3->tmp.cert_request
1564                     || (!((s->verify_mode & SSL_VERIFY_PEER) &&
1565                           (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1566                         && (s->version == SSL3_VERSION)))) {
1567             st->hand_state = TLS_ST_SR_KEY_EXCH;
1568             return 1;
1569         } else if (s->s3->tmp.cert_request) {
1570             if (mt == SSL3_MT_CERTIFICATE) {
1571                 st->hand_state = TLS_ST_SR_CERT;
1572                 return 1;
1573             } 
1574         }
1575         break;
1576
1577     case TLS_ST_SR_CERT:
1578         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
1579             st->hand_state = TLS_ST_SR_KEY_EXCH;
1580             return 1;
1581         }
1582         break;
1583
1584     case TLS_ST_SR_KEY_EXCH:
1585         /*
1586          * We should only process a CertificateVerify message if we have
1587          * received a Certificate from the client. If so then |s->session->peer|
1588          * will be non NULL. In some instances a CertificateVerify message is
1589          * not required even if the peer has sent a Certificate (e.g. such as in
1590          * the case of static DH). In that case |s->no_cert_verify| should be
1591          * set.
1592          */
1593         if (s->session->peer == NULL || s->no_cert_verify) {
1594             if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
1595                 /*
1596                  * For the ECDH ciphersuites when the client sends its ECDH
1597                  * pub key in a certificate, the CertificateVerify message is
1598                  * not sent. Also for GOST ciphersuites when the client uses
1599                  * its key from the certificate for key exchange.
1600                  */
1601                 st->hand_state = TLS_ST_SR_CHANGE;
1602                 return 1;
1603             }
1604         } else {
1605             if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
1606                 st->hand_state = TLS_ST_SR_CERT_VRFY;
1607                 return 1;
1608             }
1609         }
1610         break;
1611
1612     case TLS_ST_SR_CERT_VRFY:
1613         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
1614             st->hand_state = TLS_ST_SR_CHANGE;
1615             return 1;
1616         }
1617         break;
1618
1619     case TLS_ST_SR_CHANGE:
1620 #ifndef OPENSSL_NO_NEXTPROTONEG
1621         if (s->s3->next_proto_neg_seen) {
1622             if (mt == SSL3_MT_NEXT_PROTO) {
1623                 st->hand_state = TLS_ST_SR_NEXT_PROTO;
1624                 return 1;
1625             }
1626         } else {
1627 #endif
1628             if (mt == SSL3_MT_FINISHED) {
1629                 st->hand_state = TLS_ST_SR_FINISHED;
1630                 return 1;
1631             }
1632 #ifndef OPENSSL_NO_NEXTPROTONEG
1633         }
1634 #endif
1635         break;
1636
1637 #ifndef OPENSSL_NO_NEXTPROTONEG
1638     case TLS_ST_SR_NEXT_PROTO:
1639         if (mt == SSL3_MT_FINISHED) {
1640             st->hand_state = TLS_ST_SR_FINISHED;
1641             return 1;
1642         }
1643         break;
1644 #endif
1645
1646     case TLS_ST_SW_FINISHED:
1647         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
1648             st->hand_state = TLS_ST_SR_CHANGE;
1649             return 1;
1650         }
1651         break;
1652
1653     default:
1654         break;
1655     }
1656
1657     /* No valid transition found */
1658     return 0;
1659 }
1660
1661 /*
1662  * Should we send a ServerKeyExchange message?
1663  *
1664  * Valid return values are:
1665  *   1: Yes
1666  *   0: No
1667  */
1668 static inline int send_server_key_exchange(SSL *s)
1669 {
1670     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1671
1672     /*
1673      * only send a ServerKeyExchange if DH, fortezza or RSA but we have a
1674      * sign only certificate PSK: may send PSK identity hints For
1675      * ECC ciphersuites, we send a serverKeyExchange message only if
1676      * the cipher suite is either ECDH-anon or ECDHE. In other cases,
1677      * the server certificate contains the server's public key for
1678      * key exchange.
1679      */
1680     if (   (alg_k & SSL_kDHE)
1681         || (alg_k & SSL_kECDHE)
1682         || ((alg_k & SSL_kRSA)
1683             && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
1684                 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
1685                     && EVP_PKEY_size(s->cert->pkeys
1686                                      [SSL_PKEY_RSA_ENC].privatekey) *
1687                     8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
1688                    )
1689                )
1690            )
1691         /*
1692          * PSK: send ServerKeyExchange if PSK identity hint if
1693          * provided
1694          */
1695 #ifndef OPENSSL_NO_PSK
1696         /* Only send SKE if we have identity hint for plain PSK */
1697         || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
1698             && s->cert->psk_identity_hint)
1699         /* For other PSK always send SKE */
1700         || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
1701 #endif
1702 #ifndef OPENSSL_NO_SRP
1703         /* SRP: send ServerKeyExchange */
1704         || (alg_k & SSL_kSRP)
1705 #endif
1706        ) {
1707         return 1;
1708     }
1709
1710     return 0;
1711 }
1712
1713 /*
1714  * Should we send a CertificateRequest message?
1715  *
1716  * Valid return values are:
1717  *   1: Yes
1718  *   0: No
1719  */
1720 static inline int send_certificate_request(SSL *s)
1721 {
1722     if (
1723            /* don't request cert unless asked for it: */
1724            s->verify_mode & SSL_VERIFY_PEER
1725            /*
1726             * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
1727             * during re-negotiation:
1728             */
1729            && ((s->session->peer == NULL) ||
1730                !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
1731            /*
1732             * never request cert in anonymous ciphersuites (see
1733             * section "Certificate request" in SSL 3 drafts and in
1734             * RFC 2246):
1735             */
1736            && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1737            /*
1738             * ... except when the application insists on
1739             * verification (against the specs, but s3_clnt.c accepts
1740             * this for SSL 3)
1741             */
1742                || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
1743            /* don't request certificate for SRP auth */
1744            && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
1745            /*
1746             * With normal PSK Certificates and Certificate Requests
1747             * are omitted
1748             */
1749            && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1750         return 1;
1751     }
1752
1753     return 0;
1754 }
1755
1756 /*
1757  * server_write_transition() works out what handshake state to move to next
1758  * when the server is writing messages to be sent to the client.
1759  */
1760 static enum WRITE_TRAN server_write_transition(SSL *s)
1761 {
1762     STATEM *st = &s->statem;
1763
1764     switch(st->hand_state) {
1765         case TLS_ST_BEFORE:
1766             /* Just go straight to trying to read from the client */;
1767             return WRITE_TRAN_FINISHED;
1768
1769         case TLS_ST_OK:
1770             /* We must be trying to renegotiate */
1771             st->hand_state = TLS_ST_SW_HELLO_REQ;
1772             return WRITE_TRAN_CONTINUE;
1773
1774         case TLS_ST_SW_HELLO_REQ:
1775             st->hand_state = TLS_ST_OK;
1776             statem_set_in_init(s, 0);
1777             return WRITE_TRAN_CONTINUE;
1778
1779         case TLS_ST_SR_CLNT_HELLO:
1780             if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
1781                     && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
1782                 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
1783             else
1784                 st->hand_state = TLS_ST_SW_SRVR_HELLO;
1785             return WRITE_TRAN_CONTINUE;
1786
1787         case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1788             return WRITE_TRAN_FINISHED;
1789
1790         case TLS_ST_SW_SRVR_HELLO:
1791             if (s->hit) {
1792                 if (s->tlsext_ticket_expected)
1793                     st->hand_state = TLS_ST_SW_SESSION_TICKET;
1794                 else
1795                     st->hand_state = TLS_ST_SW_CHANGE;
1796             } else {
1797                 /* Check if it is anon DH or anon ECDH, */
1798                 /* normal PSK or SRP */
1799                 if (!(s->s3->tmp.new_cipher->algorithm_auth &
1800                      (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
1801                     st->hand_state = TLS_ST_SW_CERT;
1802                 } else if (send_server_key_exchange(s)) {
1803                     st->hand_state = TLS_ST_SW_KEY_EXCH;
1804                 } else if (send_certificate_request(s)) {
1805                     st->hand_state = TLS_ST_SW_CERT_REQ;
1806                 } else {
1807                     st->hand_state = TLS_ST_SW_SRVR_DONE;
1808                 }
1809             }
1810             return WRITE_TRAN_CONTINUE;
1811
1812         case TLS_ST_SW_CERT:
1813             if (s->tlsext_status_expected) {
1814                 st->hand_state = TLS_ST_SW_CERT_STATUS;
1815                 return WRITE_TRAN_CONTINUE;
1816             }
1817             /* Fall through */
1818
1819         case TLS_ST_SW_CERT_STATUS:
1820             if (send_server_key_exchange(s)) {
1821                 st->hand_state = TLS_ST_SW_KEY_EXCH;
1822                 return WRITE_TRAN_CONTINUE;
1823             }
1824             /* Fall through */
1825
1826         case TLS_ST_SW_KEY_EXCH:
1827             if (send_certificate_request(s)) {
1828                 st->hand_state = TLS_ST_SW_CERT_REQ;
1829                 return WRITE_TRAN_CONTINUE;
1830             }
1831             /* Fall through */
1832
1833         case TLS_ST_SW_CERT_REQ:
1834             st->hand_state = TLS_ST_SW_SRVR_DONE;
1835             return WRITE_TRAN_CONTINUE;
1836
1837         case TLS_ST_SW_SRVR_DONE:
1838             return WRITE_TRAN_FINISHED;
1839
1840         case TLS_ST_SR_FINISHED:
1841             if (s->hit) {
1842                 st->hand_state = TLS_ST_OK;
1843                 statem_set_in_init(s, 0);
1844                 return WRITE_TRAN_CONTINUE;
1845             } else if (s->tlsext_ticket_expected) {
1846                 st->hand_state = TLS_ST_SW_SESSION_TICKET;
1847             } else {
1848                 st->hand_state = TLS_ST_SW_CHANGE;
1849             }
1850             return WRITE_TRAN_CONTINUE;
1851
1852         case TLS_ST_SW_SESSION_TICKET:
1853             st->hand_state = TLS_ST_SW_CHANGE;
1854             return WRITE_TRAN_CONTINUE;
1855
1856         case TLS_ST_SW_CHANGE:
1857             st->hand_state = TLS_ST_SW_FINISHED;
1858             return WRITE_TRAN_CONTINUE;
1859
1860         case TLS_ST_SW_FINISHED:
1861             if (s->hit) {
1862                 return WRITE_TRAN_FINISHED;
1863             }
1864             st->hand_state = TLS_ST_OK;
1865             statem_set_in_init(s, 0);
1866             return WRITE_TRAN_CONTINUE;
1867
1868         default:
1869             /* Shouldn't happen */
1870             return WRITE_TRAN_ERROR;
1871     }
1872 }
1873
1874 /*
1875  * Perform any pre work that needs to be done prior to sending a message from
1876  * the server to the client.
1877  */
1878 static enum WORK_STATE server_pre_work(SSL *s, enum WORK_STATE wst)
1879 {
1880     STATEM *st = &s->statem;
1881
1882     switch(st->hand_state) {
1883     case TLS_ST_SW_HELLO_REQ:
1884         s->shutdown = 0;
1885         if (SSL_IS_DTLS(s))
1886             dtls1_clear_record_buffer(s);
1887         break;
1888
1889     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1890         s->shutdown = 0;
1891         if (SSL_IS_DTLS(s)) {
1892             dtls1_clear_record_buffer(s);
1893             /* We don't buffer this message so don't use the timer */
1894             st->use_timer = 0;
1895         }
1896         break;
1897
1898     case TLS_ST_SW_SRVR_HELLO:
1899         if (SSL_IS_DTLS(s)) {
1900             /*
1901              * Messages we write from now on should be bufferred and
1902              * retransmitted if necessary, so we need to use the timer now
1903              */
1904             st->use_timer = 1;
1905         }
1906         break;
1907
1908     case TLS_ST_SW_SRVR_DONE:
1909 #ifndef OPENSSL_NO_SCTP
1910         if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
1911             return dtls_wait_for_dry(s);
1912 #endif
1913         return WORK_FINISHED_CONTINUE;
1914
1915     case TLS_ST_SW_SESSION_TICKET:
1916         if (SSL_IS_DTLS(s)) {
1917             /*
1918              * We're into the last flight. We don't retransmit the last flight
1919              * unless we need to, so we don't use the timer
1920              */
1921             st->use_timer = 0;
1922         }
1923         break;
1924
1925     case TLS_ST_SW_CHANGE:
1926         s->session->cipher = s->s3->tmp.new_cipher;
1927         if (!s->method->ssl3_enc->setup_key_block(s)) {
1928             statem_set_error(s);
1929             return WORK_ERROR;
1930         }
1931         if (SSL_IS_DTLS(s)) {
1932             /*
1933              * We're into the last flight. We don't retransmit the last flight
1934              * unless we need to, so we don't use the timer. This might have
1935              * already been set to 0 if we sent a NewSessionTicket message,
1936              * but we'll set it again here in case we didn't.
1937              */
1938             st->use_timer = 0;
1939         }
1940         return WORK_FINISHED_CONTINUE;
1941
1942     case TLS_ST_OK:
1943         return tls_finish_handshake(s, wst);
1944
1945     default:
1946         /* No pre work to be done */
1947         break;
1948     }
1949
1950     return WORK_FINISHED_CONTINUE;
1951 }
1952
1953 /*
1954  * Perform any work that needs to be done after sending a message from the
1955  * server to the client.
1956  */
1957 static enum WORK_STATE server_post_work(SSL *s, enum WORK_STATE wst)
1958 {
1959     STATEM *st = &s->statem;
1960
1961     s->init_num = 0;
1962
1963     switch(st->hand_state) {
1964     case TLS_ST_SW_HELLO_REQ:
1965         if (statem_flush(s) != 1)
1966             return WORK_MORE_A;
1967         ssl3_init_finished_mac(s);
1968         break;
1969
1970     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1971         if (statem_flush(s) != 1)
1972             return WORK_MORE_A;
1973         /* HelloVerifyRequest resets Finished MAC */
1974         if (s->version != DTLS1_BAD_VER)
1975             ssl3_init_finished_mac(s);
1976         /*
1977          * The next message should be another ClientHello which we need to
1978          * treat like it was the first packet
1979          */
1980         s->first_packet = 1;
1981         break;
1982
1983     case TLS_ST_SW_SRVR_HELLO:
1984 #ifndef OPENSSL_NO_SCTP
1985         if (SSL_IS_DTLS(s) && s->hit) {
1986             unsigned char sctpauthkey[64];
1987             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1988
1989             /*
1990              * Add new shared key for SCTP-Auth, will be ignored if no
1991              * SCTP used.
1992              */
1993             snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
1994                      DTLS1_SCTP_AUTH_LABEL);
1995
1996             if (SSL_export_keying_material(s, sctpauthkey,
1997                     sizeof(sctpauthkey), labelbuffer,
1998                     sizeof(labelbuffer), NULL, 0, 0) <= 0) {
1999                 statem_set_error(s);
2000                 return WORK_ERROR;
2001             }
2002
2003             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2004                      sizeof(sctpauthkey), sctpauthkey);
2005         }
2006 #endif
2007         break;
2008
2009     case TLS_ST_SW_CHANGE:
2010 #ifndef OPENSSL_NO_SCTP
2011         if (SSL_IS_DTLS(s) && !s->hit) {
2012             /*
2013              * Change to new shared key of SCTP-Auth, will be ignored if
2014              * no SCTP used.
2015              */
2016             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
2017                      0, NULL);
2018         }
2019 #endif
2020         if (!s->method->ssl3_enc->change_cipher_state(s,
2021                 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
2022             statem_set_error(s);
2023             return WORK_ERROR;
2024         }
2025
2026         if (SSL_IS_DTLS(s))
2027             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
2028         break;
2029
2030     case TLS_ST_SW_SRVR_DONE:
2031         if (statem_flush(s) != 1)
2032             return WORK_MORE_A;
2033         break;
2034
2035     case TLS_ST_SW_FINISHED:
2036         if (statem_flush(s) != 1)
2037             return WORK_MORE_A;
2038 #ifndef OPENSSL_NO_SCTP
2039         if (SSL_IS_DTLS(s) && s->hit) {
2040             /*
2041              * Change to new shared key of SCTP-Auth, will be ignored if
2042              * no SCTP used.
2043              */
2044             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
2045                      0, NULL);
2046         }
2047 #endif
2048         break;
2049
2050     default:
2051         /* No post work to be done */
2052         break;
2053     }
2054
2055     return WORK_FINISHED_CONTINUE;
2056 }
2057
2058 /*
2059  * Construct a message to be sent from the server to the client.
2060  *
2061  * Valid return values are:
2062  *   1: Success
2063  *   0: Error
2064  */
2065 static int server_construct_message(SSL *s)
2066 {
2067     STATEM *st = &s->statem;
2068
2069     switch(st->hand_state) {
2070     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
2071         return dtls_construct_hello_verify_request(s);
2072
2073     case TLS_ST_SW_HELLO_REQ:
2074         return tls_construct_hello_request(s);
2075
2076     case TLS_ST_SW_SRVR_HELLO:
2077         return tls_construct_server_hello(s);
2078
2079     case TLS_ST_SW_CERT:
2080         return tls_construct_server_certificate(s);
2081
2082     case TLS_ST_SW_KEY_EXCH:
2083         return tls_construct_server_key_exchange(s);
2084
2085     case TLS_ST_SW_CERT_REQ:
2086         return tls_construct_certificate_request(s);
2087
2088     case TLS_ST_SW_SRVR_DONE:
2089         return tls_construct_server_done(s);
2090
2091     case TLS_ST_SW_SESSION_TICKET:
2092         return tls_construct_new_session_ticket(s);
2093
2094     case TLS_ST_SW_CERT_STATUS:
2095         return tls_construct_cert_status(s);
2096
2097     case TLS_ST_SW_CHANGE:
2098         if (SSL_IS_DTLS(s))
2099             return dtls_construct_change_cipher_spec(s);
2100         else
2101             return tls_construct_change_cipher_spec(s);
2102
2103     case TLS_ST_SW_FINISHED:
2104         return tls_construct_finished(s,
2105                                       s->method->
2106                                       ssl3_enc->server_finished_label,
2107                                       s->method->
2108                                       ssl3_enc->server_finished_label_len);
2109
2110     default:
2111         /* Shouldn't happen */
2112         break;
2113     }
2114
2115     return 0;
2116 }
2117
2118 #define CLIENT_KEY_EXCH_MAX_LENGTH      2048
2119 #define NEXT_PROTO_MAX_LENGTH           514
2120
2121 /*
2122  * Returns the maximum allowed length for the current message that we are
2123  * reading. Excludes the message header.
2124  */
2125 static unsigned long server_max_message_size(SSL *s)
2126 {
2127     STATEM *st = &s->statem;
2128
2129     switch(st->hand_state) {
2130     case TLS_ST_SR_CLNT_HELLO:
2131         return SSL3_RT_MAX_PLAIN_LENGTH;
2132
2133     case TLS_ST_SR_CERT:
2134         return s->max_cert_list;
2135
2136     case TLS_ST_SR_KEY_EXCH:
2137         return CLIENT_KEY_EXCH_MAX_LENGTH;
2138
2139     case TLS_ST_SR_CERT_VRFY:
2140         return SSL3_RT_MAX_PLAIN_LENGTH;
2141
2142 #ifndef OPENSSL_NO_NEXTPROTONEG
2143     case TLS_ST_SR_NEXT_PROTO:
2144         return NEXT_PROTO_MAX_LENGTH;
2145 #endif
2146
2147     case TLS_ST_SR_CHANGE:
2148         return CCS_MAX_LENGTH;
2149
2150     case TLS_ST_SR_FINISHED:
2151         return FINISHED_MAX_LENGTH;
2152
2153     default:
2154         /* Shouldn't happen */
2155         break;
2156     }
2157
2158     return 0;
2159 }
2160
2161 /*
2162  * Process a message that the server has received from the client.
2163  */
2164 static enum MSG_PROCESS_RETURN  server_process_message(SSL *s,
2165                                                        unsigned long len)
2166 {
2167     STATEM *st = &s->statem;
2168
2169     switch(st->hand_state) {
2170     case TLS_ST_SR_CLNT_HELLO:
2171         return tls_process_client_hello(s, len);
2172
2173     case TLS_ST_SR_CERT:
2174         return tls_process_client_certificate(s, len);
2175
2176     case TLS_ST_SR_KEY_EXCH:
2177         return tls_process_client_key_exchange(s, len);
2178
2179     case TLS_ST_SR_CERT_VRFY:
2180         return tls_process_cert_verify(s, len);
2181
2182 #ifndef OPENSSL_NO_NEXTPROTONEG
2183     case TLS_ST_SR_NEXT_PROTO:
2184         return tls_process_next_proto(s, len);
2185 #endif
2186
2187     case TLS_ST_SR_CHANGE:
2188         return tls_process_change_cipher_spec(s, len);
2189
2190     case TLS_ST_SR_FINISHED:
2191         return tls_process_finished(s, len);
2192
2193     default:
2194         /* Shouldn't happen */
2195         break;
2196     }
2197
2198     return MSG_PROCESS_ERROR;
2199 }
2200
2201 /*
2202  * Perform any further processing required following the receipt of a message
2203  * from the client
2204  */
2205 static enum WORK_STATE server_post_process_message(SSL *s, enum WORK_STATE wst)
2206 {
2207     STATEM *st = &s->statem;
2208
2209     switch(st->hand_state) {
2210     case TLS_ST_SR_CLNT_HELLO:
2211         return tls_post_process_client_hello(s, wst);
2212
2213     case TLS_ST_SR_KEY_EXCH:
2214         return tls_post_process_client_key_exchange(s, wst);
2215
2216     case TLS_ST_SR_CERT_VRFY:
2217 #ifndef OPENSSL_NO_SCTP
2218         if (    /* Is this SCTP? */
2219                 BIO_dgram_is_sctp(SSL_get_wbio(s))
2220                 /* Are we renegotiating? */
2221                 && s->renegotiate
2222                 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2223             s->s3->in_read_app_data = 2;
2224             s->rwstate = SSL_READING;
2225             BIO_clear_retry_flags(SSL_get_rbio(s));
2226             BIO_set_retry_read(SSL_get_rbio(s));
2227             statem_set_sctp_read_sock(s, 1);
2228             return WORK_MORE_A;
2229         } else {
2230             statem_set_sctp_read_sock(s, 0);
2231         }
2232 #endif
2233         return WORK_FINISHED_CONTINUE;
2234
2235
2236     case TLS_ST_SR_FINISHED:
2237         if (s->hit)
2238             return tls_finish_handshake(s, wst);
2239         else
2240             return WORK_FINISHED_STOP;
2241     default:
2242         break;
2243     }
2244
2245     /* Shouldn't happen */
2246     return WORK_ERROR;
2247 }