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