Fix cipher support for DTLS1_BAD_VER
[openssl.git] / ssl / record / rec_layer_d1.c
1 /*
2  * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <errno.h>
12 #define USE_SOCKETS
13 #include "../ssl_locl.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include "record_locl.h"
17
18 int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
19 {
20     DTLS_RECORD_LAYER *d;
21
22     if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
23         return (0);
24
25
26     rl->d = d;
27
28     d->unprocessed_rcds.q = pqueue_new();
29     d->processed_rcds.q = pqueue_new();
30     d->buffered_app_data.q = pqueue_new();
31
32     if (d->unprocessed_rcds.q == NULL || d->processed_rcds.q == NULL
33         || d->buffered_app_data.q == NULL) {
34         pqueue_free(d->unprocessed_rcds.q);
35         pqueue_free(d->processed_rcds.q);
36         pqueue_free(d->buffered_app_data.q);
37         OPENSSL_free(d);
38         rl->d = NULL;
39         return (0);
40     }
41
42     return 1;
43 }
44
45 void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
46 {
47     DTLS_RECORD_LAYER_clear(rl);
48     pqueue_free(rl->d->unprocessed_rcds.q);
49     pqueue_free(rl->d->processed_rcds.q);
50     pqueue_free(rl->d->buffered_app_data.q);
51     OPENSSL_free(rl->d);
52     rl->d = NULL;
53 }
54
55 void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
56 {
57     DTLS_RECORD_LAYER *d;
58     pitem *item = NULL;
59     DTLS1_RECORD_DATA *rdata;
60     pqueue *unprocessed_rcds;
61     pqueue *processed_rcds;
62     pqueue *buffered_app_data;
63
64     d = rl->d;
65
66     while ((item = pqueue_pop(d->unprocessed_rcds.q)) != NULL) {
67         rdata = (DTLS1_RECORD_DATA *)item->data;
68         OPENSSL_free(rdata->rbuf.buf);
69         OPENSSL_free(item->data);
70         pitem_free(item);
71     }
72
73     while ((item = pqueue_pop(d->processed_rcds.q)) != NULL) {
74         rdata = (DTLS1_RECORD_DATA *)item->data;
75         OPENSSL_free(rdata->rbuf.buf);
76         OPENSSL_free(item->data);
77         pitem_free(item);
78     }
79
80     while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
81         rdata = (DTLS1_RECORD_DATA *)item->data;
82         OPENSSL_free(rdata->rbuf.buf);
83         OPENSSL_free(item->data);
84         pitem_free(item);
85     }
86
87     unprocessed_rcds = d->unprocessed_rcds.q;
88     processed_rcds = d->processed_rcds.q;
89     buffered_app_data = d->buffered_app_data.q;
90     memset(d, 0, sizeof(*d));
91     d->unprocessed_rcds.q = unprocessed_rcds;
92     d->processed_rcds.q = processed_rcds;
93     d->buffered_app_data.q = buffered_app_data;
94 }
95
96 void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e)
97 {
98     if (e == rl->d->w_epoch - 1) {
99         memcpy(rl->d->curr_write_sequence,
100                rl->write_sequence,
101                sizeof(rl->write_sequence));
102         memcpy(rl->write_sequence,
103                rl->d->last_write_sequence,
104                sizeof(rl->write_sequence));
105     } else if (e == rl->d->w_epoch + 1) {
106         memcpy(rl->d->last_write_sequence,
107                rl->write_sequence,
108                sizeof(unsigned char[8]));
109         memcpy(rl->write_sequence,
110                rl->d->curr_write_sequence,
111                sizeof(rl->write_sequence));
112     }
113     rl->d->w_epoch = e;
114 }
115
116 void DTLS_RECORD_LAYER_resync_write(RECORD_LAYER *rl)
117 {
118     memcpy(rl->write_sequence, rl->read_sequence, sizeof(rl->write_sequence));
119 }
120
121
122 void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
123 {
124     memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
125 }
126
127 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
128                                    int len);
129
130 /* copy buffered record into SSL structure */
131 static int dtls1_copy_record(SSL *s, pitem *item)
132 {
133     DTLS1_RECORD_DATA *rdata;
134
135     rdata = (DTLS1_RECORD_DATA *)item->data;
136
137     SSL3_BUFFER_release(&s->rlayer.rbuf);
138
139     s->rlayer.packet = rdata->packet;
140     s->rlayer.packet_length = rdata->packet_length;
141     memcpy(&s->rlayer.rbuf, &(rdata->rbuf), sizeof(SSL3_BUFFER));
142     memcpy(&s->rlayer.rrec, &(rdata->rrec), sizeof(SSL3_RECORD));
143
144     /* Set proper sequence number for mac calculation */
145     memcpy(&(s->rlayer.read_sequence[2]), &(rdata->packet[5]), 6);
146
147     return (1);
148 }
149
150 int dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
151 {
152     DTLS1_RECORD_DATA *rdata;
153     pitem *item;
154
155     /* Limit the size of the queue to prevent DOS attacks */
156     if (pqueue_size(queue->q) >= 100)
157         return 0;
158
159     rdata = OPENSSL_malloc(sizeof(*rdata));
160     item = pitem_new(priority, rdata);
161     if (rdata == NULL || item == NULL) {
162         OPENSSL_free(rdata);
163         pitem_free(item);
164         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
165         return -1;
166     }
167
168     rdata->packet = s->rlayer.packet;
169     rdata->packet_length = s->rlayer.packet_length;
170     memcpy(&(rdata->rbuf), &s->rlayer.rbuf, sizeof(SSL3_BUFFER));
171     memcpy(&(rdata->rrec), &s->rlayer.rrec, sizeof(SSL3_RECORD));
172
173     item->data = rdata;
174
175 #ifndef OPENSSL_NO_SCTP
176     /* Store bio_dgram_sctp_rcvinfo struct */
177     if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
178         (SSL_get_state(s) == TLS_ST_SR_FINISHED
179          || SSL_get_state(s) == TLS_ST_CR_FINISHED)) {
180         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
181                  sizeof(rdata->recordinfo), &rdata->recordinfo);
182     }
183 #endif
184
185     s->rlayer.packet = NULL;
186     s->rlayer.packet_length = 0;
187     memset(&s->rlayer.rbuf, 0, sizeof(s->rlayer.rbuf));
188     memset(&s->rlayer.rrec, 0, sizeof(s->rlayer.rrec));
189
190     if (!ssl3_setup_buffers(s)) {
191         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
192         OPENSSL_free(rdata->rbuf.buf);
193         OPENSSL_free(rdata);
194         pitem_free(item);
195         return (-1);
196     }
197
198     /* insert should not fail, since duplicates are dropped */
199     if (pqueue_insert(queue->q, item) == NULL) {
200         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
201         OPENSSL_free(rdata->rbuf.buf);
202         OPENSSL_free(rdata);
203         pitem_free(item);
204         return (-1);
205     }
206
207     return (1);
208 }
209
210 int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
211 {
212     pitem *item;
213
214     item = pqueue_pop(queue->q);
215     if (item) {
216         dtls1_copy_record(s, item);
217
218         OPENSSL_free(item->data);
219         pitem_free(item);
220
221         return (1);
222     }
223
224     return (0);
225 }
226
227 /*
228  * retrieve a buffered record that belongs to the new epoch, i.e., not
229  * processed yet
230  */
231 #define dtls1_get_unprocessed_record(s) \
232                    dtls1_retrieve_buffered_record((s), \
233                    &((s)->rlayer.d->unprocessed_rcds))
234
235
236 int dtls1_process_buffered_records(SSL *s)
237 {
238     pitem *item;
239
240     item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
241     if (item) {
242         /* Check if epoch is current. */
243         if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
244             return (1);         /* Nothing to do. */
245
246         /* Process all the records. */
247         while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
248             dtls1_get_unprocessed_record(s);
249             if (!dtls1_process_record(s))
250                 return (0);
251             if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
252                 SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0)
253                 return -1;
254         }
255     }
256
257     /*
258      * sync epoch numbers once all the unprocessed records have been
259      * processed
260      */
261     s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
262     s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
263
264     return (1);
265 }
266
267
268 /*-
269  * Return up to 'len' payload bytes received in 'type' records.
270  * 'type' is one of the following:
271  *
272  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
273  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
274  *   -  0 (during a shutdown, no data has to be returned)
275  *
276  * If we don't have stored data to work from, read a SSL/TLS record first
277  * (possibly multiple records if we still don't have anything to return).
278  *
279  * This function must handle any surprises the peer may have for us, such as
280  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
281  * messages are treated as if they were handshake messages *if* the |recd_type|
282  * argument is non NULL.
283  * Also if record payloads contain fragments too small to process, we store
284  * them until there is enough for the respective protocol (the record protocol
285  * may use arbitrary fragmentation and even interleaving):
286  *     Change cipher spec protocol
287  *             just 1 byte needed, no need for keeping anything stored
288  *     Alert protocol
289  *             2 bytes needed (AlertLevel, AlertDescription)
290  *     Handshake protocol
291  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
292  *             to detect unexpected Client Hello and Hello Request messages
293  *             here, anything else is handled by higher layers
294  *     Application data protocol
295  *             none of our business
296  */
297 int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
298                      int len, int peek)
299 {
300     int al, i, j, ret;
301     unsigned int n;
302     SSL3_RECORD *rr;
303     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
304
305     if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) {
306         /* Not initialized yet */
307         if (!ssl3_setup_buffers(s))
308             return (-1);
309     }
310
311     if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
312          (type != SSL3_RT_HANDSHAKE)) ||
313         (peek && (type != SSL3_RT_APPLICATION_DATA))) {
314         SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
315         return -1;
316     }
317
318     /*
319      * check whether there's a handshake message (client hello?) waiting
320      */
321     if ((ret = have_handshake_fragment(s, type, buf, len)))
322         return ret;
323
324     /*
325      * Now s->rlayer.d->handshake_fragment_len == 0 if
326      * type == SSL3_RT_HANDSHAKE.
327      */
328
329 #ifndef OPENSSL_NO_SCTP
330     /*
331      * Continue handshake if it had to be interrupted to read app data with
332      * SCTP.
333      */
334     if ((!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) ||
335         (BIO_dgram_is_sctp(SSL_get_rbio(s))
336          && ossl_statem_in_sctp_read_sock(s)
337          && s->s3->in_read_app_data != 2))
338 #else
339     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s))
340 #endif
341     {
342         /* type == SSL3_RT_APPLICATION_DATA */
343         i = s->handshake_func(s);
344         if (i < 0)
345             return (i);
346         if (i == 0) {
347             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
348             return (-1);
349         }
350     }
351
352  start:
353     s->rwstate = SSL_NOTHING;
354
355     /*-
356      * s->s3->rrec.type         - is the type of record
357      * s->s3->rrec.data,    - data
358      * s->s3->rrec.off,     - offset into 'data' for next read
359      * s->s3->rrec.length,  - number of bytes.
360      */
361     rr = s->rlayer.rrec;
362
363     /*
364      * We are not handshaking and have no data yet, so process data buffered
365      * during the last handshake in advance, if any.
366      */
367     if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) {
368         pitem *item;
369         item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
370         if (item) {
371 #ifndef OPENSSL_NO_SCTP
372             /* Restore bio_dgram_sctp_rcvinfo struct */
373             if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
374                 DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
375                 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
376                          sizeof(rdata->recordinfo), &rdata->recordinfo);
377             }
378 #endif
379
380             dtls1_copy_record(s, item);
381
382             OPENSSL_free(item->data);
383             pitem_free(item);
384         }
385     }
386
387     /* Check for timeout */
388     if (dtls1_handle_timeout(s) > 0)
389         goto start;
390
391     /* get new packet if necessary */
392     if ((SSL3_RECORD_get_length(rr) == 0)
393             || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
394         ret = dtls1_get_record(s);
395         if (ret <= 0) {
396             ret = dtls1_read_failed(s, ret);
397             /* anything other than a timeout is an error */
398             if (ret <= 0)
399                 return (ret);
400             else
401                 goto start;
402         }
403     }
404
405     /* we now have a packet which can be read and processed */
406
407     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
408                                    * reset by ssl3_get_finished */
409         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
410         /*
411          * We now have application data between CCS and Finished. Most likely
412          * the packets were reordered on their way, so buffer the application
413          * data for later processing rather than dropping the connection.
414          */
415         if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data),
416             SSL3_RECORD_get_seq_num(rr)) < 0) {
417             SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
418             return -1;
419         }
420         SSL3_RECORD_set_length(rr, 0);
421         goto start;
422     }
423
424     /*
425      * If the other end has shut down, throw anything we read away (even in
426      * 'peek' mode)
427      */
428     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
429         SSL3_RECORD_set_length(rr, 0);
430         s->rwstate = SSL_NOTHING;
431         return (0);
432     }
433
434     if (type == SSL3_RECORD_get_type(rr)
435             || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
436                 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
437         /*
438          * SSL3_RT_APPLICATION_DATA or
439          * SSL3_RT_HANDSHAKE or
440          * SSL3_RT_CHANGE_CIPHER_SPEC
441          */
442         /*
443          * make sure that we are not getting application data when we are
444          * doing a handshake for the first time
445          */
446         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
447             (s->enc_read_ctx == NULL)) {
448             al = SSL_AD_UNEXPECTED_MESSAGE;
449             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
450             goto f_err;
451         }
452
453         if (recvd_type != NULL)
454             *recvd_type = SSL3_RECORD_get_type(rr);
455
456         if (len <= 0)
457             return (len);
458
459         if ((unsigned int)len > SSL3_RECORD_get_length(rr))
460             n = SSL3_RECORD_get_length(rr);
461         else
462             n = (unsigned int)len;
463
464         memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
465         if (!peek) {
466             SSL3_RECORD_sub_length(rr, n);
467             SSL3_RECORD_add_off(rr, n);
468             if (SSL3_RECORD_get_length(rr) == 0) {
469                 s->rlayer.rstate = SSL_ST_READ_HEADER;
470                 SSL3_RECORD_set_off(rr, 0);
471             }
472         }
473 #ifndef OPENSSL_NO_SCTP
474         /*
475          * We were about to renegotiate but had to read belated application
476          * data first, so retry.
477          */
478         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
479             SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA &&
480             ossl_statem_in_sctp_read_sock(s)) {
481             s->rwstate = SSL_READING;
482             BIO_clear_retry_flags(SSL_get_rbio(s));
483             BIO_set_retry_read(SSL_get_rbio(s));
484         }
485
486         /*
487          * We might had to delay a close_notify alert because of reordered
488          * app data. If there was an alert and there is no message to read
489          * anymore, finally set shutdown.
490          */
491         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
492             s->d1->shutdown_received
493             && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
494             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
495             return (0);
496         }
497 #endif
498         return (n);
499     }
500
501     /*
502      * If we get here, then type != rr->type; if we have a handshake message,
503      * then it was unexpected (Hello Request or Client Hello).
504      */
505
506     /*
507      * In case of record types for which we have 'fragment' storage, fill
508      * that so that we can process the data at a fixed place.
509      */
510     {
511         unsigned int k, dest_maxlen = 0;
512         unsigned char *dest = NULL;
513         unsigned int *dest_len = NULL;
514
515         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
516             dest_maxlen = sizeof s->rlayer.d->handshake_fragment;
517             dest = s->rlayer.d->handshake_fragment;
518             dest_len = &s->rlayer.d->handshake_fragment_len;
519         } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
520             dest_maxlen = sizeof(s->rlayer.d->alert_fragment);
521             dest = s->rlayer.d->alert_fragment;
522             dest_len = &s->rlayer.d->alert_fragment_len;
523         }
524 #ifndef OPENSSL_NO_HEARTBEATS
525         else if (SSL3_RECORD_get_type(rr) == DTLS1_RT_HEARTBEAT) {
526             /* We allow a 0 return */
527             if (dtls1_process_heartbeat(s, SSL3_RECORD_get_data(rr),
528                     SSL3_RECORD_get_length(rr)) < 0) {
529                 return -1;
530             }
531             /* Exit and notify application to read again */
532             SSL3_RECORD_set_length(rr, 0);
533             s->rwstate = SSL_READING;
534             BIO_clear_retry_flags(SSL_get_rbio(s));
535             BIO_set_retry_read(SSL_get_rbio(s));
536             return (-1);
537         }
538 #endif
539         /* else it's a CCS message, or application data or wrong */
540         else if (SSL3_RECORD_get_type(rr) != SSL3_RT_CHANGE_CIPHER_SPEC) {
541             /*
542              * Application data while renegotiating is allowed. Try again
543              * reading.
544              */
545             if (SSL3_RECORD_get_type(rr)  == SSL3_RT_APPLICATION_DATA) {
546                 BIO *bio;
547                 s->s3->in_read_app_data = 2;
548                 bio = SSL_get_rbio(s);
549                 s->rwstate = SSL_READING;
550                 BIO_clear_retry_flags(bio);
551                 BIO_set_retry_read(bio);
552                 return (-1);
553             }
554
555             /* Not certain if this is the right error handling */
556             al = SSL_AD_UNEXPECTED_MESSAGE;
557             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
558             goto f_err;
559         }
560
561         if (dest_maxlen > 0) {
562             /*
563              * XDTLS: In a pathological case, the Client Hello may be
564              * fragmented--don't always expect dest_maxlen bytes
565              */
566             if (SSL3_RECORD_get_length(rr)  < dest_maxlen) {
567 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
568                 /*
569                  * for normal alerts rr->length is 2, while
570                  * dest_maxlen is 7 if we were to handle this
571                  * non-existing alert...
572                  */
573                 FIX ME
574 #endif
575                 s->rlayer.rstate = SSL_ST_READ_HEADER;
576                 SSL3_RECORD_set_length(rr, 0);
577                 goto start;
578             }
579
580             /* now move 'n' bytes: */
581             for (k = 0; k < dest_maxlen; k++) {
582                 dest[k] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
583                 SSL3_RECORD_add_off(rr, 1);
584                 SSL3_RECORD_add_length(rr, -1);
585             }
586             *dest_len = dest_maxlen;
587         }
588     }
589
590     /*-
591      * s->rlayer.d->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
592      * s->rlayer.d->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
593      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
594      */
595
596     /* If we are a client, check for an incoming 'Hello Request': */
597     if ((!s->server) &&
598         (s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
599         (s->rlayer.d->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
600         (s->session != NULL) && (s->session->cipher != NULL)) {
601         s->rlayer.d->handshake_fragment_len = 0;
602
603         if ((s->rlayer.d->handshake_fragment[1] != 0) ||
604             (s->rlayer.d->handshake_fragment[2] != 0) ||
605             (s->rlayer.d->handshake_fragment[3] != 0)) {
606             al = SSL_AD_DECODE_ERROR;
607             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
608             goto f_err;
609         }
610
611         /*
612          * no need to check sequence number on HELLO REQUEST messages
613          */
614
615         if (s->msg_callback)
616             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
617                             s->rlayer.d->handshake_fragment, 4, s,
618                             s->msg_callback_arg);
619
620         if (SSL_is_init_finished(s) &&
621             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
622             !s->s3->renegotiate) {
623             s->d1->handshake_read_seq++;
624             s->new_session = 1;
625             ssl3_renegotiate(s);
626             if (ssl3_renegotiate_check(s)) {
627                 i = s->handshake_func(s);
628                 if (i < 0)
629                     return (i);
630                 if (i == 0) {
631                     SSLerr(SSL_F_DTLS1_READ_BYTES,
632                            SSL_R_SSL_HANDSHAKE_FAILURE);
633                     return (-1);
634                 }
635
636                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
637                     if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
638                         /* no read-ahead left? */
639                         BIO *bio;
640                         /*
641                          * In the case where we try to read application data,
642                          * but we trigger an SSL handshake, we return -1 with
643                          * the retry option set.  Otherwise renegotiation may
644                          * cause nasty problems in the blocking world
645                          */
646                         s->rwstate = SSL_READING;
647                         bio = SSL_get_rbio(s);
648                         BIO_clear_retry_flags(bio);
649                         BIO_set_retry_read(bio);
650                         return (-1);
651                     }
652                 }
653             }
654         }
655         /*
656          * we either finished a handshake or ignored the request, now try
657          * again to obtain the (application) data we were asked for
658          */
659         goto start;
660     }
661
662     if (s->rlayer.d->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
663         int alert_level = s->rlayer.d->alert_fragment[0];
664         int alert_descr = s->rlayer.d->alert_fragment[1];
665
666         s->rlayer.d->alert_fragment_len = 0;
667
668         if (s->msg_callback)
669             s->msg_callback(0, s->version, SSL3_RT_ALERT,
670                             s->rlayer.d->alert_fragment, 2, s,
671                             s->msg_callback_arg);
672
673         if (s->info_callback != NULL)
674             cb = s->info_callback;
675         else if (s->ctx->info_callback != NULL)
676             cb = s->ctx->info_callback;
677
678         if (cb != NULL) {
679             j = (alert_level << 8) | alert_descr;
680             cb(s, SSL_CB_READ_ALERT, j);
681         }
682
683         if (alert_level == SSL3_AL_WARNING) {
684             s->s3->warn_alert = alert_descr;
685             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
686 #ifndef OPENSSL_NO_SCTP
687                 /*
688                  * With SCTP and streams the socket may deliver app data
689                  * after a close_notify alert. We have to check this first so
690                  * that nothing gets discarded.
691                  */
692                 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
693                     BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
694                     s->d1->shutdown_received = 1;
695                     s->rwstate = SSL_READING;
696                     BIO_clear_retry_flags(SSL_get_rbio(s));
697                     BIO_set_retry_read(SSL_get_rbio(s));
698                     return -1;
699                 }
700 #endif
701                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
702                 return (0);
703             }
704 #if 0
705             /* XXX: this is a possible improvement in the future */
706             /* now check if it's a missing record */
707             if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
708                 unsigned short seq;
709                 unsigned int frag_off;
710                 unsigned char *p = &(s->rlayer.d->alert_fragment[2]);
711
712                 n2s(p, seq);
713                 n2l3(p, frag_off);
714
715                 dtls1_retransmit_message(s,
716                                          dtls1_get_queue_priority
717                                          (frag->msg_header.seq, 0), frag_off,
718                                          &found);
719                 if (!found && SSL_in_init(s)) {
720                     /*
721                      * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
722                      */
723                     /*
724                      * requested a message not yet sent, send an alert
725                      * ourselves
726                      */
727                     ssl3_send_alert(s, SSL3_AL_WARNING,
728                                     DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
729                 }
730             }
731 #endif
732         } else if (alert_level == SSL3_AL_FATAL) {
733             char tmp[16];
734
735             s->rwstate = SSL_NOTHING;
736             s->s3->fatal_alert = alert_descr;
737             SSLerr(SSL_F_DTLS1_READ_BYTES,
738                    SSL_AD_REASON_OFFSET + alert_descr);
739             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
740             ERR_add_error_data(2, "SSL alert number ", tmp);
741             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
742             SSL_CTX_remove_session(s->session_ctx, s->session);
743             return (0);
744         } else {
745             al = SSL_AD_ILLEGAL_PARAMETER;
746             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
747             goto f_err;
748         }
749
750         goto start;
751     }
752
753     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
754                                             * shutdown */
755         s->rwstate = SSL_NOTHING;
756         SSL3_RECORD_set_length(rr, 0);
757         return (0);
758     }
759
760     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
761         /*
762          * We can't process a CCS now, because previous handshake messages
763          * are still missing, so just drop it.
764          */
765         SSL3_RECORD_set_length(rr, 0);
766         goto start;
767     }
768
769     /*
770      * Unexpected handshake message (Client Hello, or protocol violation)
771      */
772     if ((s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
773         !ossl_statem_get_in_handshake(s)) {
774         struct hm_header_st msg_hdr;
775
776         /* this may just be a stale retransmit */
777         dtls1_get_message_header(rr->data, &msg_hdr);
778         if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch) {
779             SSL3_RECORD_set_length(rr, 0);
780             goto start;
781         }
782
783         /*
784          * If we are server, we may have a repeated FINISHED of the client
785          * here, then retransmit our CCS and FINISHED.
786          */
787         if (msg_hdr.type == SSL3_MT_FINISHED) {
788             if (dtls1_check_timeout_num(s) < 0)
789                 return -1;
790
791             dtls1_retransmit_buffered_messages(s);
792             SSL3_RECORD_set_length(rr, 0);
793             goto start;
794         }
795
796         if (SSL_is_init_finished(s) &&
797             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
798             ossl_statem_set_in_init(s, 1);
799             s->renegotiate = 1;
800             s->new_session = 1;
801         }
802         i = s->handshake_func(s);
803         if (i < 0)
804             return (i);
805         if (i == 0) {
806             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
807             return (-1);
808         }
809
810         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
811             if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
812                 /* no read-ahead left? */
813                 BIO *bio;
814                 /*
815                  * In the case where we try to read application data, but we
816                  * trigger an SSL handshake, we return -1 with the retry
817                  * option set.  Otherwise renegotiation may cause nasty
818                  * problems in the blocking world
819                  */
820                 s->rwstate = SSL_READING;
821                 bio = SSL_get_rbio(s);
822                 BIO_clear_retry_flags(bio);
823                 BIO_set_retry_read(bio);
824                 return (-1);
825             }
826         }
827         goto start;
828     }
829
830     switch (SSL3_RECORD_get_type(rr)) {
831     default:
832         /* TLS just ignores unknown message types */
833         if (s->version == TLS1_VERSION) {
834             SSL3_RECORD_set_length(rr, 0);
835             goto start;
836         }
837         al = SSL_AD_UNEXPECTED_MESSAGE;
838         SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
839         goto f_err;
840     case SSL3_RT_CHANGE_CIPHER_SPEC:
841     case SSL3_RT_ALERT:
842     case SSL3_RT_HANDSHAKE:
843         /*
844          * we already handled all of these, with the possible exception of
845          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
846          * that should not happen when type != rr->type
847          */
848         al = SSL_AD_UNEXPECTED_MESSAGE;
849         SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
850         goto f_err;
851     case SSL3_RT_APPLICATION_DATA:
852         /*
853          * At this point, we were expecting handshake data, but have
854          * application data.  If the library was running inside ssl3_read()
855          * (i.e. in_read_app_data is set) and it makes sense to read
856          * application data at this point (session renegotiation not yet
857          * started), we will indulge it.
858          */
859         if (s->s3->in_read_app_data &&
860             (s->s3->total_renegotiations != 0) &&
861             ossl_statem_app_data_allowed(s)) {
862             s->s3->in_read_app_data = 2;
863             return (-1);
864         } else {
865             al = SSL_AD_UNEXPECTED_MESSAGE;
866             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
867             goto f_err;
868         }
869     }
870     /* not reached */
871
872  f_err:
873     ssl3_send_alert(s, SSL3_AL_FATAL, al);
874     return (-1);
875 }
876
877
878         /*
879          * this only happens when a client hello is received and a handshake
880          * is started.
881          */
882 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
883                                    int len)
884 {
885
886     if ((type == SSL3_RT_HANDSHAKE)
887             && (s->rlayer.d->handshake_fragment_len > 0))
888         /* (partially) satisfy request from storage */
889     {
890         unsigned char *src = s->rlayer.d->handshake_fragment;
891         unsigned char *dst = buf;
892         unsigned int k, n;
893
894         /* peek == 0 */
895         n = 0;
896         while ((len > 0) && (s->rlayer.d->handshake_fragment_len > 0)) {
897             *dst++ = *src++;
898             len--;
899             s->rlayer.d->handshake_fragment_len--;
900             n++;
901         }
902         /* move any remaining fragment bytes: */
903         for (k = 0; k < s->rlayer.d->handshake_fragment_len; k++)
904             s->rlayer.d->handshake_fragment[k] = *src++;
905         return n;
906     }
907
908     return 0;
909 }
910
911 /*
912  * Call this to write data in records of type 'type' It will return <= 0 if
913  * not all data has been sent or non-blocking IO.
914  */
915 int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
916 {
917     int i;
918
919     OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
920     s->rwstate = SSL_NOTHING;
921     i = do_dtls1_write(s, type, buf, len, 0);
922     return i;
923 }
924
925 int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
926                    unsigned int len, int create_empty_fragment)
927 {
928     unsigned char *p, *pseq;
929     int i, mac_size, clear = 0;
930     int prefix_len = 0;
931     int eivlen;
932     SSL3_RECORD wr;
933     SSL3_BUFFER *wb;
934     SSL_SESSION *sess;
935
936     wb = &s->rlayer.wbuf[0];
937
938     /*
939      * first check if there is a SSL3_BUFFER still being written out.  This
940      * will happen with non blocking IO
941      */
942     if (SSL3_BUFFER_get_left(wb) != 0) {
943         OPENSSL_assert(0);      /* XDTLS: want to see if we ever get here */
944         return (ssl3_write_pending(s, type, buf, len));
945     }
946
947     /* If we have an alert to send, lets send it */
948     if (s->s3->alert_dispatch) {
949         i = s->method->ssl_dispatch_alert(s);
950         if (i <= 0)
951             return (i);
952         /* if it went, fall through and send more stuff */
953     }
954
955     if (len == 0 && !create_empty_fragment)
956         return 0;
957
958     sess = s->session;
959
960     if ((sess == NULL) ||
961         (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
962         clear = 1;
963
964     if (clear)
965         mac_size = 0;
966     else {
967         mac_size = EVP_MD_CTX_size(s->write_hash);
968         if (mac_size < 0)
969             goto err;
970     }
971
972     p = SSL3_BUFFER_get_buf(wb) + prefix_len;
973
974     /* write the header */
975
976     *(p++) = type & 0xff;
977     SSL3_RECORD_set_type(&wr, type);
978     /*
979      * Special case: for hello verify request, client version 1.0 and we
980      * haven't decided which version to use yet send back using version 1.0
981      * header: otherwise some clients will ignore it.
982      */
983     if (s->method->version == DTLS_ANY_VERSION) {
984         *(p++) = DTLS1_VERSION >> 8;
985         *(p++) = DTLS1_VERSION & 0xff;
986     } else {
987         *(p++) = s->version >> 8;
988         *(p++) = s->version & 0xff;
989     }
990
991     /* field where we are to write out packet epoch, seq num and len */
992     pseq = p;
993     p += 10;
994
995     /* Explicit IV length, block ciphers appropriate version flag */
996     if (s->enc_write_ctx) {
997         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
998         if (mode == EVP_CIPH_CBC_MODE) {
999             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
1000             if (eivlen <= 1)
1001                 eivlen = 0;
1002         }
1003         /* Need explicit part of IV for GCM mode */
1004         else if (mode == EVP_CIPH_GCM_MODE)
1005             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1006         else if (mode == EVP_CIPH_CCM_MODE)
1007             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1008         else
1009             eivlen = 0;
1010     } else
1011         eivlen = 0;
1012
1013     /* lets setup the record stuff. */
1014     SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
1015     SSL3_RECORD_set_length(&wr, (int)len);
1016     SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
1017
1018     /*
1019      * we now 'read' from wr.input, wr.length bytes into wr.data
1020      */
1021
1022     /* first we compress */
1023     if (s->compress != NULL) {
1024         if (!ssl3_do_compress(s, &wr)) {
1025             SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
1026             goto err;
1027         }
1028     } else {
1029         memcpy(SSL3_RECORD_get_data(&wr), SSL3_RECORD_get_input(&wr),
1030                SSL3_RECORD_get_length(&wr));
1031         SSL3_RECORD_reset_input(&wr);
1032     }
1033
1034     /*
1035      * we should still have the output to wr.data and the input from
1036      * wr.input.  Length should be wr.length. wr.data still points in the
1037      * wb->buf
1038      */
1039
1040     if (mac_size != 0) {
1041         if (s->method->ssl3_enc->mac(s, &wr,
1042                 &(p[SSL3_RECORD_get_length(&wr) + eivlen]), 1) < 0)
1043             goto err;
1044         SSL3_RECORD_add_length(&wr, mac_size);
1045     }
1046
1047     /* this is true regardless of mac size */
1048     SSL3_RECORD_set_data(&wr, p);
1049     SSL3_RECORD_reset_input(&wr);
1050
1051     if (eivlen)
1052         SSL3_RECORD_add_length(&wr, eivlen);
1053
1054     if (s->method->ssl3_enc->enc(s, &wr, 1, 1) < 1)
1055         goto err;
1056
1057     /* record length after mac and block padding */
1058     /*
1059      * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
1060      * SSL_in_init(s)))
1061      */
1062
1063     /* there's only one epoch between handshake and app data */
1064
1065     s2n(s->rlayer.d->w_epoch, pseq);
1066
1067     /* XDTLS: ?? */
1068     /*
1069      * else s2n(s->d1->handshake_epoch, pseq);
1070      */
1071
1072     memcpy(pseq, &(s->rlayer.write_sequence[2]), 6);
1073     pseq += 6;
1074     s2n(SSL3_RECORD_get_length(&wr), pseq);
1075
1076     if (s->msg_callback)
1077         s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
1078                         DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
1079
1080     /*
1081      * we should now have wr.data pointing to the encrypted data, which is
1082      * wr->length long
1083      */
1084     SSL3_RECORD_set_type(&wr, type); /* not needed but helps for debugging */
1085     SSL3_RECORD_add_length(&wr, DTLS1_RT_HEADER_LENGTH);
1086
1087     ssl3_record_sequence_update(&(s->rlayer.write_sequence[0]));
1088
1089     if (create_empty_fragment) {
1090         /*
1091          * we are in a recursive call; just return the length, don't write
1092          * out anything here
1093          */
1094         return wr.length;
1095     }
1096
1097     /* now let's set up wb */
1098     SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(&wr));
1099     SSL3_BUFFER_set_offset(wb, 0);
1100
1101     /*
1102      * memorize arguments so that ssl3_write_pending can detect bad write
1103      * retries later
1104      */
1105     s->rlayer.wpend_tot = len;
1106     s->rlayer.wpend_buf = buf;
1107     s->rlayer.wpend_type = type;
1108     s->rlayer.wpend_ret = len;
1109
1110     /* we now just need to write the buffer */
1111     return ssl3_write_pending(s, type, buf, len);
1112  err:
1113     return -1;
1114 }
1115
1116 DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1117                                       unsigned int *is_next_epoch)
1118 {
1119
1120     *is_next_epoch = 0;
1121
1122     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1123     if (rr->epoch == s->rlayer.d->r_epoch)
1124         return &s->rlayer.d->bitmap;
1125
1126     /* Only HM and ALERT messages can be from the next epoch */
1127     else if (rr->epoch == (unsigned long)(s->rlayer.d->r_epoch + 1) &&
1128             (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1129         *is_next_epoch = 1;
1130         return &s->rlayer.d->next_bitmap;
1131     }
1132
1133     return NULL;
1134 }
1135
1136 void dtls1_reset_seq_numbers(SSL *s, int rw)
1137 {
1138     unsigned char *seq;
1139     unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
1140
1141     if (rw & SSL3_CC_READ) {
1142         seq = s->rlayer.read_sequence;
1143         s->rlayer.d->r_epoch++;
1144         memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
1145                sizeof(s->rlayer.d->bitmap));
1146         memset(&s->rlayer.d->next_bitmap, 0,
1147                sizeof(s->rlayer.d->next_bitmap));
1148     } else {
1149         seq = s->rlayer.write_sequence;
1150         memcpy(s->rlayer.d->last_write_sequence, seq,
1151                sizeof(s->rlayer.write_sequence));
1152         s->rlayer.d->w_epoch++;
1153     }
1154
1155     memset(seq, 0, seq_bytes);
1156 }