Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

1790 righe
48 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 <stdio.h>
  112. #include <errno.h>
  113. #include <assert.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 "ssl_locl.h"
  120. /* mod 128 saturating subtract of two 64-bit values in big-endian order */
  121. static int satsub64be(const unsigned char *v1,const unsigned char *v2)
  122. { int ret,sat,brw,i;
  123. if (sizeof(long) == 8) do
  124. { const union { long one; char little; } is_endian = {1};
  125. long l;
  126. if (is_endian.little) break;
  127. /* not reached on little-endians */
  128. /* following test is redundant, because input is
  129. * always aligned, but I take no chances... */
  130. if (((size_t)v1|(size_t)v2)&0x7) break;
  131. l = *((long *)v1);
  132. l -= *((long *)v2);
  133. if (l>128) return 128;
  134. else if (l<-128) return -128;
  135. else return (int)l;
  136. } while (0);
  137. ret = (int)v1[7]-(int)v2[7];
  138. sat = 0;
  139. brw = ret>>8; /* brw is either 0 or -1 */
  140. if (ret & 0x80)
  141. { for (i=6;i>=0;i--)
  142. { brw += (int)v1[i]-(int)v2[i];
  143. sat |= ~brw;
  144. brw >>= 8;
  145. }
  146. }
  147. else
  148. { for (i=6;i>=0;i--)
  149. { brw += (int)v1[i]-(int)v2[i];
  150. sat |= brw;
  151. brw >>= 8;
  152. }
  153. }
  154. brw <<= 8; /* brw is either 0 or -256 */
  155. if (sat&0xff) return brw | 0x80;
  156. else return brw + (ret&0xFF);
  157. }
  158. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  159. int len, int peek);
  160. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  161. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  162. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  163. unsigned int *is_next_epoch);
  164. #if 0
  165. static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  166. unsigned short *priority, unsigned long *offset);
  167. #endif
  168. static int dtls1_buffer_record(SSL *s, record_pqueue *q,
  169. unsigned char *priority);
  170. static int dtls1_process_record(SSL *s);
  171. static int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  172. unsigned int len);
  173. /* copy buffered record into SSL structure */
  174. static int
  175. dtls1_copy_record(SSL *s, pitem *item)
  176. {
  177. DTLS1_RECORD_DATA *rdata;
  178. rdata = (DTLS1_RECORD_DATA *)item->data;
  179. if (s->s3->rbuf.buf != NULL)
  180. OPENSSL_free(s->s3->rbuf.buf);
  181. s->packet = rdata->packet;
  182. s->packet_length = rdata->packet_length;
  183. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  184. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  185. /* Set proper sequence number for mac calculation */
  186. memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
  187. return(1);
  188. }
  189. static int
  190. dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
  191. {
  192. DTLS1_RECORD_DATA *rdata;
  193. pitem *item;
  194. /* Limit the size of the queue to prevent DOS attacks */
  195. if (pqueue_size(queue->q) >= 100)
  196. return 0;
  197. rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
  198. item = pitem_new(priority, rdata);
  199. if (rdata == NULL || item == NULL)
  200. {
  201. if (rdata != NULL) OPENSSL_free(rdata);
  202. if (item != NULL) pitem_free(item);
  203. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  204. return(0);
  205. }
  206. rdata->packet = s->packet;
  207. rdata->packet_length = s->packet_length;
  208. memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
  209. memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
  210. item->data = rdata;
  211. /* insert should not fail, since duplicates are dropped */
  212. if (pqueue_insert(queue->q, item) == NULL)
  213. {
  214. OPENSSL_free(rdata);
  215. pitem_free(item);
  216. return(0);
  217. }
  218. s->packet = NULL;
  219. s->packet_length = 0;
  220. memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
  221. memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
  222. if (!ssl3_setup_buffers(s))
  223. {
  224. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  225. OPENSSL_free(rdata);
  226. pitem_free(item);
  227. return(0);
  228. }
  229. return(1);
  230. }
  231. static int
  232. dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
  233. {
  234. pitem *item;
  235. item = pqueue_pop(queue->q);
  236. if (item)
  237. {
  238. dtls1_copy_record(s, item);
  239. OPENSSL_free(item->data);
  240. pitem_free(item);
  241. return(1);
  242. }
  243. return(0);
  244. }
  245. /* retrieve a buffered record that belongs to the new epoch, i.e., not processed
  246. * yet */
  247. #define dtls1_get_unprocessed_record(s) \
  248. dtls1_retrieve_buffered_record((s), \
  249. &((s)->d1->unprocessed_rcds))
  250. /* retrieve a buffered record that belongs to the current epoch, ie, processed */
  251. #define dtls1_get_processed_record(s) \
  252. dtls1_retrieve_buffered_record((s), \
  253. &((s)->d1->processed_rcds))
  254. static int
  255. dtls1_process_buffered_records(SSL *s)
  256. {
  257. pitem *item;
  258. item = pqueue_peek(s->d1->unprocessed_rcds.q);
  259. if (item)
  260. {
  261. /* Check if epoch is current. */
  262. if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
  263. return(1); /* Nothing to do. */
  264. /* Process all the records. */
  265. while (pqueue_peek(s->d1->unprocessed_rcds.q))
  266. {
  267. dtls1_get_unprocessed_record(s);
  268. if ( ! dtls1_process_record(s))
  269. return(0);
  270. dtls1_buffer_record(s, &(s->d1->processed_rcds),
  271. s->s3->rrec.seq_num);
  272. }
  273. }
  274. /* sync epoch numbers once all the unprocessed records
  275. * have been processed */
  276. s->d1->processed_rcds.epoch = s->d1->r_epoch;
  277. s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
  278. return(1);
  279. }
  280. #if 0
  281. static int
  282. dtls1_get_buffered_record(SSL *s)
  283. {
  284. pitem *item;
  285. PQ_64BIT priority =
  286. (((PQ_64BIT)s->d1->handshake_read_seq) << 32) |
  287. ((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
  288. if ( ! SSL_in_init(s)) /* if we're not (re)negotiating,
  289. nothing buffered */
  290. return 0;
  291. item = pqueue_peek(s->d1->rcvd_records);
  292. if (item && item->priority == priority)
  293. {
  294. /* Check if we've received the record of interest. It must be
  295. * a handshake record, since data records as passed up without
  296. * buffering */
  297. DTLS1_RECORD_DATA *rdata;
  298. item = pqueue_pop(s->d1->rcvd_records);
  299. rdata = (DTLS1_RECORD_DATA *)item->data;
  300. if (s->s3->rbuf.buf != NULL)
  301. OPENSSL_free(s->s3->rbuf.buf);
  302. s->packet = rdata->packet;
  303. s->packet_length = rdata->packet_length;
  304. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  305. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  306. OPENSSL_free(item->data);
  307. pitem_free(item);
  308. /* s->d1->next_expected_seq_num++; */
  309. return(1);
  310. }
  311. return 0;
  312. }
  313. #endif
  314. static int
  315. dtls1_process_record(SSL *s)
  316. {
  317. int i,al;
  318. int enc_err;
  319. SSL_SESSION *sess;
  320. SSL3_RECORD *rr;
  321. unsigned int mac_size, orig_len;
  322. unsigned char md[EVP_MAX_MD_SIZE];
  323. rr= &(s->s3->rrec);
  324. sess = s->session;
  325. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  326. * and we have that many bytes in s->packet
  327. */
  328. rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
  329. /* ok, we can now read from 's->packet' data into 'rr'
  330. * rr->input points at rr->length bytes, which
  331. * need to be copied into rr->data by either
  332. * the decryption or by the decompression
  333. * When the data is 'copied' into the rr->data buffer,
  334. * rr->input will be pointed at the new buffer */
  335. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  336. * rr->length bytes of encrypted compressed stuff. */
  337. /* check is not needed I believe */
  338. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  339. {
  340. al=SSL_AD_RECORD_OVERFLOW;
  341. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  342. goto f_err;
  343. }
  344. /* decrypt in place in 'rr->input' */
  345. rr->data=rr->input;
  346. enc_err = s->method->ssl3_enc->enc(s,0);
  347. /* enc_err is:
  348. * 0: (in non-constant time) if the record is publically invalid.
  349. * 1: if the padding is valid
  350. * -1: if the padding is invalid */
  351. if (enc_err == 0)
  352. {
  353. /* For DTLS we simply ignore bad packets. */
  354. rr->length = 0;
  355. s->packet_length = 0;
  356. goto err;
  357. }
  358. #ifdef TLS_DEBUG
  359. printf("dec %d\n",rr->length);
  360. { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
  361. printf("\n");
  362. #endif
  363. /* r->length is now the compressed data plus mac */
  364. if ((sess != NULL) &&
  365. (s->enc_read_ctx != NULL) &&
  366. (EVP_MD_CTX_md(s->read_hash) != NULL))
  367. {
  368. /* s->read_hash != NULL => mac_size != -1 */
  369. unsigned char *mac = NULL;
  370. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  371. mac_size=EVP_MD_CTX_size(s->read_hash);
  372. assert(mac_size <= EVP_MAX_MD_SIZE);
  373. /* kludge: *_cbc_remove_padding passes padding length in rr->type */
  374. orig_len = rr->length+((unsigned int)rr->type>>8);
  375. /* orig_len is the length of the record before any padding was
  376. * removed. This is public information, as is the MAC in use,
  377. * therefore we can safely process the record in a different
  378. * amount of time if it's too short to possibly contain a MAC.
  379. */
  380. if (orig_len < mac_size ||
  381. /* CBC records must have a padding length byte too. */
  382. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  383. orig_len < mac_size+1))
  384. {
  385. al=SSL_AD_DECODE_ERROR;
  386. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_LENGTH_TOO_SHORT);
  387. goto f_err;
  388. }
  389. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
  390. {
  391. /* We update the length so that the TLS header bytes
  392. * can be constructed correctly but we need to extract
  393. * the MAC in constant time from within the record,
  394. * without leaking the contents of the padding bytes.
  395. * */
  396. mac = mac_tmp;
  397. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  398. rr->length -= mac_size;
  399. }
  400. else
  401. {
  402. /* In this case there's no padding, so |orig_len|
  403. * equals |rec->length| and we checked that there's
  404. * enough bytes for |mac_size| above. */
  405. rr->length -= mac_size;
  406. mac = &rr->data[rr->length];
  407. }
  408. i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
  409. if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  410. enc_err = -1;
  411. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
  412. enc_err = -1;
  413. }
  414. if (enc_err < 0)
  415. {
  416. /* decryption failed, silently discard message */
  417. rr->length = 0;
  418. s->packet_length = 0;
  419. goto err;
  420. }
  421. /* r->length is now just compressed */
  422. if (s->expand != NULL)
  423. {
  424. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
  425. {
  426. al=SSL_AD_RECORD_OVERFLOW;
  427. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  428. goto f_err;
  429. }
  430. if (!ssl3_do_uncompress(s))
  431. {
  432. al=SSL_AD_DECOMPRESSION_FAILURE;
  433. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_BAD_DECOMPRESSION);
  434. goto f_err;
  435. }
  436. }
  437. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
  438. {
  439. al=SSL_AD_RECORD_OVERFLOW;
  440. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_DATA_LENGTH_TOO_LONG);
  441. goto f_err;
  442. }
  443. rr->off=0;
  444. /* So at this point the following is true
  445. * ssl->s3->rrec.type is the type of record
  446. * ssl->s3->rrec.length == number of bytes in record
  447. * ssl->s3->rrec.off == offset to first valid byte
  448. * ssl->s3->rrec.data == where to take bytes from, increment
  449. * after use :-).
  450. */
  451. /* we have pulled in a full packet so zero things */
  452. s->packet_length=0;
  453. dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
  454. return(1);
  455. f_err:
  456. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  457. err:
  458. return(0);
  459. }
  460. /* Call this to get a new input record.
  461. * It will return <= 0 if more data is needed, normally due to an error
  462. * or non-blocking IO.
  463. * When it finishes, one packet has been decoded and can be found in
  464. * ssl->s3->rrec.type - is the type of record
  465. * ssl->s3->rrec.data, - data
  466. * ssl->s3->rrec.length, - number of bytes
  467. */
  468. /* used only by dtls1_read_bytes */
  469. int dtls1_get_record(SSL *s)
  470. {
  471. int ssl_major,ssl_minor;
  472. int i,n;
  473. SSL3_RECORD *rr;
  474. unsigned char *p = NULL;
  475. unsigned short version;
  476. DTLS1_BITMAP *bitmap;
  477. unsigned int is_next_epoch;
  478. rr= &(s->s3->rrec);
  479. /* The epoch may have changed. If so, process all the
  480. * pending records. This is a non-blocking operation. */
  481. dtls1_process_buffered_records(s);
  482. /* if we're renegotiating, then there may be buffered records */
  483. if (dtls1_get_processed_record(s))
  484. return 1;
  485. /* get something from the wire */
  486. again:
  487. /* check if we have the header */
  488. if ( (s->rstate != SSL_ST_READ_BODY) ||
  489. (s->packet_length < DTLS1_RT_HEADER_LENGTH))
  490. {
  491. n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  492. /* read timeout is handled by dtls1_read_bytes */
  493. if (n <= 0) return(n); /* error or non-blocking */
  494. /* this packet contained a partial record, dump it */
  495. if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
  496. {
  497. s->packet_length = 0;
  498. goto again;
  499. }
  500. s->rstate=SSL_ST_READ_BODY;
  501. p=s->packet;
  502. if (s->msg_callback)
  503. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  504. /* Pull apart the header into the DTLS1_RECORD */
  505. rr->type= *(p++);
  506. ssl_major= *(p++);
  507. ssl_minor= *(p++);
  508. version=(ssl_major<<8)|ssl_minor;
  509. /* sequence number is 64 bits, with top 2 bytes = epoch */
  510. n2s(p,rr->epoch);
  511. memcpy(&(s->s3->read_sequence[2]), p, 6);
  512. p+=6;
  513. n2s(p,rr->length);
  514. /* Lets check version */
  515. if (!s->first_packet)
  516. {
  517. if (version != s->version)
  518. {
  519. /* unexpected version, silently discard */
  520. rr->length = 0;
  521. s->packet_length = 0;
  522. goto again;
  523. }
  524. }
  525. if ((version & 0xff00) != (s->version & 0xff00))
  526. {
  527. /* wrong version, silently discard record */
  528. rr->length = 0;
  529. s->packet_length = 0;
  530. goto again;
  531. }
  532. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  533. {
  534. /* record too long, silently discard it */
  535. rr->length = 0;
  536. s->packet_length = 0;
  537. goto again;
  538. }
  539. /* now s->rstate == SSL_ST_READ_BODY */
  540. }
  541. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  542. if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
  543. {
  544. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  545. i=rr->length;
  546. n=ssl3_read_n(s,i,i,1);
  547. if (n <= 0) return(n); /* error or non-blocking io */
  548. /* this packet contained a partial record, dump it */
  549. if ( n != i)
  550. {
  551. rr->length = 0;
  552. s->packet_length = 0;
  553. goto again;
  554. }
  555. /* now n == rr->length,
  556. * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
  557. }
  558. s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
  559. /* match epochs. NULL means the packet is dropped on the floor */
  560. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  561. if ( bitmap == NULL)
  562. {
  563. rr->length = 0;
  564. s->packet_length = 0; /* dump this record */
  565. goto again; /* get another record */
  566. }
  567. /* Check whether this is a repeat, or aged record.
  568. * Don't check if we're listening and this message is
  569. * a ClientHello. They can look as if they're replayed,
  570. * since they arrive from different connections and
  571. * would be dropped unnecessarily.
  572. */
  573. if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
  574. *p == SSL3_MT_CLIENT_HELLO) &&
  575. !dtls1_record_replay_check(s, bitmap))
  576. {
  577. rr->length = 0;
  578. s->packet_length=0; /* dump this record */
  579. goto again; /* get another record */
  580. }
  581. /* just read a 0 length packet */
  582. if (rr->length == 0) goto again;
  583. /* If this record is from the next epoch (either HM or ALERT),
  584. * and a handshake is currently in progress, buffer it since it
  585. * cannot be processed at this time. However, do not buffer
  586. * anything while listening.
  587. */
  588. if (is_next_epoch)
  589. {
  590. if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
  591. {
  592. dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
  593. }
  594. rr->length = 0;
  595. s->packet_length = 0;
  596. goto again;
  597. }
  598. if (!dtls1_process_record(s))
  599. {
  600. rr->length = 0;
  601. s->packet_length = 0; /* dump this record */
  602. goto again; /* get another record */
  603. }
  604. return(1);
  605. }
  606. /* Return up to 'len' payload bytes received in 'type' records.
  607. * 'type' is one of the following:
  608. *
  609. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  610. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  611. * - 0 (during a shutdown, no data has to be returned)
  612. *
  613. * If we don't have stored data to work from, read a SSL/TLS record first
  614. * (possibly multiple records if we still don't have anything to return).
  615. *
  616. * This function must handle any surprises the peer may have for us, such as
  617. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  618. * a surprise, but handled as if it were), or renegotiation requests.
  619. * Also if record payloads contain fragments too small to process, we store
  620. * them until there is enough for the respective protocol (the record protocol
  621. * may use arbitrary fragmentation and even interleaving):
  622. * Change cipher spec protocol
  623. * just 1 byte needed, no need for keeping anything stored
  624. * Alert protocol
  625. * 2 bytes needed (AlertLevel, AlertDescription)
  626. * Handshake protocol
  627. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  628. * to detect unexpected Client Hello and Hello Request messages
  629. * here, anything else is handled by higher layers
  630. * Application data protocol
  631. * none of our business
  632. */
  633. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  634. {
  635. int al,i,j,ret;
  636. unsigned int n;
  637. SSL3_RECORD *rr;
  638. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  639. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  640. if (!ssl3_setup_buffers(s))
  641. return(-1);
  642. /* XXX: check what the second '&& type' is about */
  643. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  644. (type != SSL3_RT_HANDSHAKE) && type) ||
  645. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  646. {
  647. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
  648. return -1;
  649. }
  650. /* check whether there's a handshake message (client hello?) waiting */
  651. if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
  652. return ret;
  653. /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  654. if (!s->in_handshake && SSL_in_init(s))
  655. {
  656. /* type == SSL3_RT_APPLICATION_DATA */
  657. i=s->handshake_func(s);
  658. if (i < 0) return(i);
  659. if (i == 0)
  660. {
  661. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  662. return(-1);
  663. }
  664. }
  665. start:
  666. s->rwstate=SSL_NOTHING;
  667. /* s->s3->rrec.type - is the type of record
  668. * s->s3->rrec.data, - data
  669. * s->s3->rrec.off, - offset into 'data' for next read
  670. * s->s3->rrec.length, - number of bytes. */
  671. rr = &(s->s3->rrec);
  672. /* We are not handshaking and have no data yet,
  673. * so process data buffered during the last handshake
  674. * in advance, if any.
  675. */
  676. if (s->state == SSL_ST_OK && rr->length == 0)
  677. {
  678. pitem *item;
  679. item = pqueue_pop(s->d1->buffered_app_data.q);
  680. if (item)
  681. {
  682. dtls1_copy_record(s, item);
  683. OPENSSL_free(item->data);
  684. pitem_free(item);
  685. }
  686. }
  687. /* Check for timeout */
  688. if (dtls1_handle_timeout(s) > 0)
  689. goto start;
  690. /* get new packet if necessary */
  691. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  692. {
  693. ret=dtls1_get_record(s);
  694. if (ret <= 0)
  695. {
  696. ret = dtls1_read_failed(s, ret);
  697. /* anything other than a timeout is an error */
  698. if (ret <= 0)
  699. return(ret);
  700. else
  701. goto start;
  702. }
  703. }
  704. if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE)
  705. {
  706. rr->length = 0;
  707. goto start;
  708. }
  709. /* we now have a packet which can be read and processed */
  710. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  711. * reset by ssl3_get_finished */
  712. && (rr->type != SSL3_RT_HANDSHAKE))
  713. {
  714. /* We now have application data between CCS and Finished.
  715. * Most likely the packets were reordered on their way, so
  716. * buffer the application data for later processing rather
  717. * than dropping the connection.
  718. */
  719. dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num);
  720. rr->length = 0;
  721. goto start;
  722. }
  723. /* If the other end has shut down, throw anything we read away
  724. * (even in 'peek' mode) */
  725. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  726. {
  727. rr->length=0;
  728. s->rwstate=SSL_NOTHING;
  729. return(0);
  730. }
  731. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  732. {
  733. /* make sure that we are not getting application data when we
  734. * are doing a handshake for the first time */
  735. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  736. (s->enc_read_ctx == NULL))
  737. {
  738. al=SSL_AD_UNEXPECTED_MESSAGE;
  739. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  740. goto f_err;
  741. }
  742. if (len <= 0) return(len);
  743. if ((unsigned int)len > rr->length)
  744. n = rr->length;
  745. else
  746. n = (unsigned int)len;
  747. memcpy(buf,&(rr->data[rr->off]),n);
  748. if (!peek)
  749. {
  750. rr->length-=n;
  751. rr->off+=n;
  752. if (rr->length == 0)
  753. {
  754. s->rstate=SSL_ST_READ_HEADER;
  755. rr->off=0;
  756. }
  757. }
  758. return(n);
  759. }
  760. /* If we get here, then type != rr->type; if we have a handshake
  761. * message, then it was unexpected (Hello Request or Client Hello). */
  762. /* In case of record types for which we have 'fragment' storage,
  763. * fill that so that we can process the data at a fixed place.
  764. */
  765. {
  766. unsigned int k, dest_maxlen = 0;
  767. unsigned char *dest = NULL;
  768. unsigned int *dest_len = NULL;
  769. if (rr->type == SSL3_RT_HANDSHAKE)
  770. {
  771. dest_maxlen = sizeof s->d1->handshake_fragment;
  772. dest = s->d1->handshake_fragment;
  773. dest_len = &s->d1->handshake_fragment_len;
  774. }
  775. else if (rr->type == SSL3_RT_ALERT)
  776. {
  777. dest_maxlen = sizeof(s->d1->alert_fragment);
  778. dest = s->d1->alert_fragment;
  779. dest_len = &s->d1->alert_fragment_len;
  780. }
  781. #ifndef OPENSSL_NO_HEARTBEATS
  782. else if (rr->type == TLS1_RT_HEARTBEAT)
  783. {
  784. dtls1_process_heartbeat(s);
  785. /* Exit and notify application to read again */
  786. rr->length = 0;
  787. s->rwstate=SSL_READING;
  788. BIO_clear_retry_flags(SSL_get_rbio(s));
  789. BIO_set_retry_read(SSL_get_rbio(s));
  790. return(-1);
  791. }
  792. #endif
  793. /* else it's a CCS message, or application data or wrong */
  794. else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
  795. {
  796. /* Application data while renegotiating
  797. * is allowed. Try again reading.
  798. */
  799. if (rr->type == SSL3_RT_APPLICATION_DATA)
  800. {
  801. BIO *bio;
  802. s->s3->in_read_app_data=2;
  803. bio=SSL_get_rbio(s);
  804. s->rwstate=SSL_READING;
  805. BIO_clear_retry_flags(bio);
  806. BIO_set_retry_read(bio);
  807. return(-1);
  808. }
  809. /* Not certain if this is the right error handling */
  810. al=SSL_AD_UNEXPECTED_MESSAGE;
  811. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  812. goto f_err;
  813. }
  814. if (dest_maxlen > 0)
  815. {
  816. /* XDTLS: In a pathalogical case, the Client Hello
  817. * may be fragmented--don't always expect dest_maxlen bytes */
  818. if ( rr->length < dest_maxlen)
  819. {
  820. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  821. /*
  822. * for normal alerts rr->length is 2, while
  823. * dest_maxlen is 7 if we were to handle this
  824. * non-existing alert...
  825. */
  826. FIX ME
  827. #endif
  828. s->rstate=SSL_ST_READ_HEADER;
  829. rr->length = 0;
  830. goto start;
  831. }
  832. /* now move 'n' bytes: */
  833. for ( k = 0; k < dest_maxlen; k++)
  834. {
  835. dest[k] = rr->data[rr->off++];
  836. rr->length--;
  837. }
  838. *dest_len = dest_maxlen;
  839. }
  840. }
  841. /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  842. * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  843. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  844. /* If we are a client, check for an incoming 'Hello Request': */
  845. if ((!s->server) &&
  846. (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  847. (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  848. (s->session != NULL) && (s->session->cipher != NULL))
  849. {
  850. s->d1->handshake_fragment_len = 0;
  851. if ((s->d1->handshake_fragment[1] != 0) ||
  852. (s->d1->handshake_fragment[2] != 0) ||
  853. (s->d1->handshake_fragment[3] != 0))
  854. {
  855. al=SSL_AD_DECODE_ERROR;
  856. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  857. goto err;
  858. }
  859. /* no need to check sequence number on HELLO REQUEST messages */
  860. if (s->msg_callback)
  861. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  862. s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
  863. if (SSL_is_init_finished(s) &&
  864. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  865. !s->s3->renegotiate)
  866. {
  867. s->d1->handshake_read_seq++;
  868. s->new_session = 1;
  869. ssl3_renegotiate(s);
  870. if (ssl3_renegotiate_check(s))
  871. {
  872. i=s->handshake_func(s);
  873. if (i < 0) return(i);
  874. if (i == 0)
  875. {
  876. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  877. return(-1);
  878. }
  879. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  880. {
  881. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  882. {
  883. BIO *bio;
  884. /* In the case where we try to read application data,
  885. * but we trigger an SSL handshake, we return -1 with
  886. * the retry option set. Otherwise renegotiation may
  887. * cause nasty problems in the blocking world */
  888. s->rwstate=SSL_READING;
  889. bio=SSL_get_rbio(s);
  890. BIO_clear_retry_flags(bio);
  891. BIO_set_retry_read(bio);
  892. return(-1);
  893. }
  894. }
  895. }
  896. }
  897. /* we either finished a handshake or ignored the request,
  898. * now try again to obtain the (application) data we were asked for */
  899. goto start;
  900. }
  901. if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
  902. {
  903. int alert_level = s->d1->alert_fragment[0];
  904. int alert_descr = s->d1->alert_fragment[1];
  905. s->d1->alert_fragment_len = 0;
  906. if (s->msg_callback)
  907. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  908. s->d1->alert_fragment, 2, s, s->msg_callback_arg);
  909. if (s->info_callback != NULL)
  910. cb=s->info_callback;
  911. else if (s->ctx->info_callback != NULL)
  912. cb=s->ctx->info_callback;
  913. if (cb != NULL)
  914. {
  915. j = (alert_level << 8) | alert_descr;
  916. cb(s, SSL_CB_READ_ALERT, j);
  917. }
  918. if (alert_level == 1) /* warning */
  919. {
  920. s->s3->warn_alert = alert_descr;
  921. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  922. {
  923. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  924. return(0);
  925. }
  926. #if 0
  927. /* XXX: this is a possible improvement in the future */
  928. /* now check if it's a missing record */
  929. if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
  930. {
  931. unsigned short seq;
  932. unsigned int frag_off;
  933. unsigned char *p = &(s->d1->alert_fragment[2]);
  934. n2s(p, seq);
  935. n2l3(p, frag_off);
  936. dtls1_retransmit_message(s,
  937. dtls1_get_queue_priority(frag->msg_header.seq, 0),
  938. frag_off, &found);
  939. if ( ! found && SSL_in_init(s))
  940. {
  941. /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
  942. /* requested a message not yet sent,
  943. send an alert ourselves */
  944. ssl3_send_alert(s,SSL3_AL_WARNING,
  945. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  946. }
  947. }
  948. #endif
  949. }
  950. else if (alert_level == 2) /* fatal */
  951. {
  952. char tmp[16];
  953. s->rwstate=SSL_NOTHING;
  954. s->s3->fatal_alert = alert_descr;
  955. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
  956. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  957. ERR_add_error_data(2,"SSL alert number ",tmp);
  958. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  959. SSL_CTX_remove_session(s->ctx,s->session);
  960. return(0);
  961. }
  962. else
  963. {
  964. al=SSL_AD_ILLEGAL_PARAMETER;
  965. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  966. goto f_err;
  967. }
  968. goto start;
  969. }
  970. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  971. {
  972. s->rwstate=SSL_NOTHING;
  973. rr->length=0;
  974. return(0);
  975. }
  976. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  977. {
  978. struct ccs_header_st ccs_hdr;
  979. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  980. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  981. if (s->version == DTLS1_BAD_VER)
  982. ccs_hdr_len = 3;
  983. /* 'Change Cipher Spec' is just a single byte, so we know
  984. * exactly what the record payload has to look like */
  985. /* XDTLS: check that epoch is consistent */
  986. if ( (rr->length != ccs_hdr_len) ||
  987. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
  988. {
  989. i=SSL_AD_ILLEGAL_PARAMETER;
  990. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  991. goto err;
  992. }
  993. rr->length=0;
  994. if (s->msg_callback)
  995. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  996. rr->data, 1, s, s->msg_callback_arg);
  997. /* We can't process a CCS now, because previous handshake
  998. * messages are still missing, so just drop it.
  999. */
  1000. if (!s->d1->change_cipher_spec_ok)
  1001. {
  1002. goto start;
  1003. }
  1004. s->d1->change_cipher_spec_ok = 0;
  1005. s->s3->change_cipher_spec=1;
  1006. if (!ssl3_do_change_cipher_spec(s))
  1007. goto err;
  1008. /* do this whenever CCS is processed */
  1009. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  1010. if (s->version == DTLS1_BAD_VER)
  1011. s->d1->handshake_read_seq++;
  1012. goto start;
  1013. }
  1014. /* Unexpected handshake message (Client Hello, or protocol violation) */
  1015. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  1016. !s->in_handshake)
  1017. {
  1018. struct hm_header_st msg_hdr;
  1019. /* this may just be a stale retransmit */
  1020. dtls1_get_message_header(rr->data, &msg_hdr);
  1021. if( rr->epoch != s->d1->r_epoch)
  1022. {
  1023. rr->length = 0;
  1024. goto start;
  1025. }
  1026. /* If we are server, we may have a repeated FINISHED of the
  1027. * client here, then retransmit our CCS and FINISHED.
  1028. */
  1029. if (msg_hdr.type == SSL3_MT_FINISHED)
  1030. {
  1031. if (dtls1_check_timeout_num(s) < 0)
  1032. return -1;
  1033. dtls1_retransmit_buffered_messages(s);
  1034. rr->length = 0;
  1035. goto start;
  1036. }
  1037. if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
  1038. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
  1039. {
  1040. #if 0 /* worked only because C operator preferences are not as expected (and
  1041. * because this is not really needed for clients except for detecting
  1042. * protocol violations): */
  1043. s->state=SSL_ST_BEFORE|(s->server)
  1044. ?SSL_ST_ACCEPT
  1045. :SSL_ST_CONNECT;
  1046. #else
  1047. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1048. #endif
  1049. s->renegotiate=1;
  1050. s->new_session=1;
  1051. }
  1052. i=s->handshake_func(s);
  1053. if (i < 0) return(i);
  1054. if (i == 0)
  1055. {
  1056. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1057. return(-1);
  1058. }
  1059. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  1060. {
  1061. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  1062. {
  1063. BIO *bio;
  1064. /* In the case where we try to read application data,
  1065. * but we trigger an SSL handshake, we return -1 with
  1066. * the retry option set. Otherwise renegotiation may
  1067. * cause nasty problems in the blocking world */
  1068. s->rwstate=SSL_READING;
  1069. bio=SSL_get_rbio(s);
  1070. BIO_clear_retry_flags(bio);
  1071. BIO_set_retry_read(bio);
  1072. return(-1);
  1073. }
  1074. }
  1075. goto start;
  1076. }
  1077. switch (rr->type)
  1078. {
  1079. default:
  1080. #ifndef OPENSSL_NO_TLS
  1081. /* TLS just ignores unknown message types */
  1082. if (s->version == TLS1_VERSION)
  1083. {
  1084. rr->length = 0;
  1085. goto start;
  1086. }
  1087. #endif
  1088. al=SSL_AD_UNEXPECTED_MESSAGE;
  1089. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1090. goto f_err;
  1091. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1092. case SSL3_RT_ALERT:
  1093. case SSL3_RT_HANDSHAKE:
  1094. /* we already handled all of these, with the possible exception
  1095. * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
  1096. * should not happen when type != rr->type */
  1097. al=SSL_AD_UNEXPECTED_MESSAGE;
  1098. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
  1099. goto f_err;
  1100. case SSL3_RT_APPLICATION_DATA:
  1101. /* At this point, we were expecting handshake data,
  1102. * but have application data. If the library was
  1103. * running inside ssl3_read() (i.e. in_read_app_data
  1104. * is set) and it makes sense to read application data
  1105. * at this point (session renegotiation not yet started),
  1106. * we will indulge it.
  1107. */
  1108. if (s->s3->in_read_app_data &&
  1109. (s->s3->total_renegotiations != 0) &&
  1110. ((
  1111. (s->state & SSL_ST_CONNECT) &&
  1112. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1113. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1114. ) || (
  1115. (s->state & SSL_ST_ACCEPT) &&
  1116. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1117. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1118. )
  1119. ))
  1120. {
  1121. s->s3->in_read_app_data=2;
  1122. return(-1);
  1123. }
  1124. else
  1125. {
  1126. al=SSL_AD_UNEXPECTED_MESSAGE;
  1127. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1128. goto f_err;
  1129. }
  1130. }
  1131. /* not reached */
  1132. f_err:
  1133. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1134. err:
  1135. return(-1);
  1136. }
  1137. int
  1138. dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
  1139. {
  1140. int i;
  1141. if (SSL_in_init(s) && !s->in_handshake)
  1142. {
  1143. i=s->handshake_func(s);
  1144. if (i < 0) return(i);
  1145. if (i == 0)
  1146. {
  1147. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1148. return -1;
  1149. }
  1150. }
  1151. if (len > SSL3_RT_MAX_PLAIN_LENGTH)
  1152. {
  1153. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes, SSL_R_DTLS_MESSAGE_TOO_BIG);
  1154. return -1;
  1155. }
  1156. i = dtls1_write_bytes(s, type, buf_, len);
  1157. return i;
  1158. }
  1159. /* this only happens when a client hello is received and a handshake
  1160. * is started. */
  1161. static int
  1162. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1163. int len, int peek)
  1164. {
  1165. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1166. /* (partially) satisfy request from storage */
  1167. {
  1168. unsigned char *src = s->d1->handshake_fragment;
  1169. unsigned char *dst = buf;
  1170. unsigned int k,n;
  1171. /* peek == 0 */
  1172. n = 0;
  1173. while ((len > 0) && (s->d1->handshake_fragment_len > 0))
  1174. {
  1175. *dst++ = *src++;
  1176. len--; s->d1->handshake_fragment_len--;
  1177. n++;
  1178. }
  1179. /* move any remaining fragment bytes: */
  1180. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1181. s->d1->handshake_fragment[k] = *src++;
  1182. return n;
  1183. }
  1184. return 0;
  1185. }
  1186. /* Call this to write data in records of type 'type'
  1187. * It will return <= 0 if not all data has been sent or non-blocking IO.
  1188. */
  1189. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1190. {
  1191. int i;
  1192. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1193. s->rwstate=SSL_NOTHING;
  1194. i=do_dtls1_write(s, type, buf, len);
  1195. return i;
  1196. }
  1197. static int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  1198. unsigned int len)
  1199. {
  1200. unsigned char *p,*pseq;
  1201. int i,mac_size,clear=0;
  1202. int prefix_len = 0;
  1203. int eivlen;
  1204. SSL3_RECORD *wr;
  1205. SSL3_BUFFER *wb;
  1206. SSL_SESSION *sess;
  1207. /* first check if there is a SSL3_BUFFER still being written
  1208. * out. This will happen with non blocking IO */
  1209. if (s->s3->wbuf.left != 0)
  1210. {
  1211. assert(0); /* XDTLS: want to see if we ever get here */
  1212. return(ssl3_write_pending(s,type,buf,len));
  1213. }
  1214. /* If we have an alert to send, lets send it */
  1215. if (s->s3->alert_dispatch)
  1216. {
  1217. i=s->method->ssl_dispatch_alert(s);
  1218. if (i <= 0)
  1219. return(i);
  1220. /* if it went, fall through and send more stuff */
  1221. }
  1222. if (len == 0)
  1223. return 0;
  1224. wr= &(s->s3->wrec);
  1225. wb= &(s->s3->wbuf);
  1226. sess=s->session;
  1227. if ( (sess == NULL) ||
  1228. (s->enc_write_ctx == NULL) ||
  1229. (EVP_MD_CTX_md(s->write_hash) == NULL))
  1230. clear=1;
  1231. if (clear)
  1232. mac_size=0;
  1233. else
  1234. {
  1235. mac_size=EVP_MD_CTX_size(s->write_hash);
  1236. if (mac_size < 0)
  1237. goto err;
  1238. }
  1239. p = wb->buf + prefix_len;
  1240. /* write the header */
  1241. *(p++)=type&0xff;
  1242. wr->type=type;
  1243. /* Special case: for hello verify request, client version 1.0 and
  1244. * we haven't decided which version to use yet send back using
  1245. * version 1.0 header: otherwise some clients will ignore it.
  1246. */
  1247. if (s->method->version == DTLS_ANY_VERSION)
  1248. {
  1249. *(p++)=DTLS1_VERSION>>8;
  1250. *(p++)=DTLS1_VERSION&0xff;
  1251. }
  1252. else
  1253. {
  1254. *(p++)=s->version>>8;
  1255. *(p++)=s->version&0xff;
  1256. }
  1257. /* field where we are to write out packet epoch, seq num and len */
  1258. pseq=p;
  1259. p+=10;
  1260. /* Explicit IV length, block ciphers appropriate version flag */
  1261. if (s->enc_write_ctx)
  1262. {
  1263. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  1264. if (mode == EVP_CIPH_CBC_MODE)
  1265. {
  1266. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  1267. if (eivlen <= 1)
  1268. eivlen = 0;
  1269. }
  1270. /* Need explicit part of IV for GCM mode */
  1271. else if (mode == EVP_CIPH_GCM_MODE)
  1272. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1273. else
  1274. eivlen = 0;
  1275. }
  1276. else
  1277. eivlen = 0;
  1278. /* lets setup the record stuff. */
  1279. wr->data=p + eivlen; /* make room for IV in case of CBC */
  1280. wr->length=(int)len;
  1281. wr->input=(unsigned char *)buf;
  1282. /* we now 'read' from wr->input, wr->length bytes into
  1283. * wr->data */
  1284. /* first we compress */
  1285. if (s->compress != NULL)
  1286. {
  1287. if (!ssl3_do_compress(s))
  1288. {
  1289. OPENSSL_PUT_ERROR(SSL, do_dtls1_write, SSL_R_COMPRESSION_FAILURE);
  1290. goto err;
  1291. }
  1292. }
  1293. else
  1294. {
  1295. memcpy(wr->data,wr->input,wr->length);
  1296. wr->input=wr->data;
  1297. }
  1298. /* we should still have the output to wr->data and the input
  1299. * from wr->input. Length should be wr->length.
  1300. * wr->data still points in the wb->buf */
  1301. if (mac_size != 0)
  1302. {
  1303. if(s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
  1304. goto err;
  1305. wr->length+=mac_size;
  1306. }
  1307. /* this is true regardless of mac size */
  1308. wr->input=p;
  1309. wr->data=p;
  1310. if (eivlen)
  1311. wr->length += eivlen;
  1312. s->method->ssl3_enc->enc(s,1);
  1313. /* record length after mac and block padding */
  1314. /* if (type == SSL3_RT_APPLICATION_DATA ||
  1315. (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
  1316. /* there's only one epoch between handshake and app data */
  1317. s2n(s->d1->w_epoch, pseq);
  1318. /* XDTLS: ?? */
  1319. /* else
  1320. s2n(s->d1->handshake_epoch, pseq); */
  1321. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1322. pseq+=6;
  1323. s2n(wr->length,pseq);
  1324. if (s->msg_callback)
  1325. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1326. /* we should now have
  1327. * wr->data pointing to the encrypted data, which is
  1328. * wr->length long */
  1329. wr->type=type; /* not needed but helps for debugging */
  1330. wr->length+=DTLS1_RT_HEADER_LENGTH;
  1331. #if 0 /* this is now done at the message layer */
  1332. /* buffer the record, making it easy to handle retransmits */
  1333. if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1334. dtls1_buffer_record(s, wr->data, wr->length,
  1335. *((PQ_64BIT *)&(s->s3->write_sequence[0])));
  1336. #endif
  1337. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1338. /* now let's set up wb */
  1339. wb->left = prefix_len + wr->length;
  1340. wb->offset = 0;
  1341. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  1342. s->s3->wpend_tot=len;
  1343. s->s3->wpend_buf=buf;
  1344. s->s3->wpend_type=type;
  1345. s->s3->wpend_ret=len;
  1346. /* we now just need to write the buffer */
  1347. return ssl3_write_pending(s,type,buf,len);
  1348. err:
  1349. return -1;
  1350. }
  1351. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1352. {
  1353. int cmp;
  1354. unsigned int shift;
  1355. const unsigned char *seq = s->s3->read_sequence;
  1356. cmp = satsub64be(seq,bitmap->max_seq_num);
  1357. if (cmp > 0)
  1358. {
  1359. memcpy (s->s3->rrec.seq_num,seq,8);
  1360. return 1; /* this record in new */
  1361. }
  1362. shift = -cmp;
  1363. if (shift >= sizeof(bitmap->map)*8)
  1364. return 0; /* stale, outside the window */
  1365. else if (bitmap->map & (1UL<<shift))
  1366. return 0; /* record previously received */
  1367. memcpy (s->s3->rrec.seq_num,seq,8);
  1368. return 1;
  1369. }
  1370. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1371. {
  1372. int cmp;
  1373. unsigned int shift;
  1374. const unsigned char *seq = s->s3->read_sequence;
  1375. cmp = satsub64be(seq,bitmap->max_seq_num);
  1376. if (cmp > 0)
  1377. {
  1378. shift = cmp;
  1379. if (shift < sizeof(bitmap->map)*8)
  1380. bitmap->map <<= shift, bitmap->map |= 1UL;
  1381. else
  1382. bitmap->map = 1UL;
  1383. memcpy(bitmap->max_seq_num,seq,8);
  1384. }
  1385. else {
  1386. shift = -cmp;
  1387. if (shift < sizeof(bitmap->map)*8)
  1388. bitmap->map |= 1UL<<shift;
  1389. }
  1390. }
  1391. int dtls1_dispatch_alert(SSL *s)
  1392. {
  1393. int i,j;
  1394. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1395. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1396. unsigned char *ptr = &buf[0];
  1397. s->s3->alert_dispatch=0;
  1398. memset(buf, 0x00, sizeof(buf));
  1399. *ptr++ = s->s3->send_alert[0];
  1400. *ptr++ = s->s3->send_alert[1];
  1401. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1402. if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
  1403. {
  1404. s2n(s->d1->handshake_read_seq, ptr);
  1405. #if 0
  1406. if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */
  1407. else
  1408. s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
  1409. #endif
  1410. #if 0
  1411. fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
  1412. #endif
  1413. l2n3(s->d1->r_msg_hdr.frag_off, ptr);
  1414. }
  1415. #endif
  1416. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
  1417. if (i <= 0)
  1418. {
  1419. s->s3->alert_dispatch=1;
  1420. /* fprintf( stderr, "not done with alert\n" ); */
  1421. }
  1422. else
  1423. {
  1424. if (s->s3->send_alert[0] == SSL3_AL_FATAL
  1425. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1426. || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1427. #endif
  1428. )
  1429. (void)BIO_flush(s->wbio);
  1430. if (s->msg_callback)
  1431. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1432. 2, s, s->msg_callback_arg);
  1433. if (s->info_callback != NULL)
  1434. cb=s->info_callback;
  1435. else if (s->ctx->info_callback != NULL)
  1436. cb=s->ctx->info_callback;
  1437. if (cb != NULL)
  1438. {
  1439. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1440. cb(s,SSL_CB_WRITE_ALERT,j);
  1441. }
  1442. }
  1443. return(i);
  1444. }
  1445. static DTLS1_BITMAP *
  1446. dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
  1447. {
  1448. *is_next_epoch = 0;
  1449. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1450. if (rr->epoch == s->d1->r_epoch)
  1451. return &s->d1->bitmap;
  1452. /* Only HM and ALERT messages can be from the next epoch */
  1453. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1454. (rr->type == SSL3_RT_HANDSHAKE ||
  1455. rr->type == SSL3_RT_ALERT))
  1456. {
  1457. *is_next_epoch = 1;
  1458. return &s->d1->next_bitmap;
  1459. }
  1460. return NULL;
  1461. }
  1462. #if 0
  1463. static int
  1464. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
  1465. unsigned long *offset)
  1466. {
  1467. /* alerts are passed up immediately */
  1468. if ( rr->type == SSL3_RT_APPLICATION_DATA ||
  1469. rr->type == SSL3_RT_ALERT)
  1470. return 0;
  1471. /* Only need to buffer if a handshake is underway.
  1472. * (this implies that Hello Request and Client Hello are passed up
  1473. * immediately) */
  1474. if ( SSL_in_init(s))
  1475. {
  1476. unsigned char *data = rr->data;
  1477. /* need to extract the HM/CCS sequence number here */
  1478. if ( rr->type == SSL3_RT_HANDSHAKE ||
  1479. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1480. {
  1481. unsigned short seq_num;
  1482. struct hm_header_st msg_hdr;
  1483. struct ccs_header_st ccs_hdr;
  1484. if ( rr->type == SSL3_RT_HANDSHAKE)
  1485. {
  1486. dtls1_get_message_header(data, &msg_hdr);
  1487. seq_num = msg_hdr.seq;
  1488. *offset = msg_hdr.frag_off;
  1489. }
  1490. else
  1491. {
  1492. dtls1_get_ccs_header(data, &ccs_hdr);
  1493. seq_num = ccs_hdr.seq;
  1494. *offset = 0;
  1495. }
  1496. /* this is either a record we're waiting for, or a
  1497. * retransmit of something we happened to previously
  1498. * receive (higher layers will drop the repeat silently */
  1499. if ( seq_num < s->d1->handshake_read_seq)
  1500. return 0;
  1501. if (rr->type == SSL3_RT_HANDSHAKE &&
  1502. seq_num == s->d1->handshake_read_seq &&
  1503. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1504. return 0;
  1505. else if ( seq_num == s->d1->handshake_read_seq &&
  1506. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1507. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1508. return 0;
  1509. else
  1510. {
  1511. *priority = seq_num;
  1512. return 1;
  1513. }
  1514. }
  1515. else /* unknown record type */
  1516. return 0;
  1517. }
  1518. return 0;
  1519. }
  1520. #endif
  1521. void
  1522. dtls1_reset_seq_numbers(SSL *s, int rw)
  1523. {
  1524. unsigned char *seq;
  1525. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1526. if ( rw & SSL3_CC_READ)
  1527. {
  1528. seq = s->s3->read_sequence;
  1529. s->d1->r_epoch++;
  1530. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1531. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1532. }
  1533. else
  1534. {
  1535. seq = s->s3->write_sequence;
  1536. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  1537. s->d1->w_epoch++;
  1538. }
  1539. memset(seq, 0x00, seq_bytes);
  1540. }