d1_lib.c 30 KB

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