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