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