d1_lib.c 30 KB

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