You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

926 lines
29 KiB

  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. #include <assert.h>
  112. #include <stdio.h>
  113. #include <string.h>
  114. #include <openssl/buf.h>
  115. #include <openssl/mem.h>
  116. #include <openssl/evp.h>
  117. #include <openssl/err.h>
  118. #include <openssl/rand.h>
  119. #include "internal.h"
  120. /* mod 128 saturating subtract of two 64-bit values in big-endian order */
  121. static int satsub64be(const uint8_t *v1, const uint8_t *v2) {
  122. int ret, sat, brw, i;
  123. if (sizeof(long) == 8) {
  124. do {
  125. const union {
  126. long one;
  127. char little;
  128. } is_endian = {1};
  129. long l;
  130. if (is_endian.little) {
  131. break;
  132. }
  133. /* not reached on little-endians */
  134. /* following test is redundant, because input is
  135. * always aligned, but I take no chances... */
  136. if (((size_t)v1 | (size_t)v2) & 0x7) {
  137. break;
  138. }
  139. l = *((long *)v1);
  140. l -= *((long *)v2);
  141. if (l > 128) {
  142. return 128;
  143. } else if (l < -128) {
  144. return -128;
  145. } else {
  146. return (int)l;
  147. }
  148. } while (0);
  149. }
  150. ret = (int)v1[7] - (int)v2[7];
  151. sat = 0;
  152. brw = ret >> 8; /* brw is either 0 or -1 */
  153. if (ret & 0x80) {
  154. for (i = 6; i >= 0; i--) {
  155. brw += (int)v1[i] - (int)v2[i];
  156. sat |= ~brw;
  157. brw >>= 8;
  158. }
  159. } else {
  160. for (i = 6; i >= 0; i--) {
  161. brw += (int)v1[i] - (int)v2[i];
  162. sat |= brw;
  163. brw >>= 8;
  164. }
  165. }
  166. brw <<= 8; /* brw is either 0 or -256 */
  167. if (sat & 0xff) {
  168. return brw | 0x80;
  169. } else {
  170. return brw + (ret & 0xFF);
  171. }
  172. }
  173. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  174. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  175. static int dtls1_process_record(SSL *s);
  176. static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
  177. unsigned int len, enum dtls1_use_epoch_t use_epoch);
  178. static int dtls1_process_record(SSL *s) {
  179. int al;
  180. SSL3_RECORD *rr = &s->s3->rrec;
  181. /* check is not needed I believe */
  182. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  183. al = SSL_AD_RECORD_OVERFLOW;
  184. OPENSSL_PUT_ERROR(SSL, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  185. goto f_err;
  186. }
  187. /* |rr->data| points to |rr->length| bytes of ciphertext in |s->packet|. */
  188. rr->data = &s->packet[DTLS1_RT_HEADER_LENGTH];
  189. uint8_t seq[8];
  190. seq[0] = rr->epoch >> 8;
  191. seq[1] = rr->epoch & 0xff;
  192. memcpy(&seq[2], &rr->seq_num[2], 6);
  193. /* Decrypt the packet in-place. Note it is important that |SSL_AEAD_CTX_open|
  194. * not write beyond |rr->length|. There may be another record in the packet.
  195. *
  196. * TODO(davidben): This assumes |s->version| is the same as the record-layer
  197. * version which isn't always true, but it only differs with the NULL cipher
  198. * which ignores the parameter. */
  199. size_t plaintext_len;
  200. if (!SSL_AEAD_CTX_open(s->aead_read_ctx, rr->data, &plaintext_len, rr->length,
  201. rr->type, s->version, seq, rr->data, rr->length)) {
  202. /* Bad packets are silently dropped in DTLS. Clear the error queue of any
  203. * errors decryption may have added. */
  204. ERR_clear_error();
  205. rr->length = 0;
  206. s->packet_length = 0;
  207. goto err;
  208. }
  209. if (plaintext_len > SSL3_RT_MAX_PLAIN_LENGTH) {
  210. al = SSL_AD_RECORD_OVERFLOW;
  211. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  212. goto f_err;
  213. }
  214. assert(plaintext_len < (1u << 16));
  215. rr->length = plaintext_len;
  216. rr->off = 0;
  217. /* So at this point the following is true
  218. * ssl->s3->rrec.type is the type of record
  219. * ssl->s3->rrec.length == number of bytes in record
  220. * ssl->s3->rrec.off == offset to first valid byte
  221. * ssl->s3->rrec.data == the first byte of the record body. */
  222. /* we have pulled in a full packet so zero things */
  223. s->packet_length = 0;
  224. return 1;
  225. f_err:
  226. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  227. err:
  228. return 0;
  229. }
  230. /* Call this to get a new input record.
  231. * It will return <= 0 if more data is needed, normally due to an error
  232. * or non-blocking IO.
  233. * When it finishes, one packet has been decoded and can be found in
  234. * ssl->s3->rrec.type - is the type of record
  235. * ssl->s3->rrec.data, - data
  236. * ssl->s3->rrec.length, - number of bytes
  237. *
  238. * used only by dtls1_read_bytes */
  239. int dtls1_get_record(SSL *s) {
  240. uint8_t ssl_major, ssl_minor;
  241. int n;
  242. SSL3_RECORD *rr;
  243. uint8_t *p = NULL;
  244. uint16_t version;
  245. rr = &(s->s3->rrec);
  246. /* get something from the wire */
  247. again:
  248. /* check if we have the header */
  249. if ((s->rstate != SSL_ST_READ_BODY) ||
  250. (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
  251. n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, 0);
  252. /* read timeout is handled by dtls1_read_bytes */
  253. if (n <= 0) {
  254. return n; /* error or non-blocking */
  255. }
  256. /* this packet contained a partial record, dump it */
  257. if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
  258. s->packet_length = 0;
  259. goto again;
  260. }
  261. s->rstate = SSL_ST_READ_BODY;
  262. p = s->packet;
  263. if (s->msg_callback) {
  264. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s,
  265. s->msg_callback_arg);
  266. }
  267. /* Pull apart the header into the DTLS1_RECORD */
  268. rr->type = *(p++);
  269. ssl_major = *(p++);
  270. ssl_minor = *(p++);
  271. version = (((uint16_t)ssl_major) << 8) | ssl_minor;
  272. /* sequence number is 64 bits, with top 2 bytes = epoch */
  273. n2s(p, rr->epoch);
  274. memcpy(&(s->s3->read_sequence[2]), p, 6);
  275. p += 6;
  276. n2s(p, rr->length);
  277. /* Lets check version */
  278. if (s->s3->have_version) {
  279. if (version != s->version) {
  280. /* The record's version doesn't match, so silently drop it.
  281. *
  282. * TODO(davidben): This doesn't work. The DTLS record layer is not
  283. * packet-based, so the remainder of the packet isn't dropped and we
  284. * get a framing error. It's also unclear what it means to silently
  285. * drop a record in a packet containing two records. */
  286. rr->length = 0;
  287. s->packet_length = 0;
  288. goto again;
  289. }
  290. }
  291. if ((version & 0xff00) != (s->version & 0xff00)) {
  292. /* wrong version, silently discard record */
  293. rr->length = 0;
  294. s->packet_length = 0;
  295. goto again;
  296. }
  297. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  298. /* record too long, silently discard it */
  299. rr->length = 0;
  300. s->packet_length = 0;
  301. goto again;
  302. }
  303. /* now s->rstate == SSL_ST_READ_BODY */
  304. }
  305. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  306. if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
  307. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  308. n = ssl3_read_n(s, rr->length, 1);
  309. /* This packet contained a partial record, dump it. */
  310. if (n != rr->length) {
  311. rr->length = 0;
  312. s->packet_length = 0;
  313. goto again;
  314. }
  315. /* now n == rr->length,
  316. * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
  317. }
  318. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  319. if (rr->epoch != s->d1->r_epoch) {
  320. /* This record is from the wrong epoch. If it is the next epoch, it could be
  321. * buffered. For simplicity, drop it and expect retransmit to handle it
  322. * later; DTLS is supposed to handle packet loss. */
  323. rr->length = 0;
  324. s->packet_length = 0;
  325. goto again;
  326. }
  327. /* Check whether this is a repeat, or aged record. */
  328. if (!dtls1_record_replay_check(s, &s->d1->bitmap)) {
  329. rr->length = 0;
  330. s->packet_length = 0; /* dump this record */
  331. goto again; /* get another record */
  332. }
  333. /* just read a 0 length packet */
  334. if (rr->length == 0) {
  335. goto again;
  336. }
  337. if (!dtls1_process_record(s)) {
  338. rr->length = 0;
  339. s->packet_length = 0; /* dump this record */
  340. goto again; /* get another record */
  341. }
  342. dtls1_record_bitmap_update(s, &s->d1->bitmap); /* Mark receipt of record. */
  343. return 1;
  344. }
  345. int dtls1_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
  346. return dtls1_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
  347. }
  348. void dtls1_read_close_notify(SSL *ssl) {
  349. dtls1_read_bytes(ssl, 0, NULL, 0, 0);
  350. }
  351. /* Return up to 'len' payload bytes received in 'type' records.
  352. * 'type' is one of the following:
  353. *
  354. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  355. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  356. * - 0 (during a shutdown, no data has to be returned)
  357. *
  358. * If we don't have stored data to work from, read a SSL/TLS record first
  359. * (possibly multiple records if we still don't have anything to return).
  360. *
  361. * This function must handle any surprises the peer may have for us, such as
  362. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  363. * a surprise, but handled as if it were), or renegotiation requests.
  364. * Also if record payloads contain fragments too small to process, we store
  365. * them until there is enough for the respective protocol (the record protocol
  366. * may use arbitrary fragmentation and even interleaving):
  367. * Change cipher spec protocol
  368. * just 1 byte needed, no need for keeping anything stored
  369. * Alert protocol
  370. * 2 bytes needed (AlertLevel, AlertDescription)
  371. * Handshake protocol
  372. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  373. * to detect unexpected Client Hello and Hello Request messages
  374. * here, anything else is handled by higher layers
  375. * Application data protocol
  376. * none of our business
  377. */
  378. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) {
  379. int al, i, ret;
  380. unsigned int n;
  381. SSL3_RECORD *rr;
  382. void (*cb)(const SSL *ssl, int type2, int val) = NULL;
  383. /* XXX: check what the second '&& type' is about */
  384. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  385. (type != SSL3_RT_HANDSHAKE) && type) ||
  386. (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  387. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  388. return -1;
  389. }
  390. if (!s->in_handshake && SSL_in_init(s)) {
  391. /* type == SSL3_RT_APPLICATION_DATA */
  392. i = s->handshake_func(s);
  393. if (i < 0) {
  394. return i;
  395. }
  396. if (i == 0) {
  397. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  398. return -1;
  399. }
  400. }
  401. start:
  402. s->rwstate = SSL_NOTHING;
  403. /* s->s3->rrec.type - is the type of record
  404. * s->s3->rrec.data - data
  405. * s->s3->rrec.off - offset into 'data' for next read
  406. * s->s3->rrec.length - number of bytes. */
  407. rr = &s->s3->rrec;
  408. /* Check for timeout */
  409. if (DTLSv1_handle_timeout(s) > 0) {
  410. goto start;
  411. }
  412. /* get new packet if necessary */
  413. if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
  414. ret = dtls1_get_record(s);
  415. if (ret <= 0) {
  416. ret = dtls1_read_failed(s, ret);
  417. /* anything other than a timeout is an error */
  418. if (ret <= 0) {
  419. return ret;
  420. } else {
  421. goto start;
  422. }
  423. }
  424. }
  425. /* we now have a packet which can be read and processed */
  426. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  427. * ssl3_get_finished. */
  428. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
  429. rr->type != SSL3_RT_ALERT) {
  430. /* We now have an unexpected record between CCS and Finished. Most likely
  431. * the packets were reordered on their way. DTLS is unreliable, so drop the
  432. * packet and expect the peer to retransmit. */
  433. rr->length = 0;
  434. goto start;
  435. }
  436. /* If the other end has shut down, throw anything we read away (even in
  437. * 'peek' mode) */
  438. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  439. rr->length = 0;
  440. s->rwstate = SSL_NOTHING;
  441. return 0;
  442. }
  443. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  444. /* make sure that we are not getting application data when we
  445. * are doing a handshake for the first time */
  446. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  447. (s->aead_read_ctx == NULL)) {
  448. /* TODO(davidben): Is this check redundant with the handshake_func
  449. * check? */
  450. al = SSL_AD_UNEXPECTED_MESSAGE;
  451. OPENSSL_PUT_ERROR(SSL, SSL_R_APP_DATA_IN_HANDSHAKE);
  452. goto f_err;
  453. }
  454. if (len <= 0) {
  455. return len;
  456. }
  457. if ((unsigned int)len > rr->length) {
  458. n = rr->length;
  459. } else {
  460. n = (unsigned int)len;
  461. }
  462. memcpy(buf, &(rr->data[rr->off]), n);
  463. if (!peek) {
  464. rr->length -= n;
  465. rr->off += n;
  466. if (rr->length == 0) {
  467. s->rstate = SSL_ST_READ_HEADER;
  468. rr->off = 0;
  469. }
  470. }
  471. return n;
  472. }
  473. /* If we get here, then type != rr->type. */
  474. /* If an alert record, process one alert out of the record. Note that we allow
  475. * a single record to contain multiple alerts. */
  476. if (rr->type == SSL3_RT_ALERT) {
  477. /* Alerts may not be fragmented. */
  478. if (rr->length < 2) {
  479. al = SSL_AD_DECODE_ERROR;
  480. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  481. goto f_err;
  482. }
  483. if (s->msg_callback) {
  484. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  485. s->msg_callback_arg);
  486. }
  487. const uint8_t alert_level = rr->data[rr->off++];
  488. const uint8_t alert_descr = rr->data[rr->off++];
  489. rr->length -= 2;
  490. if (s->info_callback != NULL) {
  491. cb = s->info_callback;
  492. } else if (s->ctx->info_callback != NULL) {
  493. cb = s->ctx->info_callback;
  494. }
  495. if (cb != NULL) {
  496. uint16_t alert = (alert_level << 8) | alert_descr;
  497. cb(s, SSL_CB_READ_ALERT, alert);
  498. }
  499. if (alert_level == SSL3_AL_WARNING) {
  500. s->s3->warn_alert = alert_descr;
  501. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  502. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  503. return 0;
  504. }
  505. } else if (alert_level == SSL3_AL_FATAL) {
  506. char tmp[16];
  507. s->rwstate = SSL_NOTHING;
  508. s->s3->fatal_alert = alert_descr;
  509. OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
  510. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  511. ERR_add_error_data(2, "SSL alert number ", tmp);
  512. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  513. SSL_CTX_remove_session(s->ctx, s->session);
  514. return 0;
  515. } else {
  516. al = SSL_AD_ILLEGAL_PARAMETER;
  517. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
  518. goto f_err;
  519. }
  520. goto start;
  521. }
  522. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  523. /* but we have not received a shutdown */
  524. s->rwstate = SSL_NOTHING;
  525. rr->length = 0;
  526. return 0;
  527. }
  528. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  529. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  530. * record payload has to look like */
  531. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  532. al = SSL_AD_ILLEGAL_PARAMETER;
  533. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  534. goto f_err;
  535. }
  536. rr->length = 0;
  537. if (s->msg_callback) {
  538. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  539. s->msg_callback_arg);
  540. }
  541. /* We can't process a CCS now, because previous handshake
  542. * messages are still missing, so just drop it.
  543. */
  544. if (!s->d1->change_cipher_spec_ok) {
  545. goto start;
  546. }
  547. s->d1->change_cipher_spec_ok = 0;
  548. s->s3->change_cipher_spec = 1;
  549. if (!ssl3_do_change_cipher_spec(s)) {
  550. goto err;
  551. }
  552. /* do this whenever CCS is processed */
  553. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  554. goto start;
  555. }
  556. /* Unexpected handshake message. It may be a retransmitted Finished (the only
  557. * post-CCS message). Otherwise, it's a pre-CCS handshake message from an
  558. * unsupported renegotiation attempt. */
  559. if (rr->type == SSL3_RT_HANDSHAKE && !s->in_handshake) {
  560. if (rr->length < DTLS1_HM_HEADER_LENGTH) {
  561. al = SSL_AD_DECODE_ERROR;
  562. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  563. goto f_err;
  564. }
  565. struct hm_header_st msg_hdr;
  566. dtls1_get_message_header(&rr->data[rr->off], &msg_hdr);
  567. /* Ignore a stray Finished from the previous handshake. */
  568. if (msg_hdr.type == SSL3_MT_FINISHED) {
  569. if (msg_hdr.frag_off == 0) {
  570. /* Retransmit our last flight of messages. If the peer sends the second
  571. * Finished, they may not have received ours. Only do this for the
  572. * first fragment, in case the Finished was fragmented. */
  573. if (dtls1_check_timeout_num(s) < 0) {
  574. return -1;
  575. }
  576. dtls1_retransmit_buffered_messages(s);
  577. }
  578. rr->length = 0;
  579. goto start;
  580. }
  581. }
  582. /* We already handled these. */
  583. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT);
  584. al = SSL_AD_UNEXPECTED_MESSAGE;
  585. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  586. f_err:
  587. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  588. err:
  589. return -1;
  590. }
  591. int dtls1_write_app_data(SSL *s, const void *buf_, int len) {
  592. int i;
  593. if (SSL_in_init(s) && !s->in_handshake) {
  594. i = s->handshake_func(s);
  595. if (i < 0) {
  596. return i;
  597. }
  598. if (i == 0) {
  599. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  600. return -1;
  601. }
  602. }
  603. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  604. OPENSSL_PUT_ERROR(SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
  605. return -1;
  606. }
  607. i = dtls1_write_bytes(s, SSL3_RT_APPLICATION_DATA, buf_, len,
  608. dtls1_use_current_epoch);
  609. return i;
  610. }
  611. /* Call this to write data in records of type 'type' It will return <= 0 if not
  612. * all data has been sent or non-blocking IO. */
  613. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len,
  614. enum dtls1_use_epoch_t use_epoch) {
  615. int i;
  616. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  617. s->rwstate = SSL_NOTHING;
  618. i = do_dtls1_write(s, type, buf, len, use_epoch);
  619. return i;
  620. }
  621. /* dtls1_seal_record seals a new record of type |type| and plaintext |in| and
  622. * writes it to |out|. At most |max_out| bytes will be written. It returns one
  623. * on success and zero on error. On success, it updates the write sequence
  624. * number. */
  625. static int dtls1_seal_record(SSL *s, uint8_t *out, size_t *out_len,
  626. size_t max_out, uint8_t type, const uint8_t *in,
  627. size_t in_len, enum dtls1_use_epoch_t use_epoch) {
  628. if (max_out < DTLS1_RT_HEADER_LENGTH) {
  629. OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
  630. return 0;
  631. }
  632. /* Determine the parameters for the current epoch. */
  633. uint16_t epoch = s->d1->w_epoch;
  634. SSL_AEAD_CTX *aead = s->aead_write_ctx;
  635. uint8_t *seq = s->s3->write_sequence;
  636. if (use_epoch == dtls1_use_previous_epoch) {
  637. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  638. * (negotiated cipher) exist. */
  639. assert(s->d1->w_epoch == 1);
  640. epoch = s->d1->w_epoch - 1;
  641. aead = NULL;
  642. seq = s->d1->last_write_sequence;
  643. }
  644. out[0] = type;
  645. uint16_t wire_version = s->s3->have_version ? s->version : DTLS1_VERSION;
  646. out[1] = wire_version >> 8;
  647. out[2] = wire_version & 0xff;
  648. out[3] = epoch >> 8;
  649. out[4] = epoch & 0xff;
  650. memcpy(&out[5], &seq[2], 6);
  651. size_t ciphertext_len;
  652. if (!SSL_AEAD_CTX_seal(aead, out + DTLS1_RT_HEADER_LENGTH, &ciphertext_len,
  653. max_out - DTLS1_RT_HEADER_LENGTH, type, wire_version,
  654. &out[3] /* seq */, in, in_len) ||
  655. !ssl3_record_sequence_update(&seq[2], 6)) {
  656. return 0;
  657. }
  658. if (ciphertext_len >= 1 << 16) {
  659. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  660. return 0;
  661. }
  662. out[11] = ciphertext_len >> 8;
  663. out[12] = ciphertext_len & 0xff;
  664. *out_len = DTLS1_RT_HEADER_LENGTH + ciphertext_len;
  665. if (s->msg_callback) {
  666. s->msg_callback(1 /* write */, 0, SSL3_RT_HEADER, out,
  667. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  668. }
  669. return 1;
  670. }
  671. static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
  672. unsigned int len, enum dtls1_use_epoch_t use_epoch) {
  673. SSL3_BUFFER *wb = &s->s3->wbuf;
  674. /* ssl3_write_pending drops the write if |BIO_write| fails in DTLS, so there
  675. * is never pending data. */
  676. assert(s->s3->wbuf.left == 0);
  677. /* If we have an alert to send, lets send it */
  678. if (s->s3->alert_dispatch) {
  679. int ret = s->method->ssl_dispatch_alert(s);
  680. if (ret <= 0) {
  681. return ret;
  682. }
  683. /* if it went, fall through and send more stuff */
  684. }
  685. if (wb->buf == NULL && !ssl3_setup_write_buffer(s)) {
  686. return -1;
  687. }
  688. if (len == 0) {
  689. return 0;
  690. }
  691. /* Align the output so the ciphertext is aligned to |SSL3_ALIGN_PAYLOAD|. */
  692. uintptr_t align = (uintptr_t)wb->buf + DTLS1_RT_HEADER_LENGTH;
  693. align = (0 - align) & (SSL3_ALIGN_PAYLOAD - 1);
  694. uint8_t *out = wb->buf + align;
  695. wb->offset = align;
  696. size_t max_out = wb->len - wb->offset;
  697. size_t ciphertext_len;
  698. if (!dtls1_seal_record(s, out, &ciphertext_len, max_out, type, buf, len,
  699. use_epoch)) {
  700. return -1;
  701. }
  702. /* now let's set up wb */
  703. wb->left = ciphertext_len;
  704. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  705. * later */
  706. s->s3->wpend_tot = len;
  707. s->s3->wpend_buf = buf;
  708. s->s3->wpend_type = type;
  709. s->s3->wpend_ret = len;
  710. /* we now just need to write the buffer */
  711. return ssl3_write_pending(s, type, buf, len);
  712. }
  713. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) {
  714. int cmp;
  715. unsigned int shift;
  716. const uint8_t *seq = s->s3->read_sequence;
  717. cmp = satsub64be(seq, bitmap->max_seq_num);
  718. if (cmp > 0) {
  719. memcpy(s->s3->rrec.seq_num, seq, 8);
  720. return 1; /* this record in new */
  721. }
  722. shift = -cmp;
  723. if (shift >= sizeof(bitmap->map) * 8) {
  724. return 0; /* stale, outside the window */
  725. } else if (bitmap->map & (((uint64_t)1) << shift)) {
  726. return 0; /* record previously received */
  727. }
  728. memcpy(s->s3->rrec.seq_num, seq, 8);
  729. return 1;
  730. }
  731. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) {
  732. int cmp;
  733. unsigned int shift;
  734. const uint8_t *seq = s->s3->read_sequence;
  735. cmp = satsub64be(seq, bitmap->max_seq_num);
  736. if (cmp > 0) {
  737. shift = cmp;
  738. if (shift < sizeof(bitmap->map) * 8) {
  739. bitmap->map <<= shift, bitmap->map |= 1UL;
  740. } else {
  741. bitmap->map = 1UL;
  742. }
  743. memcpy(bitmap->max_seq_num, seq, 8);
  744. } else {
  745. shift = -cmp;
  746. if (shift < sizeof(bitmap->map) * 8) {
  747. bitmap->map |= ((uint64_t)1) << shift;
  748. }
  749. }
  750. }
  751. int dtls1_dispatch_alert(SSL *s) {
  752. int i, j;
  753. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  754. uint8_t buf[DTLS1_AL_HEADER_LENGTH];
  755. uint8_t *ptr = &buf[0];
  756. s->s3->alert_dispatch = 0;
  757. memset(buf, 0x00, sizeof(buf));
  758. *ptr++ = s->s3->send_alert[0];
  759. *ptr++ = s->s3->send_alert[1];
  760. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf),
  761. dtls1_use_current_epoch);
  762. if (i <= 0) {
  763. s->s3->alert_dispatch = 1;
  764. } else {
  765. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  766. (void)BIO_flush(s->wbio);
  767. }
  768. if (s->msg_callback) {
  769. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  770. s->msg_callback_arg);
  771. }
  772. if (s->info_callback != NULL) {
  773. cb = s->info_callback;
  774. } else if (s->ctx->info_callback != NULL) {
  775. cb = s->ctx->info_callback;
  776. }
  777. if (cb != NULL) {
  778. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  779. cb(s, SSL_CB_WRITE_ALERT, j);
  780. }
  781. }
  782. return i;
  783. }
  784. void dtls1_reset_seq_numbers(SSL *s, int rw) {
  785. uint8_t *seq;
  786. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  787. if (rw & SSL3_CC_READ) {
  788. seq = s->s3->read_sequence;
  789. s->d1->r_epoch++;
  790. memset(&s->d1->bitmap, 0, sizeof(DTLS1_BITMAP));
  791. } else {
  792. seq = s->s3->write_sequence;
  793. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  794. s->d1->w_epoch++;
  795. }
  796. memset(seq, 0x00, seq_bytes);
  797. }