d1_lib.c 30 KB

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