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