d1_lib.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. /*
  2. * Copyright 2005-2022 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "internal/e_os.h"
  10. #include <stdio.h>
  11. #include <openssl/objects.h>
  12. #include <openssl/rand.h>
  13. #include "ssl_local.h"
  14. #include "internal/time.h"
  15. static void get_current_time(struct timeval *t);
  16. static int dtls1_handshake_write(SSL *s);
  17. static size_t dtls1_link_min_mtu(void);
  18. /* XDTLS: figure out the right values */
  19. static const size_t g_probable_mtu[] = { 1500, 512, 256 };
  20. const SSL3_ENC_METHOD DTLSv1_enc_data = {
  21. tls1_enc,
  22. tls1_mac,
  23. tls1_setup_key_block,
  24. tls1_generate_master_secret,
  25. tls1_change_cipher_state,
  26. tls1_final_finish_mac,
  27. TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
  28. TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
  29. tls1_alert_code,
  30. tls1_export_keying_material,
  31. SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
  32. dtls1_set_handshake_header,
  33. dtls1_close_construct_packet,
  34. dtls1_handshake_write
  35. };
  36. const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
  37. tls1_enc,
  38. tls1_mac,
  39. tls1_setup_key_block,
  40. tls1_generate_master_secret,
  41. tls1_change_cipher_state,
  42. tls1_final_finish_mac,
  43. TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
  44. TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
  45. tls1_alert_code,
  46. tls1_export_keying_material,
  47. SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
  48. | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
  49. dtls1_set_handshake_header,
  50. dtls1_close_construct_packet,
  51. dtls1_handshake_write
  52. };
  53. long dtls1_default_timeout(void)
  54. {
  55. /*
  56. * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
  57. * http, the cache would over fill
  58. */
  59. return (60 * 60 * 2);
  60. }
  61. int dtls1_new(SSL *s)
  62. {
  63. DTLS1_STATE *d1;
  64. if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
  65. return 0;
  66. }
  67. if (!ssl3_new(s))
  68. return 0;
  69. if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
  70. ssl3_free(s);
  71. return 0;
  72. }
  73. d1->buffered_messages = pqueue_new();
  74. d1->sent_messages = pqueue_new();
  75. if (s->server) {
  76. d1->cookie_len = sizeof(s->d1->cookie);
  77. }
  78. d1->link_mtu = 0;
  79. d1->mtu = 0;
  80. if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
  81. pqueue_free(d1->buffered_messages);
  82. pqueue_free(d1->sent_messages);
  83. OPENSSL_free(d1);
  84. ssl3_free(s);
  85. return 0;
  86. }
  87. s->d1 = d1;
  88. if (!s->method->ssl_clear(s))
  89. return 0;
  90. return 1;
  91. }
  92. static void dtls1_clear_queues(SSL *s)
  93. {
  94. dtls1_clear_received_buffer(s);
  95. dtls1_clear_sent_buffer(s);
  96. }
  97. void dtls1_clear_received_buffer(SSL *s)
  98. {
  99. pitem *item = NULL;
  100. hm_fragment *frag = NULL;
  101. while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
  102. frag = (hm_fragment *)item->data;
  103. dtls1_hm_fragment_free(frag);
  104. pitem_free(item);
  105. }
  106. }
  107. void dtls1_clear_sent_buffer(SSL *s)
  108. {
  109. pitem *item = NULL;
  110. hm_fragment *frag = NULL;
  111. while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
  112. frag = (hm_fragment *)item->data;
  113. dtls1_hm_fragment_free(frag);
  114. pitem_free(item);
  115. }
  116. }
  117. void dtls1_free(SSL *s)
  118. {
  119. DTLS_RECORD_LAYER_free(&s->rlayer);
  120. ssl3_free(s);
  121. if (s->d1 != NULL) {
  122. dtls1_clear_queues(s);
  123. pqueue_free(s->d1->buffered_messages);
  124. pqueue_free(s->d1->sent_messages);
  125. }
  126. OPENSSL_free(s->d1);
  127. s->d1 = NULL;
  128. }
  129. int dtls1_clear(SSL *s)
  130. {
  131. pqueue *buffered_messages;
  132. pqueue *sent_messages;
  133. size_t mtu;
  134. size_t link_mtu;
  135. DTLS_RECORD_LAYER_clear(&s->rlayer);
  136. if (s->d1) {
  137. DTLS_timer_cb timer_cb = s->d1->timer_cb;
  138. buffered_messages = s->d1->buffered_messages;
  139. sent_messages = s->d1->sent_messages;
  140. mtu = s->d1->mtu;
  141. link_mtu = s->d1->link_mtu;
  142. dtls1_clear_queues(s);
  143. memset(s->d1, 0, sizeof(*s->d1));
  144. /* Restore the timer callback from previous state */
  145. s->d1->timer_cb = timer_cb;
  146. if (s->server) {
  147. s->d1->cookie_len = sizeof(s->d1->cookie);
  148. }
  149. if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
  150. s->d1->mtu = mtu;
  151. s->d1->link_mtu = link_mtu;
  152. }
  153. s->d1->buffered_messages = buffered_messages;
  154. s->d1->sent_messages = sent_messages;
  155. }
  156. if (!ssl3_clear(s))
  157. return 0;
  158. if (s->method->version == DTLS_ANY_VERSION)
  159. s->version = DTLS_MAX_VERSION_INTERNAL;
  160. #ifndef OPENSSL_NO_DTLS1_METHOD
  161. else if (s->options & SSL_OP_CISCO_ANYCONNECT)
  162. s->client_version = s->version = DTLS1_BAD_VER;
  163. #endif
  164. else
  165. s->version = s->method->version;
  166. return 1;
  167. }
  168. long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
  169. {
  170. int ret = 0;
  171. switch (cmd) {
  172. case DTLS_CTRL_GET_TIMEOUT:
  173. if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
  174. ret = 1;
  175. }
  176. break;
  177. case DTLS_CTRL_HANDLE_TIMEOUT:
  178. ret = dtls1_handle_timeout(s);
  179. break;
  180. case DTLS_CTRL_SET_LINK_MTU:
  181. if (larg < (long)dtls1_link_min_mtu())
  182. return 0;
  183. s->d1->link_mtu = larg;
  184. return 1;
  185. case DTLS_CTRL_GET_LINK_MIN_MTU:
  186. return (long)dtls1_link_min_mtu();
  187. case SSL_CTRL_SET_MTU:
  188. /*
  189. * We may not have a BIO set yet so can't call dtls1_min_mtu()
  190. * We'll have to make do with dtls1_link_min_mtu() and max overhead
  191. */
  192. if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
  193. return 0;
  194. s->d1->mtu = larg;
  195. return larg;
  196. default:
  197. ret = ssl3_ctrl(s, cmd, larg, parg);
  198. break;
  199. }
  200. return ret;
  201. }
  202. void dtls1_start_timer(SSL *s)
  203. {
  204. unsigned int sec, usec;
  205. #ifndef OPENSSL_NO_SCTP
  206. /* Disable timer for SCTP */
  207. if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
  208. memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
  209. return;
  210. }
  211. #endif
  212. /*
  213. * If timer is not set, initialize duration with 1 second or
  214. * a user-specified value if the timer callback is installed.
  215. */
  216. if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
  217. if (s->d1->timer_cb != NULL)
  218. s->d1->timeout_duration_us = s->d1->timer_cb(s, 0);
  219. else
  220. s->d1->timeout_duration_us = 1000000;
  221. }
  222. /* Set timeout to current time */
  223. get_current_time(&(s->d1->next_timeout));
  224. /* Add duration to current time */
  225. sec = s->d1->timeout_duration_us / 1000000;
  226. usec = s->d1->timeout_duration_us - (sec * 1000000);
  227. s->d1->next_timeout.tv_sec += sec;
  228. s->d1->next_timeout.tv_usec += usec;
  229. if (s->d1->next_timeout.tv_usec >= 1000000) {
  230. s->d1->next_timeout.tv_sec++;
  231. s->d1->next_timeout.tv_usec -= 1000000;
  232. }
  233. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
  234. &(s->d1->next_timeout));
  235. }
  236. struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
  237. {
  238. struct timeval timenow;
  239. /* If no timeout is set, just return NULL */
  240. if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
  241. return NULL;
  242. }
  243. /* Get current time */
  244. get_current_time(&timenow);
  245. /* If timer already expired, set remaining time to 0 */
  246. if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
  247. (s->d1->next_timeout.tv_sec == timenow.tv_sec &&
  248. s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
  249. memset(timeleft, 0, sizeof(*timeleft));
  250. return timeleft;
  251. }
  252. /* Calculate time left until timer expires */
  253. memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
  254. timeleft->tv_sec -= timenow.tv_sec;
  255. timeleft->tv_usec -= timenow.tv_usec;
  256. if (timeleft->tv_usec < 0) {
  257. timeleft->tv_sec--;
  258. timeleft->tv_usec += 1000000;
  259. }
  260. /*
  261. * If remaining time is less than 15 ms, set it to 0 to prevent issues
  262. * because of small divergences with socket timeouts.
  263. */
  264. if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
  265. memset(timeleft, 0, sizeof(*timeleft));
  266. }
  267. return timeleft;
  268. }
  269. int dtls1_is_timer_expired(SSL *s)
  270. {
  271. struct timeval timeleft;
  272. /* Get time left until timeout, return false if no timer running */
  273. if (dtls1_get_timeout(s, &timeleft) == NULL) {
  274. return 0;
  275. }
  276. /* Return false if timer is not expired yet */
  277. if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
  278. return 0;
  279. }
  280. /* Timer expired, so return true */
  281. return 1;
  282. }
  283. static void dtls1_double_timeout(SSL *s)
  284. {
  285. s->d1->timeout_duration_us *= 2;
  286. if (s->d1->timeout_duration_us > 60000000)
  287. s->d1->timeout_duration_us = 60000000;
  288. }
  289. void dtls1_stop_timer(SSL *s)
  290. {
  291. /* Reset everything */
  292. s->d1->timeout_num_alerts = 0;
  293. memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
  294. s->d1->timeout_duration_us = 1000000;
  295. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
  296. &(s->d1->next_timeout));
  297. /* Clear retransmission buffer */
  298. dtls1_clear_sent_buffer(s);
  299. }
  300. int dtls1_check_timeout_num(SSL *s)
  301. {
  302. size_t mtu;
  303. s->d1->timeout_num_alerts++;
  304. /* Reduce MTU after 2 unsuccessful retransmissions */
  305. if (s->d1->timeout_num_alerts > 2
  306. && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  307. mtu =
  308. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
  309. if (mtu < s->d1->mtu)
  310. s->d1->mtu = mtu;
  311. }
  312. if (s->d1->timeout_num_alerts > DTLS1_TMO_ALERT_COUNT) {
  313. /* fail the connection, enough alerts have been sent */
  314. SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_READ_TIMEOUT_EXPIRED);
  315. return -1;
  316. }
  317. return 0;
  318. }
  319. int dtls1_handle_timeout(SSL *s)
  320. {
  321. /* if no timer is expired, don't do anything */
  322. if (!dtls1_is_timer_expired(s)) {
  323. return 0;
  324. }
  325. if (s->d1->timer_cb != NULL)
  326. s->d1->timeout_duration_us = s->d1->timer_cb(s, s->d1->timeout_duration_us);
  327. else
  328. dtls1_double_timeout(s);
  329. if (dtls1_check_timeout_num(s) < 0) {
  330. /* SSLfatal() already called */
  331. return -1;
  332. }
  333. dtls1_start_timer(s);
  334. /* Calls SSLfatal() if required */
  335. return dtls1_retransmit_buffered_messages(s);
  336. }
  337. static void get_current_time(struct timeval *t)
  338. {
  339. ossl_time_time_to_timeval(ossl_time_now(), t);
  340. }
  341. #define LISTEN_SUCCESS 2
  342. #define LISTEN_SEND_VERIFY_REQUEST 1
  343. #ifndef OPENSSL_NO_SOCK
  344. int DTLSv1_listen(SSL *s, BIO_ADDR *client)
  345. {
  346. int next, n, ret = 0;
  347. unsigned char cookie[DTLS1_COOKIE_LENGTH];
  348. unsigned char seq[SEQ_NUM_SIZE];
  349. const unsigned char *data;
  350. unsigned char *buf, *wbuf;
  351. size_t fragoff, fraglen, msglen, reclen, align = 0;
  352. unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
  353. BIO *rbio, *wbio;
  354. BIO_ADDR *tmpclient = NULL;
  355. PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
  356. if (s->handshake_func == NULL) {
  357. /* Not properly initialized yet */
  358. SSL_set_accept_state(s);
  359. }
  360. /* Ensure there is no state left over from a previous invocation */
  361. if (!SSL_clear(s))
  362. return -1;
  363. ERR_clear_error();
  364. rbio = SSL_get_rbio(s);
  365. wbio = SSL_get_wbio(s);
  366. if (!rbio || !wbio) {
  367. ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
  368. return -1;
  369. }
  370. /*
  371. * Note: This check deliberately excludes DTLS1_BAD_VER because that version
  372. * requires the MAC to be calculated *including* the first ClientHello
  373. * (without the cookie). Since DTLSv1_listen is stateless that cannot be
  374. * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
  375. * SSL_accept)
  376. */
  377. if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
  378. ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
  379. return -1;
  380. }
  381. if (!ssl3_setup_buffers(s)) {
  382. /* ERR_raise() already called */
  383. return -1;
  384. }
  385. buf = RECORD_LAYER_get_rbuf(&s->rlayer)->buf;
  386. wbuf = RECORD_LAYER_get_wbuf(&s->rlayer)[0].buf;
  387. #if defined(SSL3_ALIGN_PAYLOAD)
  388. # if SSL3_ALIGN_PAYLOAD != 0
  389. /*
  390. * Using SSL3_RT_HEADER_LENGTH here instead of DTLS1_RT_HEADER_LENGTH for
  391. * consistency with ssl3_read_n. In practice it should make no difference
  392. * for sensible values of SSL3_ALIGN_PAYLOAD because the difference between
  393. * SSL3_RT_HEADER_LENGTH and DTLS1_RT_HEADER_LENGTH is exactly 8
  394. */
  395. align = (size_t)buf + SSL3_RT_HEADER_LENGTH;
  396. align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
  397. # endif
  398. #endif
  399. buf += align;
  400. do {
  401. /* Get a packet */
  402. clear_sys_error();
  403. n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH
  404. + DTLS1_RT_HEADER_LENGTH);
  405. if (n <= 0) {
  406. if (BIO_should_retry(rbio)) {
  407. /* Non-blocking IO */
  408. goto end;
  409. }
  410. return -1;
  411. }
  412. if (!PACKET_buf_init(&pkt, buf, n)) {
  413. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  414. return -1;
  415. }
  416. /*
  417. * Parse the received record. If there are any problems with it we just
  418. * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
  419. * resilient in the face of invalid records (e.g., invalid formatting,
  420. * length, MAC, etc.). In general, invalid records SHOULD be silently
  421. * discarded, thus preserving the association; however, an error MAY be
  422. * logged for diagnostic purposes."
  423. */
  424. /* this packet contained a partial record, dump it */
  425. if (n < DTLS1_RT_HEADER_LENGTH) {
  426. ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
  427. goto end;
  428. }
  429. if (s->msg_callback)
  430. s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
  431. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  432. /* Get the record header */
  433. if (!PACKET_get_1(&pkt, &rectype)
  434. || !PACKET_get_1(&pkt, &versmajor)) {
  435. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  436. goto end;
  437. }
  438. if (rectype != SSL3_RT_HANDSHAKE) {
  439. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  440. goto end;
  441. }
  442. /*
  443. * Check record version number. We only check that the major version is
  444. * the same.
  445. */
  446. if (versmajor != DTLS1_VERSION_MAJOR) {
  447. ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
  448. goto end;
  449. }
  450. if (!PACKET_forward(&pkt, 1)
  451. /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
  452. || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
  453. || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
  454. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  455. goto end;
  456. }
  457. reclen = PACKET_remaining(&msgpkt);
  458. /*
  459. * We allow data remaining at the end of the packet because there could
  460. * be a second record (but we ignore it)
  461. */
  462. /* This is an initial ClientHello so the epoch has to be 0 */
  463. if (seq[0] != 0 || seq[1] != 0) {
  464. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  465. goto end;
  466. }
  467. /* Get a pointer to the raw message for the later callback */
  468. data = PACKET_data(&msgpkt);
  469. /* Finished processing the record header, now process the message */
  470. if (!PACKET_get_1(&msgpkt, &msgtype)
  471. || !PACKET_get_net_3_len(&msgpkt, &msglen)
  472. || !PACKET_get_net_2(&msgpkt, &msgseq)
  473. || !PACKET_get_net_3_len(&msgpkt, &fragoff)
  474. || !PACKET_get_net_3_len(&msgpkt, &fraglen)
  475. || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
  476. || PACKET_remaining(&msgpkt) != 0) {
  477. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  478. goto end;
  479. }
  480. if (msgtype != SSL3_MT_CLIENT_HELLO) {
  481. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  482. goto end;
  483. }
  484. /* Message sequence number can only be 0 or 1 */
  485. if (msgseq > 2) {
  486. ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
  487. goto end;
  488. }
  489. /*
  490. * We don't support fragment reassembly for ClientHellos whilst
  491. * listening because that would require server side state (which is
  492. * against the whole point of the ClientHello/HelloVerifyRequest
  493. * mechanism). Instead we only look at the first ClientHello fragment
  494. * and require that the cookie must be contained within it.
  495. */
  496. if (fragoff != 0 || fraglen > msglen) {
  497. /* Non initial ClientHello fragment (or bad fragment) */
  498. ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
  499. goto end;
  500. }
  501. if (s->msg_callback)
  502. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
  503. fraglen + DTLS1_HM_HEADER_LENGTH, s,
  504. s->msg_callback_arg);
  505. if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
  506. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  507. goto end;
  508. }
  509. /*
  510. * Verify client version is supported
  511. */
  512. if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) &&
  513. s->method->version != DTLS_ANY_VERSION) {
  514. ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
  515. goto end;
  516. }
  517. if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
  518. || !PACKET_get_length_prefixed_1(&msgpayload, &session)
  519. || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
  520. /*
  521. * Could be malformed or the cookie does not fit within the initial
  522. * ClientHello fragment. Either way we can't handle it.
  523. */
  524. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  525. goto end;
  526. }
  527. /*
  528. * Check if we have a cookie or not. If not we need to send a
  529. * HelloVerifyRequest.
  530. */
  531. if (PACKET_remaining(&cookiepkt) == 0) {
  532. next = LISTEN_SEND_VERIFY_REQUEST;
  533. } else {
  534. /*
  535. * We have a cookie, so lets check it.
  536. */
  537. if (s->ctx->app_verify_cookie_cb == NULL) {
  538. ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
  539. /* This is fatal */
  540. return -1;
  541. }
  542. if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
  543. (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
  544. /*
  545. * We treat invalid cookies in the same was as no cookie as
  546. * per RFC6347
  547. */
  548. next = LISTEN_SEND_VERIFY_REQUEST;
  549. } else {
  550. /* Cookie verification succeeded */
  551. next = LISTEN_SUCCESS;
  552. }
  553. }
  554. if (next == LISTEN_SEND_VERIFY_REQUEST) {
  555. WPACKET wpkt;
  556. unsigned int version;
  557. size_t wreclen;
  558. /*
  559. * There was no cookie in the ClientHello so we need to send a
  560. * HelloVerifyRequest. If this fails we do not worry about trying
  561. * to resend, we just drop it.
  562. */
  563. /* Generate the cookie */
  564. if (s->ctx->app_gen_cookie_cb == NULL ||
  565. s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
  566. cookielen > 255) {
  567. ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
  568. /* This is fatal */
  569. return -1;
  570. }
  571. /*
  572. * Special case: for hello verify request, client version 1.0 and we
  573. * haven't decided which version to use yet send back using version
  574. * 1.0 header: otherwise some clients will ignore it.
  575. */
  576. version = (s->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
  577. : s->version;
  578. /* Construct the record and message headers */
  579. if (!WPACKET_init_static_len(&wpkt,
  580. wbuf,
  581. ssl_get_max_send_fragment(s)
  582. + DTLS1_RT_HEADER_LENGTH,
  583. 0)
  584. || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
  585. || !WPACKET_put_bytes_u16(&wpkt, version)
  586. /*
  587. * Record sequence number is always the same as in the
  588. * received ClientHello
  589. */
  590. || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
  591. /* End of record, start sub packet for message */
  592. || !WPACKET_start_sub_packet_u16(&wpkt)
  593. /* Message type */
  594. || !WPACKET_put_bytes_u8(&wpkt,
  595. DTLS1_MT_HELLO_VERIFY_REQUEST)
  596. /*
  597. * Message length - doesn't follow normal TLS convention:
  598. * the length isn't the last thing in the message header.
  599. * We'll need to fill this in later when we know the
  600. * length. Set it to zero for now
  601. */
  602. || !WPACKET_put_bytes_u24(&wpkt, 0)
  603. /*
  604. * Message sequence number is always 0 for a
  605. * HelloVerifyRequest
  606. */
  607. || !WPACKET_put_bytes_u16(&wpkt, 0)
  608. /*
  609. * We never fragment a HelloVerifyRequest, so fragment
  610. * offset is 0
  611. */
  612. || !WPACKET_put_bytes_u24(&wpkt, 0)
  613. /*
  614. * Fragment length is the same as message length, but
  615. * this *is* the last thing in the message header so we
  616. * can just start a sub-packet. No need to come back
  617. * later for this one.
  618. */
  619. || !WPACKET_start_sub_packet_u24(&wpkt)
  620. /* Create the actual HelloVerifyRequest body */
  621. || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
  622. /* Close message body */
  623. || !WPACKET_close(&wpkt)
  624. /* Close record body */
  625. || !WPACKET_close(&wpkt)
  626. || !WPACKET_get_total_written(&wpkt, &wreclen)
  627. || !WPACKET_finish(&wpkt)) {
  628. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  629. WPACKET_cleanup(&wpkt);
  630. /* This is fatal */
  631. return -1;
  632. }
  633. /*
  634. * Fix up the message len in the message header. Its the same as the
  635. * fragment len which has been filled in by WPACKET, so just copy
  636. * that. Destination for the message len is after the record header
  637. * plus one byte for the message content type. The source is the
  638. * last 3 bytes of the message header
  639. */
  640. memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
  641. &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
  642. 3);
  643. if (s->msg_callback)
  644. s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
  645. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  646. if ((tmpclient = BIO_ADDR_new()) == NULL) {
  647. ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
  648. goto end;
  649. }
  650. /*
  651. * This is unnecessary if rbio and wbio are one and the same - but
  652. * maybe they're not. We ignore errors here - some BIOs do not
  653. * support this.
  654. */
  655. if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
  656. (void)BIO_dgram_set_peer(wbio, tmpclient);
  657. }
  658. BIO_ADDR_free(tmpclient);
  659. tmpclient = NULL;
  660. if (BIO_write(wbio, wbuf, wreclen) < (int)wreclen) {
  661. if (BIO_should_retry(wbio)) {
  662. /*
  663. * Non-blocking IO...but we're stateless, so we're just
  664. * going to drop this packet.
  665. */
  666. goto end;
  667. }
  668. return -1;
  669. }
  670. if (BIO_flush(wbio) <= 0) {
  671. if (BIO_should_retry(wbio)) {
  672. /*
  673. * Non-blocking IO...but we're stateless, so we're just
  674. * going to drop this packet.
  675. */
  676. goto end;
  677. }
  678. return -1;
  679. }
  680. }
  681. } while (next != LISTEN_SUCCESS);
  682. /*
  683. * Set expected sequence numbers to continue the handshake.
  684. */
  685. s->d1->handshake_read_seq = 1;
  686. s->d1->handshake_write_seq = 1;
  687. s->d1->next_handshake_write_seq = 1;
  688. DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
  689. /*
  690. * We are doing cookie exchange, so make sure we set that option in the
  691. * SSL object
  692. */
  693. SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
  694. /*
  695. * Tell the state machine that we've done the initial hello verify
  696. * exchange
  697. */
  698. ossl_statem_set_hello_verify_done(s);
  699. /*
  700. * Some BIOs may not support this. If we fail we clear the client address
  701. */
  702. if (BIO_dgram_get_peer(rbio, client) <= 0)
  703. BIO_ADDR_clear(client);
  704. /* Buffer the record in the processed_rcds queue */
  705. if (!dtls_buffer_listen_record(s, reclen, seq, align))
  706. return -1;
  707. ret = 1;
  708. end:
  709. BIO_ADDR_free(tmpclient);
  710. return ret;
  711. }
  712. #endif
  713. static int dtls1_handshake_write(SSL *s)
  714. {
  715. return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
  716. }
  717. int dtls1_shutdown(SSL *s)
  718. {
  719. int ret;
  720. #ifndef OPENSSL_NO_SCTP
  721. BIO *wbio;
  722. wbio = SSL_get_wbio(s);
  723. if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
  724. !(s->shutdown & SSL_SENT_SHUTDOWN)) {
  725. ret = BIO_dgram_sctp_wait_for_dry(wbio);
  726. if (ret < 0)
  727. return -1;
  728. if (ret == 0)
  729. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
  730. NULL);
  731. }
  732. #endif
  733. ret = ssl3_shutdown(s);
  734. #ifndef OPENSSL_NO_SCTP
  735. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
  736. #endif
  737. return ret;
  738. }
  739. int dtls1_query_mtu(SSL *s)
  740. {
  741. if (s->d1->link_mtu) {
  742. s->d1->mtu =
  743. s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
  744. s->d1->link_mtu = 0;
  745. }
  746. /* AHA! Figure out the MTU, and stick to the right size */
  747. if (s->d1->mtu < dtls1_min_mtu(s)) {
  748. if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  749. s->d1->mtu =
  750. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  751. /*
  752. * I've seen the kernel return bogus numbers when it doesn't know
  753. * (initial write), so just make sure we have a reasonable number
  754. */
  755. if (s->d1->mtu < dtls1_min_mtu(s)) {
  756. /* Set to min mtu */
  757. s->d1->mtu = dtls1_min_mtu(s);
  758. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
  759. (long)s->d1->mtu, NULL);
  760. }
  761. } else
  762. return 0;
  763. }
  764. return 1;
  765. }
  766. static size_t dtls1_link_min_mtu(void)
  767. {
  768. return (g_probable_mtu[(sizeof(g_probable_mtu) /
  769. sizeof(g_probable_mtu[0])) - 1]);
  770. }
  771. size_t dtls1_min_mtu(SSL *s)
  772. {
  773. return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
  774. }
  775. size_t DTLS_get_data_mtu(const SSL *s)
  776. {
  777. size_t mac_overhead, int_overhead, blocksize, ext_overhead;
  778. const SSL_CIPHER *ciph = SSL_get_current_cipher(s);
  779. size_t mtu = s->d1->mtu;
  780. if (ciph == NULL)
  781. return 0;
  782. if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
  783. &blocksize, &ext_overhead))
  784. return 0;
  785. if (SSL_READ_ETM(s))
  786. ext_overhead += mac_overhead;
  787. else
  788. int_overhead += mac_overhead;
  789. /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
  790. if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
  791. return 0;
  792. mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
  793. /* Round encrypted payload down to cipher block size (for CBC etc.)
  794. * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
  795. if (blocksize)
  796. mtu -= (mtu % blocksize);
  797. /* Subtract internal overhead (e.g. CBC padding len byte) */
  798. if (int_overhead >= mtu)
  799. return 0;
  800. mtu -= int_overhead;
  801. return mtu;
  802. }
  803. void DTLS_set_timer_cb(SSL *s, DTLS_timer_cb cb)
  804. {
  805. s->d1->timer_cb = cb;
  806. }