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