d1_lib.c 29 KB

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