1 /* DTLS implementation written by Nagendra Modadugu
2  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */
3 /* ====================================================================
4  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  *
18  * 3. All advertising materials mentioning features or use of this
19  *    software must display the following acknowledgment:
20  *    "This product includes software developed by the OpenSSL Project
21  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22  *
23  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
24  *    endorse or promote products derived from this software without
25  *    prior written permission. For written permission, please contact
26  *    openssl-core@openssl.org.
27  *
28  * 5. Products derived from this software may not be called "OpenSSL"
29  *    nor may "OpenSSL" appear in their names without prior written
30  *    permission of the OpenSSL Project.
31  *
32  * 6. Redistributions of any form whatsoever must retain the following
33  *    acknowledgment:
34  *    "This product includes software developed by the OpenSSL Project
35  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36  *
37  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
38  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
40  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
43  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
46  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
48  * OF THE POSSIBILITY OF SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This product includes cryptographic software written by Eric Young
52  * (eay@cryptsoft.com).  This product includes software written by Tim
53  * Hudson (tjh@cryptsoft.com).
54  *
55  */
56 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
57  * All rights reserved.
58  *
59  * This package is an SSL implementation written
60  * by Eric Young (eay@cryptsoft.com).
61  * The implementation was written so as to conform with Netscapes SSL.
62  *
63  * This library is free for commercial and non-commercial use as long as
64  * the following conditions are aheared to.  The following conditions
65  * apply to all code found in this distribution, be it the RC4, RSA,
66  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
67  * included with this distribution is covered by the same copyright terms
68  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
69  *
70  * Copyright remains Eric Young's, and as such any Copyright notices in
71  * the code are not to be removed.
72  * If this package is used in a product, Eric Young should be given attribution
73  * as the author of the parts of the library used.
74  * This can be in the form of a textual message at program startup or
75  * in documentation (online or textual) provided with the package.
76  *
77  * Redistribution and use in source and binary forms, with or without
78  * modification, are permitted provided that the following conditions
79  * are met:
80  * 1. Redistributions of source code must retain the copyright
81  *    notice, this list of conditions and the following disclaimer.
82  * 2. Redistributions in binary form must reproduce the above copyright
83  *    notice, this list of conditions and the following disclaimer in the
84  *    documentation and/or other materials provided with the distribution.
85  * 3. All advertising materials mentioning features or use of this software
86  *    must display the following acknowledgement:
87  *    "This product includes cryptographic software written by
88  *     Eric Young (eay@cryptsoft.com)"
89  *    The word 'cryptographic' can be left out if the rouines from the library
90  *    being used are not cryptographic related :-).
91  * 4. If you include any Windows specific code (or a derivative thereof) from
92  *    the apps directory (application code) you must include an acknowledgement:
93  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
94  *
95  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
96  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
97  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
98  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
99  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
100  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
101  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
103  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
104  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
105  * SUCH DAMAGE.
106  *
107  * The licence and distribution terms for any publically available version or
108  * derivative of this code cannot be changed.  i.e. this code cannot simply be
109  * copied and put under another distribution licence
110  * [including the GNU Public Licence.] */
111 
112 #include <assert.h>
113 #include <stdio.h>
114 #include <string.h>
115 
116 #include <openssl/buf.h>
117 #include <openssl/mem.h>
118 #include <openssl/evp.h>
119 #include <openssl/err.h>
120 #include <openssl/rand.h>
121 
122 #include "internal.h"
123 
124 
125 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
satsub64be(const uint8_t * v1,const uint8_t * v2)126 static int satsub64be(const uint8_t *v1, const uint8_t *v2) {
127   int ret, sat, brw, i;
128 
129   if (sizeof(long) == 8) {
130     do {
131       const union {
132         long one;
133         char little;
134       } is_endian = {1};
135       long l;
136 
137       if (is_endian.little) {
138         break;
139       }
140       /* not reached on little-endians */
141       /* following test is redundant, because input is
142        * always aligned, but I take no chances... */
143       if (((size_t)v1 | (size_t)v2) & 0x7) {
144         break;
145       }
146 
147       l = *((long *)v1);
148       l -= *((long *)v2);
149       if (l > 128) {
150         return 128;
151       } else if (l < -128) {
152         return -128;
153       } else {
154         return (int)l;
155       }
156     } while (0);
157   }
158 
159   ret = (int)v1[7] - (int)v2[7];
160   sat = 0;
161   brw = ret >> 8; /* brw is either 0 or -1 */
162   if (ret & 0x80) {
163     for (i = 6; i >= 0; i--) {
164       brw += (int)v1[i] - (int)v2[i];
165       sat |= ~brw;
166       brw >>= 8;
167     }
168   } else {
169     for (i = 6; i >= 0; i--) {
170       brw += (int)v1[i] - (int)v2[i];
171       sat |= brw;
172       brw >>= 8;
173     }
174   }
175   brw <<= 8; /* brw is either 0 or -256 */
176 
177   if (sat & 0xff) {
178     return brw | 0x80;
179   } else {
180     return brw + (ret & 0xFF);
181   }
182 }
183 
184 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
185 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
186 static int dtls1_process_record(SSL *s);
187 static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
188                           unsigned int len, enum dtls1_use_epoch_t use_epoch);
189 
dtls1_process_record(SSL * s)190 static int dtls1_process_record(SSL *s) {
191   int al;
192   SSL3_RECORD *rr = &s->s3->rrec;
193 
194   /* check is not needed I believe */
195   if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
196     al = SSL_AD_RECORD_OVERFLOW;
197     OPENSSL_PUT_ERROR(SSL, dtls1_process_record,
198                       SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
199     goto f_err;
200   }
201 
202   /* |rr->data| points to |rr->length| bytes of ciphertext in |s->packet|. */
203   rr->data = &s->packet[DTLS1_RT_HEADER_LENGTH];
204 
205   uint8_t seq[8];
206   seq[0] = rr->epoch >> 8;
207   seq[1] = rr->epoch & 0xff;
208   memcpy(&seq[2], &rr->seq_num[2], 6);
209 
210   /* Decrypt the packet in-place. Note it is important that |SSL_AEAD_CTX_open|
211    * not write beyond |rr->length|. There may be another record in the packet.
212    *
213    * TODO(davidben): This assumes |s->version| is the same as the record-layer
214    * version which isn't always true, but it only differs with the NULL cipher
215    * which ignores the parameter. */
216   size_t plaintext_len;
217   if (!SSL_AEAD_CTX_open(s->aead_read_ctx, rr->data, &plaintext_len, rr->length,
218                          rr->type, s->version, seq, rr->data, rr->length)) {
219     /* Bad packets are silently dropped in DTLS. Clear the error queue of any
220      * errors decryption may have added. */
221     ERR_clear_error();
222     rr->length = 0;
223     s->packet_length = 0;
224     goto err;
225   }
226 
227   if (plaintext_len > SSL3_RT_MAX_PLAIN_LENGTH) {
228     al = SSL_AD_RECORD_OVERFLOW;
229     OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_DATA_LENGTH_TOO_LONG);
230     goto f_err;
231   }
232   assert(plaintext_len < (1u << 16));
233   rr->length = plaintext_len;
234 
235   rr->off = 0;
236   /* So at this point the following is true
237    * ssl->s3->rrec.type 	is the type of record
238    * ssl->s3->rrec.length	== number of bytes in record
239    * ssl->s3->rrec.off	== offset to first valid byte
240    * ssl->s3->rrec.data	== the first byte of the record body. */
241 
242   /* we have pulled in a full packet so zero things */
243   s->packet_length = 0;
244   return 1;
245 
246 f_err:
247   ssl3_send_alert(s, SSL3_AL_FATAL, al);
248 
249 err:
250   return 0;
251 }
252 
253 /* Call this to get a new input record.
254  * It will return <= 0 if more data is needed, normally due to an error
255  * or non-blocking IO.
256  * When it finishes, one packet has been decoded and can be found in
257  * ssl->s3->rrec.type    - is the type of record
258  * ssl->s3->rrec.data,   - data
259  * ssl->s3->rrec.length, - number of bytes
260  *
261  * used only by dtls1_read_bytes */
dtls1_get_record(SSL * s)262 int dtls1_get_record(SSL *s) {
263   uint8_t ssl_major, ssl_minor;
264   int n;
265   SSL3_RECORD *rr;
266   uint8_t *p = NULL;
267   uint16_t version;
268 
269   rr = &(s->s3->rrec);
270 
271   /* get something from the wire */
272 again:
273   /* check if we have the header */
274   if ((s->rstate != SSL_ST_READ_BODY) ||
275       (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
276     n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, 0);
277     /* read timeout is handled by dtls1_read_bytes */
278     if (n <= 0) {
279       return n; /* error or non-blocking */
280     }
281 
282     /* this packet contained a partial record, dump it */
283     if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
284       s->packet_length = 0;
285       goto again;
286     }
287 
288     s->rstate = SSL_ST_READ_BODY;
289 
290     p = s->packet;
291 
292     if (s->msg_callback) {
293       s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s,
294                       s->msg_callback_arg);
295     }
296 
297     /* Pull apart the header into the DTLS1_RECORD */
298     rr->type = *(p++);
299     ssl_major = *(p++);
300     ssl_minor = *(p++);
301     version = (((uint16_t)ssl_major) << 8) | ssl_minor;
302 
303     /* sequence number is 64 bits, with top 2 bytes = epoch */
304     n2s(p, rr->epoch);
305 
306     memcpy(&(s->s3->read_sequence[2]), p, 6);
307     p += 6;
308 
309     n2s(p, rr->length);
310 
311     /* Lets check version */
312     if (s->s3->have_version) {
313       if (version != s->version) {
314         /* The record's version doesn't match, so silently drop it.
315          *
316          * TODO(davidben): This doesn't work. The DTLS record layer is not
317          * packet-based, so the remainder of the packet isn't dropped and we
318          * get a framing error. It's also unclear what it means to silently
319          * drop a record in a packet containing two records. */
320         rr->length = 0;
321         s->packet_length = 0;
322         goto again;
323       }
324     }
325 
326     if ((version & 0xff00) != (s->version & 0xff00)) {
327       /* wrong version, silently discard record */
328       rr->length = 0;
329       s->packet_length = 0;
330       goto again;
331     }
332 
333     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
334       /* record too long, silently discard it */
335       rr->length = 0;
336       s->packet_length = 0;
337       goto again;
338     }
339 
340     /* now s->rstate == SSL_ST_READ_BODY */
341   }
342 
343   /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
344 
345   if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
346     /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
347     n = ssl3_read_n(s, rr->length, 1);
348     /* This packet contained a partial record, dump it. */
349     if (n != rr->length) {
350       rr->length = 0;
351       s->packet_length = 0;
352       goto again;
353     }
354 
355     /* now n == rr->length,
356      * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
357   }
358   s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
359 
360   if (rr->epoch != s->d1->r_epoch) {
361     /* This record is from the wrong epoch. If it is the next epoch, it could be
362      * buffered. For simplicity, drop it and expect retransmit to handle it
363      * later; DTLS is supposed to handle packet loss. */
364     rr->length = 0;
365     s->packet_length = 0;
366     goto again;
367   }
368 
369   /* Check whether this is a repeat, or aged record. */
370   if (!dtls1_record_replay_check(s, &s->d1->bitmap)) {
371     rr->length = 0;
372     s->packet_length = 0; /* dump this record */
373     goto again;           /* get another record */
374   }
375 
376   /* just read a 0 length packet */
377   if (rr->length == 0) {
378     goto again;
379   }
380 
381   if (!dtls1_process_record(s)) {
382     rr->length = 0;
383     s->packet_length = 0; /* dump this record */
384     goto again;           /* get another record */
385   }
386   dtls1_record_bitmap_update(s, &s->d1->bitmap); /* Mark receipt of record. */
387 
388   return 1;
389 }
390 
dtls1_read_app_data(SSL * ssl,uint8_t * buf,int len,int peek)391 int dtls1_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
392   return dtls1_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
393 }
394 
dtls1_read_close_notify(SSL * ssl)395 void dtls1_read_close_notify(SSL *ssl) {
396   dtls1_read_bytes(ssl, 0, NULL, 0, 0);
397 }
398 
399 /* Return up to 'len' payload bytes received in 'type' records.
400  * 'type' is one of the following:
401  *
402  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
403  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
404  *   -  0 (during a shutdown, no data has to be returned)
405  *
406  * If we don't have stored data to work from, read a SSL/TLS record first
407  * (possibly multiple records if we still don't have anything to return).
408  *
409  * This function must handle any surprises the peer may have for us, such as
410  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
411  * a surprise, but handled as if it were), or renegotiation requests.
412  * Also if record payloads contain fragments too small to process, we store
413  * them until there is enough for the respective protocol (the record protocol
414  * may use arbitrary fragmentation and even interleaving):
415  *     Change cipher spec protocol
416  *             just 1 byte needed, no need for keeping anything stored
417  *     Alert protocol
418  *             2 bytes needed (AlertLevel, AlertDescription)
419  *     Handshake protocol
420  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
421  *             to detect unexpected Client Hello and Hello Request messages
422  *             here, anything else is handled by higher layers
423  *     Application data protocol
424  *             none of our business
425  */
dtls1_read_bytes(SSL * s,int type,unsigned char * buf,int len,int peek)426 int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) {
427   int al, i, ret;
428   unsigned int n;
429   SSL3_RECORD *rr;
430   void (*cb)(const SSL *ssl, int type2, int val) = NULL;
431 
432   /* XXX: check what the second '&& type' is about */
433   if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
434        (type != SSL3_RT_HANDSHAKE) && type) ||
435       (peek && (type != SSL3_RT_APPLICATION_DATA))) {
436     OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
437     return -1;
438   }
439 
440   if (!s->in_handshake && SSL_in_init(s)) {
441     /* type == SSL3_RT_APPLICATION_DATA */
442     i = s->handshake_func(s);
443     if (i < 0) {
444       return i;
445     }
446     if (i == 0) {
447       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
448       return -1;
449     }
450   }
451 
452 start:
453   s->rwstate = SSL_NOTHING;
454 
455   /* s->s3->rrec.type     - is the type of record
456    * s->s3->rrec.data     - data
457    * s->s3->rrec.off      - offset into 'data' for next read
458    * s->s3->rrec.length   - number of bytes. */
459   rr = &s->s3->rrec;
460 
461   /* Check for timeout */
462   if (DTLSv1_handle_timeout(s) > 0) {
463     goto start;
464   }
465 
466   /* get new packet if necessary */
467   if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
468     ret = dtls1_get_record(s);
469     if (ret <= 0) {
470       ret = dtls1_read_failed(s, ret);
471       /* anything other than a timeout is an error */
472       if (ret <= 0) {
473         return ret;
474       } else {
475         goto start;
476       }
477     }
478   }
479 
480   /* we now have a packet which can be read and processed */
481 
482   /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
483    * ssl3_get_finished. */
484   if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
485       rr->type != SSL3_RT_ALERT) {
486     /* We now have an unexpected record between CCS and Finished. Most likely
487      * the packets were reordered on their way. DTLS is unreliable, so drop the
488      * packet and expect the peer to retransmit. */
489     rr->length = 0;
490     goto start;
491   }
492 
493   /* If the other end has shut down, throw anything we read away (even in
494    * 'peek' mode) */
495   if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
496     rr->length = 0;
497     s->rwstate = SSL_NOTHING;
498     return 0;
499   }
500 
501 
502   if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
503     /* make sure that we are not getting application data when we
504      * are doing a handshake for the first time */
505     if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
506         (s->aead_read_ctx == NULL)) {
507       /* TODO(davidben): Is this check redundant with the handshake_func
508        * check? */
509       al = SSL_AD_UNEXPECTED_MESSAGE;
510       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
511       goto f_err;
512     }
513 
514     if (len <= 0) {
515       return len;
516     }
517 
518     if ((unsigned int)len > rr->length) {
519       n = rr->length;
520     } else {
521       n = (unsigned int)len;
522     }
523 
524     memcpy(buf, &(rr->data[rr->off]), n);
525     if (!peek) {
526       rr->length -= n;
527       rr->off += n;
528       if (rr->length == 0) {
529         s->rstate = SSL_ST_READ_HEADER;
530         rr->off = 0;
531       }
532     }
533 
534     return n;
535   }
536 
537   /* If we get here, then type != rr->type. */
538 
539   /* If an alert record, process one alert out of the record. Note that we allow
540    * a single record to contain multiple alerts. */
541   if (rr->type == SSL3_RT_ALERT) {
542     /* Alerts may not be fragmented. */
543     if (rr->length < 2) {
544       al = SSL_AD_DECODE_ERROR;
545       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_ALERT);
546       goto f_err;
547     }
548 
549     if (s->msg_callback) {
550       s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
551                       s->msg_callback_arg);
552     }
553     const uint8_t alert_level = rr->data[rr->off++];
554     const uint8_t alert_descr = rr->data[rr->off++];
555     rr->length -= 2;
556 
557     if (s->info_callback != NULL) {
558       cb = s->info_callback;
559     } else if (s->ctx->info_callback != NULL) {
560       cb = s->ctx->info_callback;
561     }
562 
563     if (cb != NULL) {
564       uint16_t alert = (alert_level << 8) | alert_descr;
565       cb(s, SSL_CB_READ_ALERT, alert);
566     }
567 
568     if (alert_level == SSL3_AL_WARNING) {
569       s->s3->warn_alert = alert_descr;
570       if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
571         s->shutdown |= SSL_RECEIVED_SHUTDOWN;
572         return 0;
573       }
574     } else if (alert_level == SSL3_AL_FATAL) {
575       char tmp[16];
576 
577       s->rwstate = SSL_NOTHING;
578       s->s3->fatal_alert = alert_descr;
579       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes,
580                         SSL_AD_REASON_OFFSET + alert_descr);
581       BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
582       ERR_add_error_data(2, "SSL alert number ", tmp);
583       s->shutdown |= SSL_RECEIVED_SHUTDOWN;
584       SSL_CTX_remove_session(s->ctx, s->session);
585       return 0;
586     } else {
587       al = SSL_AD_ILLEGAL_PARAMETER;
588       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
589       goto f_err;
590     }
591 
592     goto start;
593   }
594 
595   if (s->shutdown & SSL_SENT_SHUTDOWN) {
596     /* but we have not received a shutdown */
597     s->rwstate = SSL_NOTHING;
598     rr->length = 0;
599     return 0;
600   }
601 
602   if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
603     /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
604      * record payload has to look like */
605     if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
606       al = SSL_AD_ILLEGAL_PARAMETER;
607       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
608       goto f_err;
609     }
610 
611     rr->length = 0;
612 
613     if (s->msg_callback) {
614       s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
615                       s->msg_callback_arg);
616     }
617 
618     /* We can't process a CCS now, because previous handshake
619      * messages are still missing, so just drop it.
620      */
621     if (!s->d1->change_cipher_spec_ok) {
622       goto start;
623     }
624 
625     s->d1->change_cipher_spec_ok = 0;
626 
627     s->s3->change_cipher_spec = 1;
628     if (!ssl3_do_change_cipher_spec(s)) {
629       goto err;
630     }
631 
632     /* do this whenever CCS is processed */
633     dtls1_reset_seq_numbers(s, SSL3_CC_READ);
634 
635     goto start;
636   }
637 
638   /* Unexpected handshake message. It may be a retransmitted Finished (the only
639    * post-CCS message). Otherwise, it's a pre-CCS handshake message from an
640    * unsupported renegotiation attempt. */
641   if (rr->type == SSL3_RT_HANDSHAKE && !s->in_handshake) {
642     if (rr->length < DTLS1_HM_HEADER_LENGTH) {
643       al = SSL_AD_DECODE_ERROR;
644       OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_HANDSHAKE_RECORD);
645       goto f_err;
646     }
647     struct hm_header_st msg_hdr;
648     dtls1_get_message_header(&rr->data[rr->off], &msg_hdr);
649 
650     /* Ignore a stray Finished from the previous handshake. */
651     if (msg_hdr.type == SSL3_MT_FINISHED) {
652       if (msg_hdr.frag_off == 0) {
653         /* Retransmit our last flight of messages. If the peer sends the second
654          * Finished, they may not have received ours. Only do this for the
655          * first fragment, in case the Finished was fragmented. */
656         if (dtls1_check_timeout_num(s) < 0) {
657           return -1;
658         }
659 
660         dtls1_retransmit_buffered_messages(s);
661       }
662 
663       rr->length = 0;
664       goto start;
665     }
666   }
667 
668   /* We already handled these. */
669   assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT);
670 
671   al = SSL_AD_UNEXPECTED_MESSAGE;
672   OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
673 
674 f_err:
675   ssl3_send_alert(s, SSL3_AL_FATAL, al);
676 err:
677   return -1;
678 }
679 
dtls1_write_app_data(SSL * s,const void * buf_,int len)680 int dtls1_write_app_data(SSL *s, const void *buf_, int len) {
681   int i;
682 
683   if (SSL_in_init(s) && !s->in_handshake) {
684     i = s->handshake_func(s);
685     if (i < 0) {
686       return i;
687     }
688     if (i == 0) {
689       OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data, SSL_R_SSL_HANDSHAKE_FAILURE);
690       return -1;
691     }
692   }
693 
694   if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
695     OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data, SSL_R_DTLS_MESSAGE_TOO_BIG);
696     return -1;
697   }
698 
699   i = dtls1_write_bytes(s, SSL3_RT_APPLICATION_DATA, buf_, len,
700                         dtls1_use_current_epoch);
701   return i;
702 }
703 
704 /* Call this to write data in records of type 'type' It will return <= 0 if not
705  * all data has been sent or non-blocking IO. */
dtls1_write_bytes(SSL * s,int type,const void * buf,int len,enum dtls1_use_epoch_t use_epoch)706 int dtls1_write_bytes(SSL *s, int type, const void *buf, int len,
707                       enum dtls1_use_epoch_t use_epoch) {
708   int i;
709 
710   assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
711   s->rwstate = SSL_NOTHING;
712   i = do_dtls1_write(s, type, buf, len, use_epoch);
713   return i;
714 }
715 
716 /* dtls1_seal_record seals a new record of type |type| and plaintext |in| and
717  * writes it to |out|. At most |max_out| bytes will be written. It returns one
718  * on success and zero on error. On success, it updates the write sequence
719  * number. */
dtls1_seal_record(SSL * s,uint8_t * out,size_t * out_len,size_t max_out,uint8_t type,const uint8_t * in,size_t in_len,enum dtls1_use_epoch_t use_epoch)720 static int dtls1_seal_record(SSL *s, uint8_t *out, size_t *out_len,
721                              size_t max_out, uint8_t type, const uint8_t *in,
722                              size_t in_len, enum dtls1_use_epoch_t use_epoch) {
723   if (max_out < DTLS1_RT_HEADER_LENGTH) {
724     OPENSSL_PUT_ERROR(SSL, dtls1_seal_record, SSL_R_BUFFER_TOO_SMALL);
725     return 0;
726   }
727 
728   /* Determine the parameters for the current epoch. */
729   uint16_t epoch = s->d1->w_epoch;
730   SSL_AEAD_CTX *aead = s->aead_write_ctx;
731   uint8_t *seq = s->s3->write_sequence;
732   if (use_epoch == dtls1_use_previous_epoch) {
733     /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
734      * (negotiated cipher) exist. */
735     assert(s->d1->w_epoch == 1);
736     epoch = s->d1->w_epoch - 1;
737     aead = NULL;
738     seq = s->d1->last_write_sequence;
739   }
740 
741   out[0] = type;
742 
743   uint16_t wire_version = s->s3->have_version ? s->version : DTLS1_VERSION;
744   out[1] = wire_version >> 8;
745   out[2] = wire_version & 0xff;
746 
747   out[3] = epoch >> 8;
748   out[4] = epoch & 0xff;
749   memcpy(&out[5], &seq[2], 6);
750 
751   size_t ciphertext_len;
752   if (!SSL_AEAD_CTX_seal(aead, out + DTLS1_RT_HEADER_LENGTH, &ciphertext_len,
753                          max_out - DTLS1_RT_HEADER_LENGTH, type, wire_version,
754                          &out[3] /* seq */, in, in_len) ||
755       !ssl3_record_sequence_update(&seq[2], 6)) {
756     return 0;
757   }
758 
759   if (ciphertext_len >= 1 << 16) {
760     OPENSSL_PUT_ERROR(SSL, dtls1_seal_record, ERR_R_OVERFLOW);
761     return 0;
762   }
763   out[11] = ciphertext_len >> 8;
764   out[12] = ciphertext_len & 0xff;
765 
766   *out_len = DTLS1_RT_HEADER_LENGTH + ciphertext_len;
767 
768   if (s->msg_callback) {
769     s->msg_callback(1 /* write */, 0, SSL3_RT_HEADER, out,
770                     DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
771   }
772 
773   return 1;
774 }
775 
do_dtls1_write(SSL * s,int type,const uint8_t * buf,unsigned int len,enum dtls1_use_epoch_t use_epoch)776 static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
777                           unsigned int len, enum dtls1_use_epoch_t use_epoch) {
778   SSL3_BUFFER *wb = &s->s3->wbuf;
779 
780   /* ssl3_write_pending drops the write if |BIO_write| fails in DTLS, so there
781    * is never pending data. */
782   assert(s->s3->wbuf.left == 0);
783 
784   /* If we have an alert to send, lets send it */
785   if (s->s3->alert_dispatch) {
786     int ret = s->method->ssl_dispatch_alert(s);
787     if (ret <= 0) {
788       return ret;
789     }
790     /* if it went, fall through and send more stuff */
791   }
792 
793   if (wb->buf == NULL && !ssl3_setup_write_buffer(s)) {
794     return -1;
795   }
796 
797   if (len == 0) {
798     return 0;
799   }
800 
801   /* Align the output so the ciphertext is aligned to |SSL3_ALIGN_PAYLOAD|. */
802   uintptr_t align = (uintptr_t)wb->buf + DTLS1_RT_HEADER_LENGTH;
803   align = (0 - align) & (SSL3_ALIGN_PAYLOAD - 1);
804   uint8_t *out = wb->buf + align;
805   wb->offset = align;
806   size_t max_out = wb->len - wb->offset;
807 
808   size_t ciphertext_len;
809   if (!dtls1_seal_record(s, out, &ciphertext_len, max_out, type, buf, len,
810                          use_epoch)) {
811     return -1;
812   }
813 
814   /* now let's set up wb */
815   wb->left = ciphertext_len;
816 
817   /* memorize arguments so that ssl3_write_pending can detect bad write retries
818    * later */
819   s->s3->wpend_tot = len;
820   s->s3->wpend_buf = buf;
821   s->s3->wpend_type = type;
822   s->s3->wpend_ret = len;
823 
824   /* we now just need to write the buffer */
825   return ssl3_write_pending(s, type, buf, len);
826 }
827 
dtls1_record_replay_check(SSL * s,DTLS1_BITMAP * bitmap)828 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) {
829   int cmp;
830   unsigned int shift;
831   const uint8_t *seq = s->s3->read_sequence;
832 
833   cmp = satsub64be(seq, bitmap->max_seq_num);
834   if (cmp > 0) {
835     memcpy(s->s3->rrec.seq_num, seq, 8);
836     return 1; /* this record in new */
837   }
838   shift = -cmp;
839   if (shift >= sizeof(bitmap->map) * 8) {
840     return 0; /* stale, outside the window */
841   } else if (bitmap->map & (((uint64_t)1) << shift)) {
842     return 0; /* record previously received */
843   }
844 
845   memcpy(s->s3->rrec.seq_num, seq, 8);
846   return 1;
847 }
848 
dtls1_record_bitmap_update(SSL * s,DTLS1_BITMAP * bitmap)849 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) {
850   int cmp;
851   unsigned int shift;
852   const uint8_t *seq = s->s3->read_sequence;
853 
854   cmp = satsub64be(seq, bitmap->max_seq_num);
855   if (cmp > 0) {
856     shift = cmp;
857     if (shift < sizeof(bitmap->map) * 8) {
858       bitmap->map <<= shift, bitmap->map |= 1UL;
859     } else {
860       bitmap->map = 1UL;
861     }
862     memcpy(bitmap->max_seq_num, seq, 8);
863   } else {
864     shift = -cmp;
865     if (shift < sizeof(bitmap->map) * 8) {
866       bitmap->map |= ((uint64_t)1) << shift;
867     }
868   }
869 }
870 
dtls1_dispatch_alert(SSL * s)871 int dtls1_dispatch_alert(SSL *s) {
872   int i, j;
873   void (*cb)(const SSL *ssl, int type, int val) = NULL;
874   uint8_t buf[DTLS1_AL_HEADER_LENGTH];
875   uint8_t *ptr = &buf[0];
876 
877   s->s3->alert_dispatch = 0;
878 
879   memset(buf, 0x00, sizeof(buf));
880   *ptr++ = s->s3->send_alert[0];
881   *ptr++ = s->s3->send_alert[1];
882 
883   i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf),
884                      dtls1_use_current_epoch);
885   if (i <= 0) {
886     s->s3->alert_dispatch = 1;
887   } else {
888     if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
889       (void)BIO_flush(s->wbio);
890     }
891 
892     if (s->msg_callback) {
893       s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
894                       s->msg_callback_arg);
895     }
896 
897     if (s->info_callback != NULL) {
898       cb = s->info_callback;
899     } else if (s->ctx->info_callback != NULL) {
900       cb = s->ctx->info_callback;
901     }
902 
903     if (cb != NULL) {
904       j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
905       cb(s, SSL_CB_WRITE_ALERT, j);
906     }
907   }
908 
909   return i;
910 }
911 
dtls1_reset_seq_numbers(SSL * s,int rw)912 void dtls1_reset_seq_numbers(SSL *s, int rw) {
913   uint8_t *seq;
914   unsigned int seq_bytes = sizeof(s->s3->read_sequence);
915 
916   if (rw & SSL3_CC_READ) {
917     seq = s->s3->read_sequence;
918     s->d1->r_epoch++;
919     memset(&s->d1->bitmap, 0, sizeof(DTLS1_BITMAP));
920   } else {
921     seq = s->s3->write_sequence;
922     memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
923     s->d1->w_epoch++;
924   }
925 
926   memset(seq, 0x00, seq_bytes);
927 }
928