Remove ssl_get_message from ssl_method_st
[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, PACKET *pkt);
120 static enum WORK_STATE client_post_process_message(SSL *s, enum WORK_STATE wst);
121 static int server_read_transition(SSL *s, int mt);
122 static inline int send_server_key_exchange(SSL *s);
123 static inline int send_certificate_request(SSL *s);
124 static enum WRITE_TRAN server_write_transition(SSL *s);
125 static enum WORK_STATE server_pre_work(SSL *s, enum WORK_STATE wst);
126 static enum WORK_STATE server_post_work(SSL *s, enum WORK_STATE wst);
127 static int server_construct_message(SSL *s);
128 static unsigned long server_max_message_size(SSL *s);
129 static enum MSG_PROCESS_RETURN server_process_message(SSL *s, PACKET *pkt);
130 static enum WORK_STATE server_post_process_message(SSL *s, enum WORK_STATE wst);
131
132
133 enum HANDSHAKE_STATE SSL_state(const SSL *ssl)
134 {
135     return ssl->statem.hand_state;
136 }
137
138 void SSL_set_state(SSL *ssl, enum HANDSHAKE_STATE state)
139 {
140     /*
141      * This function seems like a really bad idea. Should we remove it
142      * completely?
143      */
144     ssl->statem.hand_state = state;
145 }
146
147 int SSL_in_init(SSL *s)
148 {
149     return s->statem.in_init;
150 }
151
152 int SSL_is_init_finished(SSL *s)
153 {
154     return !(s->statem.in_init) && (s->statem.hand_state == TLS_ST_OK);
155 }
156
157 int SSL_in_before(SSL *s)
158 {
159     /*
160      * Historically being "in before" meant before anything had happened. In the
161      * current code though we remain in the "before" state for a while after we
162      * have started the handshake process (e.g. as a server waiting for the
163      * first message to arrive). There "in before" is taken to mean "in before"
164      * and not started any handshake process yet.
165      */
166     return (s->statem.hand_state == TLS_ST_BEFORE)
167         && (s->statem.state == MSG_FLOW_UNINITED);
168 }
169
170 /*
171  * Clear the state machine state and reset back to MSG_FLOW_UNINITED
172  */
173 void statem_clear(SSL *s)
174 {
175     s->statem.state = MSG_FLOW_UNINITED;
176     s->statem.hand_state = TLS_ST_BEFORE;
177     s->statem.in_init = 1;
178 }
179
180 /*
181  * Set the state machine up ready for a renegotiation handshake
182  */
183 void statem_set_renegotiate(SSL *s)
184 {
185     s->statem.state = MSG_FLOW_RENEGOTIATE;
186     s->statem.in_init = 1;
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 (s->init_buf == NULL) {
359             if ((buf = BUF_MEM_new()) == NULL) {
360                 goto end;
361             }
362             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
363                 goto end;
364             }
365             s->init_buf = buf;
366             buf = NULL;
367         }
368
369         if (!ssl3_setup_buffers(s)) {
370             goto end;
371         }
372         s->init_num = 0;
373
374         /*
375          * Should have been reset by tls_process_finished, too.
376          */
377         s->s3->change_cipher_spec = 0;
378
379         if (!server || st->state != MSG_FLOW_RENEGOTIATE) {
380                 /*
381                  * Ok, we now need to push on a buffering BIO ...but not with
382                  * SCTP
383                  */
384 #ifndef OPENSSL_NO_SCTP
385                 if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
386 #endif
387                     if (!ssl_init_wbio_buffer(s, server ? 1 : 0)) {
388                         goto end;
389                     }
390
391             ssl3_init_finished_mac(s);
392         }
393
394         if (server) {
395             if (st->state != MSG_FLOW_RENEGOTIATE) {
396                 s->ctx->stats.sess_accept++;
397             } else if (!s->s3->send_connection_binding &&
398                        !(s->options &
399                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
400                 /*
401                  * Server attempting to renegotiate with client that doesn't
402                  * support secure renegotiation.
403                  */
404                 SSLerr(SSL_F_STATE_MACHINE,
405                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
406                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
407                 statem_set_error(s);
408                 goto end;
409             } else {
410                 /*
411                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
412                  * HelloRequest
413                  */
414                 s->ctx->stats.sess_accept_renegotiate++;
415             }
416         } else {
417             s->ctx->stats.sess_connect++;
418
419             /* mark client_random uninitialized */
420             memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
421             s->hit = 0;
422
423             s->s3->tmp.cert_request = 0;
424
425             if (SSL_IS_DTLS(s)) {
426                 st->use_timer = 1;
427             }
428         }
429
430         st->state = MSG_FLOW_WRITING;
431         init_write_state_machine(s);
432         st->read_state_first_init = 1;
433     }
434
435     while(st->state != MSG_FLOW_FINISHED) {
436         if(st->state == MSG_FLOW_READING) {
437             ssret = read_state_machine(s);
438             if (ssret == SUB_STATE_FINISHED) {
439                 st->state = MSG_FLOW_WRITING;
440                 init_write_state_machine(s);
441             } else {
442                 /* NBIO or error */
443                 goto end;
444             }
445         } else if (st->state == MSG_FLOW_WRITING) {
446             ssret = write_state_machine(s);
447             if (ssret == SUB_STATE_FINISHED) {
448                 st->state = MSG_FLOW_READING;
449                 init_read_state_machine(s);
450             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
451                 st->state = MSG_FLOW_FINISHED;
452             } else {
453                 /* NBIO or error */
454                 goto end;
455             }
456         } else {
457             /* Error */
458             statem_set_error(s);
459             goto end;
460         }
461     }
462
463     st->state = MSG_FLOW_UNINITED;
464     ret = 1;
465
466  end:
467     s->in_handshake--;
468
469 #ifndef OPENSSL_NO_SCTP
470     if (SSL_IS_DTLS(s)) {
471         /*
472          * Notify SCTP BIO socket to leave handshake mode and allow stream
473          * identifier other than 0. Will be ignored if no SCTP is used.
474          */
475         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
476                  s->in_handshake, NULL);
477     }
478 #endif
479
480     BUF_MEM_free(buf);
481     if (cb != NULL) {
482         if (server)
483             cb(s, SSL_CB_ACCEPT_EXIT, ret);
484         else
485             cb(s, SSL_CB_CONNECT_EXIT, ret);
486     }
487     return ret;
488 }
489
490 /*
491  * Initialise the MSG_FLOW_READING sub-state machine
492  */
493 static void init_read_state_machine(SSL *s)
494 {
495     STATEM *st = &s->statem;
496
497     st->read_state = READ_STATE_HEADER;
498 }
499
500 /*
501  * This function implements the sub-state machine when the message flow is in
502  * MSG_FLOW_READING. The valid sub-states and transitions are:
503  *
504  * READ_STATE_HEADER <--+<-------------+
505  *        |             |              |
506  *        v             |              |
507  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
508  *        |                            |
509  *        +----------------------------+
510  *        v
511  * [SUB_STATE_FINISHED]
512  *
513  * READ_STATE_HEADER has the responsibility for reading in the message header
514  * and transitioning the state of the handshake state machine.
515  *
516  * READ_STATE_BODY reads in the rest of the message and then subsequently
517  * processes it.
518  *
519  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
520  * processing activity performed on the message may block.
521  *
522  * Any of the above states could result in an NBIO event occuring in which case
523  * control returns to the calling application. When this function is recalled we
524  * will resume in the same state where we left off.
525  */
526 static enum SUB_STATE_RETURN read_state_machine(SSL *s) {
527     STATEM *st = &s->statem;
528     int ret, mt;
529     unsigned long len;
530     int (*transition)(SSL *s, int mt);
531     PACKET pkt;
532     enum MSG_PROCESS_RETURN (*process_message)(SSL *s, PACKET *pkt);
533     enum WORK_STATE (*post_process_message)(SSL *s, enum WORK_STATE wst);
534     unsigned long (*max_message_size)(SSL *s);
535     void (*cb) (const SSL *ssl, int type, int val) = NULL;
536
537     if (s->info_callback != NULL)
538         cb = s->info_callback;
539     else if (s->ctx->info_callback != NULL)
540         cb = s->ctx->info_callback;
541
542     if(s->server) {
543         transition = server_read_transition;
544         process_message = server_process_message;
545         max_message_size = server_max_message_size;
546         post_process_message = server_post_process_message;
547     } else {
548         transition = client_read_transition;
549         process_message = client_process_message;
550         max_message_size = client_max_message_size;
551         post_process_message = client_post_process_message;
552     }
553
554     if (st->read_state_first_init) {
555         s->first_packet = 1;
556         st->read_state_first_init = 0;
557     }
558
559     while(1) {
560         switch(st->read_state) {
561         case READ_STATE_HEADER:
562             s->init_num = 0;
563             /* Get the state the peer wants to move to */
564             if (SSL_IS_DTLS(s)) {
565                 /*
566                  * In DTLS we get the whole message in one go - header and body
567                  */
568                 ret = dtls_get_message(s, &mt, &len);
569             } else {
570                 ret = tls_get_message_header(s, &mt);
571             }
572
573             if (ret == 0) {
574                 /* Could be non-blocking IO */
575                 return SUB_STATE_ERROR;
576             }
577
578             if (cb != NULL) {
579                 /* Notify callback of an impending state change */
580                 if (s->server)
581                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
582                 else
583                     cb(s, SSL_CB_CONNECT_LOOP, 1);
584             }
585             /*
586              * Validate that we are allowed to move to the new state and move
587              * to that state if so
588              */
589             if(!transition(s, mt)) {
590                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
591                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_UNEXPECTED_MESSAGE);
592                 return SUB_STATE_ERROR;
593             }
594
595             if (s->s3->tmp.message_size > max_message_size(s)) {
596                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
597                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
598                 return SUB_STATE_ERROR;
599             }
600
601             st->read_state = READ_STATE_BODY;
602             /* Fall through */
603
604         case READ_STATE_BODY:
605             if (!SSL_IS_DTLS(s)) {
606                 /* We already got this above for DTLS */
607                 ret = tls_get_message_body(s, &len);
608                 if (ret == 0) {
609                     /* Could be non-blocking IO */
610                     return SUB_STATE_ERROR;
611                 }
612             }
613
614             s->first_packet = 0;
615             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
616                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
617                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
618                 return SUB_STATE_ERROR;
619             }
620             ret = process_message(s, &pkt);
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, PACKET *pkt)
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, pkt);
1459
1460         case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1461             return dtls_process_hello_verify(s, pkt);
1462
1463         case TLS_ST_CR_CERT:
1464             return tls_process_server_certificate(s, pkt);
1465
1466         case TLS_ST_CR_CERT_STATUS:
1467             return tls_process_cert_status(s, pkt);
1468
1469         case TLS_ST_CR_KEY_EXCH:
1470             return tls_process_key_exchange(s, pkt);
1471
1472         case TLS_ST_CR_CERT_REQ:
1473             return tls_process_certificate_request(s, pkt);
1474
1475         case TLS_ST_CR_SRVR_DONE:
1476             return tls_process_server_done(s, pkt);
1477
1478         case TLS_ST_CR_CHANGE:
1479             return tls_process_change_cipher_spec(s, pkt);
1480
1481         case TLS_ST_CR_SESSION_TICKET:
1482             return tls_process_new_session_ticket(s, pkt);
1483
1484         case TLS_ST_CR_FINISHED:
1485             return tls_process_finished(s, pkt);
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, PACKET *pkt)
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, pkt);
2176
2177     case TLS_ST_SR_CERT:
2178         return tls_process_client_certificate(s, pkt);
2179
2180     case TLS_ST_SR_KEY_EXCH:
2181         return tls_process_client_key_exchange(s, pkt);
2182
2183     case TLS_ST_SR_CERT_VRFY:
2184         return tls_process_cert_verify(s, pkt);
2185
2186 #ifndef OPENSSL_NO_NEXTPROTONEG
2187     case TLS_ST_SR_NEXT_PROTO:
2188         return tls_process_next_proto(s, pkt);
2189 #endif
2190
2191     case TLS_ST_SR_CHANGE:
2192         return tls_process_change_cipher_spec(s, pkt);
2193
2194     case TLS_ST_SR_FINISHED:
2195         return tls_process_finished(s, pkt);
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 }