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 <openssl/ssl.h>
113
114#include <assert.h>
115#include <stdio.h>
116#include <string.h>
117
118#include <openssl/buf.h>
119#include <openssl/mem.h>
120#include <openssl/evp.h>
121#include <openssl/err.h>
122#include <openssl/rand.h>
123
124#include "internal.h"
125
126
127static int do_dtls1_write(SSL *ssl, int type, const uint8_t *buf,
128                          unsigned int len, enum dtls1_use_epoch_t use_epoch);
129
130/* dtls1_get_record reads a new input record. On success, it places it in
131 * |ssl->s3->rrec| and returns one. Otherwise it returns <= 0 on error or if
132 * more data is needed. */
133static int dtls1_get_record(SSL *ssl) {
134again:
135  /* Read a new packet if there is no unconsumed one. */
136  if (ssl_read_buffer_len(ssl) == 0) {
137    int ret = ssl_read_buffer_extend_to(ssl, 0 /* unused */);
138    if (ret <= 0) {
139      return ret;
140    }
141  }
142  assert(ssl_read_buffer_len(ssl) > 0);
143
144  /* Ensure the packet is large enough to decrypt in-place. */
145  if (ssl_read_buffer_len(ssl) < ssl_record_prefix_len(ssl)) {
146    ssl_read_buffer_clear(ssl);
147    goto again;
148  }
149
150  uint8_t *out = ssl_read_buffer(ssl) + ssl_record_prefix_len(ssl);
151  size_t max_out = ssl_read_buffer_len(ssl) - ssl_record_prefix_len(ssl);
152  uint8_t type, alert;
153  size_t len, consumed;
154  switch (dtls_open_record(ssl, &type, out, &len, &consumed, &alert, max_out,
155                           ssl_read_buffer(ssl), ssl_read_buffer_len(ssl))) {
156    case ssl_open_record_success:
157      ssl_read_buffer_consume(ssl, consumed);
158
159      if (len > 0xffff) {
160        OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
161        return -1;
162      }
163
164      SSL3_RECORD *rr = &ssl->s3->rrec;
165      rr->type = type;
166      rr->length = (uint16_t)len;
167      rr->data = out;
168      return 1;
169
170    case ssl_open_record_discard:
171      ssl_read_buffer_consume(ssl, consumed);
172      goto again;
173
174    case ssl_open_record_error:
175      ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
176      return -1;
177
178    case ssl_open_record_partial:
179      /* Impossible in DTLS. */
180      break;
181  }
182
183  assert(0);
184  OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
185  return -1;
186}
187
188int dtls1_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
189  return dtls1_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
190}
191
192int dtls1_read_change_cipher_spec(SSL *ssl) {
193  uint8_t byte;
194  int ret = dtls1_read_bytes(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, &byte,
195                             1 /* len */, 0 /* no peek */);
196  if (ret <= 0) {
197    return ret;
198  }
199  assert(ret == 1);
200
201  if (ssl->s3->rrec.length != 0 || byte != SSL3_MT_CCS) {
202    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
203    ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
204    return -1;
205  }
206
207  if (ssl->msg_callback != NULL) {
208    ssl->msg_callback(0, ssl->version, SSL3_RT_CHANGE_CIPHER_SPEC, &byte, 1,
209                      ssl, ssl->msg_callback_arg);
210  }
211
212  return 1;
213}
214
215void dtls1_read_close_notify(SSL *ssl) {
216  /* Bidirectional shutdown doesn't make sense for an unordered transport. DTLS
217   * alerts also aren't delivered reliably, so we may even time out because the
218   * peer never received our close_notify. Report to the caller that the channel
219   * has fully shut down. */
220  ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
221}
222
223/* Return up to 'len' payload bytes received in 'type' records.
224 * 'type' is one of the following:
225 *
226 *   -  SSL3_RT_HANDSHAKE (when dtls1_get_message calls us)
227 *   -  SSL3_RT_CHANGE_CIPHER_SPEC (when dtls1_read_change_cipher_spec calls us)
228 *   -  SSL3_RT_APPLICATION_DATA (when dtls1_read_app_data calls us)
229 *
230 * If we don't have stored data to work from, read a DTLS record first (possibly
231 * multiple records if we still don't have anything to return).
232 *
233 * This function must handle any surprises the peer may have for us, such as
234 * Alert records (e.g. close_notify) and out of records. */
235int dtls1_read_bytes(SSL *ssl, int type, unsigned char *buf, int len, int peek) {
236  int al, i, ret;
237  unsigned int n;
238  SSL3_RECORD *rr;
239  void (*cb)(const SSL *ssl, int type, int value) = NULL;
240
241  if ((type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE &&
242       type != SSL3_RT_CHANGE_CIPHER_SPEC) ||
243      (peek && type != SSL3_RT_APPLICATION_DATA)) {
244    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
245    return -1;
246  }
247
248  if (!ssl->in_handshake && SSL_in_init(ssl)) {
249    /* type == SSL3_RT_APPLICATION_DATA */
250    i = ssl->handshake_func(ssl);
251    if (i < 0) {
252      return i;
253    }
254    if (i == 0) {
255      OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
256      return -1;
257    }
258  }
259
260start:
261  ssl->rwstate = SSL_NOTHING;
262
263  /* ssl->s3->rrec.type     - is the type of record
264   * ssl->s3->rrec.data     - data
265   * ssl->s3->rrec.off      - offset into 'data' for next read
266   * ssl->s3->rrec.length   - number of bytes. */
267  rr = &ssl->s3->rrec;
268
269  /* Check for timeout */
270  if (DTLSv1_handle_timeout(ssl) > 0) {
271    goto start;
272  }
273
274  /* get new packet if necessary */
275  if (rr->length == 0) {
276    ret = dtls1_get_record(ssl);
277    if (ret <= 0) {
278      ret = dtls1_read_failed(ssl, ret);
279      /* anything other than a timeout is an error */
280      if (ret <= 0) {
281        return ret;
282      } else {
283        goto start;
284      }
285    }
286  }
287
288  /* we now have a packet which can be read and processed */
289
290  /* If the other end has shut down, throw anything we read away (even in
291   * 'peek' mode) */
292  if (ssl->shutdown & SSL_RECEIVED_SHUTDOWN) {
293    rr->length = 0;
294    ssl->rwstate = SSL_NOTHING;
295    return 0;
296  }
297
298
299  if (type == rr->type) {
300    /* Make sure that we are not getting application data when we
301     * are doing a handshake for the first time. */
302    if (SSL_in_init(ssl) && (type == SSL3_RT_APPLICATION_DATA) &&
303        (ssl->aead_read_ctx == NULL)) {
304      /* TODO(davidben): Is this check redundant with the handshake_func
305       * check? */
306      al = SSL_AD_UNEXPECTED_MESSAGE;
307      OPENSSL_PUT_ERROR(SSL, SSL_R_APP_DATA_IN_HANDSHAKE);
308      goto f_err;
309    }
310
311    /* Discard empty records. */
312    if (rr->length == 0) {
313      goto start;
314    }
315
316    if (len <= 0) {
317      return len;
318    }
319
320    if ((unsigned int)len > rr->length) {
321      n = rr->length;
322    } else {
323      n = (unsigned int)len;
324    }
325
326    memcpy(buf, rr->data, n);
327    if (!peek) {
328      rr->length -= n;
329      rr->data += n;
330      if (rr->length == 0) {
331        /* The record has been consumed, so we may now clear the buffer. */
332        ssl_read_buffer_discard(ssl);
333      }
334    }
335
336    return n;
337  }
338
339  /* If we get here, then type != rr->type. */
340
341  /* If an alert record, process one alert out of the record. Note that we allow
342   * a single record to contain multiple alerts. */
343  if (rr->type == SSL3_RT_ALERT) {
344    /* Alerts may not be fragmented. */
345    if (rr->length < 2) {
346      al = SSL_AD_DECODE_ERROR;
347      OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
348      goto f_err;
349    }
350
351    if (ssl->msg_callback) {
352      ssl->msg_callback(0, ssl->version, SSL3_RT_ALERT, rr->data, 2, ssl,
353                      ssl->msg_callback_arg);
354    }
355    const uint8_t alert_level = rr->data[0];
356    const uint8_t alert_descr = rr->data[1];
357    rr->length -= 2;
358    rr->data += 2;
359
360    if (ssl->info_callback != NULL) {
361      cb = ssl->info_callback;
362    } else if (ssl->ctx->info_callback != NULL) {
363      cb = ssl->ctx->info_callback;
364    }
365
366    if (cb != NULL) {
367      uint16_t alert = (alert_level << 8) | alert_descr;
368      cb(ssl, SSL_CB_READ_ALERT, alert);
369    }
370
371    if (alert_level == SSL3_AL_WARNING) {
372      ssl->s3->warn_alert = alert_descr;
373      if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
374        ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
375        return 0;
376      }
377    } else if (alert_level == SSL3_AL_FATAL) {
378      char tmp[16];
379
380      ssl->rwstate = SSL_NOTHING;
381      ssl->s3->fatal_alert = alert_descr;
382      OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
383      BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
384      ERR_add_error_data(2, "SSL alert number ", tmp);
385      ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
386      SSL_CTX_remove_session(ssl->ctx, ssl->session);
387      return 0;
388    } else {
389      al = SSL_AD_ILLEGAL_PARAMETER;
390      OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
391      goto f_err;
392    }
393
394    goto start;
395  }
396
397  /* Cross-epoch records are discarded, but we may receive out-of-order
398   * application data between ChangeCipherSpec and Finished or a ChangeCipherSpec
399   * before the appropriate point in the handshake. Those must be silently
400   * discarded.
401   *
402   * However, only allow the out-of-order records in the correct epoch.
403   * Application data must come in the encrypted epoch, and ChangeCipherSpec in
404   * the unencrypted epoch (we never renegotiate). Other cases fall through and
405   * fail with a fatal error. */
406  if ((rr->type == SSL3_RT_APPLICATION_DATA && ssl->aead_read_ctx != NULL) ||
407      (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC && ssl->aead_read_ctx == NULL)) {
408    rr->length = 0;
409    goto start;
410  }
411
412  if (rr->type == SSL3_RT_HANDSHAKE) {
413    if (type != SSL3_RT_APPLICATION_DATA) {
414      /* Out-of-order handshake record while looking for ChangeCipherSpec. Drop
415       * it silently. */
416      assert(type == SSL3_RT_CHANGE_CIPHER_SPEC);
417      rr->length = 0;
418      goto start;
419    }
420
421    /* Parse the first fragment header to determine if this is a pre-CCS or
422     * post-CCS handshake record. DTLS resets handshake message numbers on each
423     * handshake, so renegotiations and retransmissions are ambiguous. */
424    if (rr->length < DTLS1_HM_HEADER_LENGTH) {
425      al = SSL_AD_DECODE_ERROR;
426      OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
427      goto f_err;
428    }
429    struct hm_header_st msg_hdr;
430    dtls1_get_message_header(rr->data, &msg_hdr);
431
432    if (msg_hdr.type == SSL3_MT_FINISHED) {
433      if (msg_hdr.frag_off == 0) {
434        /* Retransmit our last flight of messages. If the peer sends the second
435         * Finished, they may not have received ours. Only do this for the
436         * first fragment, in case the Finished was fragmented. */
437        if (dtls1_check_timeout_num(ssl) < 0) {
438          return -1;
439        }
440
441        dtls1_retransmit_buffered_messages(ssl);
442      }
443
444      rr->length = 0;
445      goto start;
446    }
447
448    /* Otherwise, this is a pre-CCS handshake message from an unsupported
449     * renegotiation attempt. Fall through to the error path. */
450  }
451
452  al = SSL_AD_UNEXPECTED_MESSAGE;
453  OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
454
455f_err:
456  ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
457  return -1;
458}
459
460int dtls1_write_app_data(SSL *ssl, const void *buf_, int len) {
461  int i;
462
463  if (SSL_in_init(ssl) && !ssl->in_handshake) {
464    i = ssl->handshake_func(ssl);
465    if (i < 0) {
466      return i;
467    }
468    if (i == 0) {
469      OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
470      return -1;
471    }
472  }
473
474  if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
475    OPENSSL_PUT_ERROR(SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
476    return -1;
477  }
478
479  i = dtls1_write_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf_, len,
480                        dtls1_use_current_epoch);
481  return i;
482}
483
484/* Call this to write data in records of type 'type' It will return <= 0 if not
485 * all data has been sent or non-blocking IO. */
486int dtls1_write_bytes(SSL *ssl, int type, const void *buf, int len,
487                      enum dtls1_use_epoch_t use_epoch) {
488  int i;
489
490  assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
491  ssl->rwstate = SSL_NOTHING;
492  i = do_dtls1_write(ssl, type, buf, len, use_epoch);
493  return i;
494}
495
496static int do_dtls1_write(SSL *ssl, int type, const uint8_t *buf,
497                          unsigned int len, enum dtls1_use_epoch_t use_epoch) {
498  /* There should never be a pending write buffer in DTLS. One can't write half
499   * a datagram, so the write buffer is always dropped in
500   * |ssl_write_buffer_flush|. */
501  assert(!ssl_write_buffer_is_pending(ssl));
502
503  /* If we have an alert to send, lets send it */
504  if (ssl->s3->alert_dispatch) {
505    int ret = ssl->method->ssl_dispatch_alert(ssl);
506    if (ret <= 0) {
507      return ret;
508    }
509    /* if it went, fall through and send more stuff */
510  }
511
512  if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
513    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
514    return -1;
515  }
516
517  if (len == 0) {
518    return 0;
519  }
520
521  size_t max_out = len + ssl_max_seal_overhead(ssl);
522  uint8_t *out;
523  size_t ciphertext_len;
524  if (!ssl_write_buffer_init(ssl, &out, max_out) ||
525      !dtls_seal_record(ssl, out, &ciphertext_len, max_out, type, buf, len,
526                        use_epoch)) {
527    ssl_write_buffer_clear(ssl);
528    return -1;
529  }
530  ssl_write_buffer_set_len(ssl, ciphertext_len);
531
532  int ret = ssl_write_buffer_flush(ssl);
533  if (ret <= 0) {
534    return ret;
535  }
536  return (int)len;
537}
538
539int dtls1_dispatch_alert(SSL *ssl) {
540  int i, j;
541  void (*cb)(const SSL *ssl, int type, int value) = NULL;
542  uint8_t buf[DTLS1_AL_HEADER_LENGTH];
543  uint8_t *ptr = &buf[0];
544
545  ssl->s3->alert_dispatch = 0;
546
547  memset(buf, 0x00, sizeof(buf));
548  *ptr++ = ssl->s3->send_alert[0];
549  *ptr++ = ssl->s3->send_alert[1];
550
551  i = do_dtls1_write(ssl, SSL3_RT_ALERT, &buf[0], sizeof(buf),
552                     dtls1_use_current_epoch);
553  if (i <= 0) {
554    ssl->s3->alert_dispatch = 1;
555  } else {
556    if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
557      (void)BIO_flush(ssl->wbio);
558    }
559
560    if (ssl->msg_callback) {
561      ssl->msg_callback(1, ssl->version, SSL3_RT_ALERT, ssl->s3->send_alert, 2,
562                        ssl, ssl->msg_callback_arg);
563    }
564
565    if (ssl->info_callback != NULL) {
566      cb = ssl->info_callback;
567    } else if (ssl->ctx->info_callback != NULL) {
568      cb = ssl->ctx->info_callback;
569    }
570
571    if (cb != NULL) {
572      j = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
573      cb(ssl, SSL_CB_WRITE_ALERT, j);
574    }
575  }
576
577  return i;
578}
579