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