2
0

d1_lib.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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 (wbuf == NULL) {
  376. OPENSSL_free(buf);
  377. return -1;
  378. }
  379. do {
  380. /* Get a packet */
  381. clear_sys_error();
  382. n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH
  383. + DTLS1_RT_HEADER_LENGTH);
  384. if (n <= 0) {
  385. if (BIO_should_retry(rbio)) {
  386. /* Non-blocking IO */
  387. goto end;
  388. }
  389. ret = -1;
  390. goto end;
  391. }
  392. if (!PACKET_buf_init(&pkt, buf, n)) {
  393. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  394. ret = -1;
  395. goto end;
  396. }
  397. /*
  398. * Parse the received record. If there are any problems with it we just
  399. * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
  400. * resilient in the face of invalid records (e.g., invalid formatting,
  401. * length, MAC, etc.). In general, invalid records SHOULD be silently
  402. * discarded, thus preserving the association; however, an error MAY be
  403. * logged for diagnostic purposes."
  404. */
  405. /* this packet contained a partial record, dump it */
  406. if (n < DTLS1_RT_HEADER_LENGTH) {
  407. ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
  408. goto end;
  409. }
  410. if (s->msg_callback)
  411. s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
  412. DTLS1_RT_HEADER_LENGTH, ssl, s->msg_callback_arg);
  413. /* Get the record header */
  414. if (!PACKET_get_1(&pkt, &rectype)
  415. || !PACKET_get_1(&pkt, &versmajor)) {
  416. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  417. goto end;
  418. }
  419. if (rectype != SSL3_RT_HANDSHAKE) {
  420. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  421. goto end;
  422. }
  423. /*
  424. * Check record version number. We only check that the major version is
  425. * the same.
  426. */
  427. if (versmajor != DTLS1_VERSION_MAJOR) {
  428. ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
  429. goto end;
  430. }
  431. if (!PACKET_forward(&pkt, 1)
  432. /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
  433. || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
  434. || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
  435. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  436. goto end;
  437. }
  438. /*
  439. * We allow data remaining at the end of the packet because there could
  440. * be a second record (but we ignore it)
  441. */
  442. /* This is an initial ClientHello so the epoch has to be 0 */
  443. if (seq[0] != 0 || seq[1] != 0) {
  444. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  445. goto end;
  446. }
  447. /* Get a pointer to the raw message for the later callback */
  448. data = PACKET_data(&msgpkt);
  449. /* Finished processing the record header, now process the message */
  450. if (!PACKET_get_1(&msgpkt, &msgtype)
  451. || !PACKET_get_net_3_len(&msgpkt, &msglen)
  452. || !PACKET_get_net_2(&msgpkt, &msgseq)
  453. || !PACKET_get_net_3_len(&msgpkt, &fragoff)
  454. || !PACKET_get_net_3_len(&msgpkt, &fraglen)
  455. || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
  456. || PACKET_remaining(&msgpkt) != 0) {
  457. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  458. goto end;
  459. }
  460. if (msgtype != SSL3_MT_CLIENT_HELLO) {
  461. ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
  462. goto end;
  463. }
  464. /* Message sequence number can only be 0 or 1 */
  465. if (msgseq > 2) {
  466. ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
  467. goto end;
  468. }
  469. /*
  470. * We don't support fragment reassembly for ClientHellos whilst
  471. * listening because that would require server side state (which is
  472. * against the whole point of the ClientHello/HelloVerifyRequest
  473. * mechanism). Instead we only look at the first ClientHello fragment
  474. * and require that the cookie must be contained within it.
  475. */
  476. if (fragoff != 0 || fraglen > msglen) {
  477. /* Non initial ClientHello fragment (or bad fragment) */
  478. ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
  479. goto end;
  480. }
  481. if (s->msg_callback)
  482. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
  483. fraglen + DTLS1_HM_HEADER_LENGTH, ssl,
  484. s->msg_callback_arg);
  485. if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
  486. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  487. goto end;
  488. }
  489. /*
  490. * Verify client version is supported
  491. */
  492. if (DTLS_VERSION_LT(clientvers, (unsigned int)ssl->method->version) &&
  493. ssl->method->version != DTLS_ANY_VERSION) {
  494. ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
  495. goto end;
  496. }
  497. if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
  498. || !PACKET_get_length_prefixed_1(&msgpayload, &session)
  499. || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
  500. /*
  501. * Could be malformed or the cookie does not fit within the initial
  502. * ClientHello fragment. Either way we can't handle it.
  503. */
  504. ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
  505. goto end;
  506. }
  507. /*
  508. * Check if we have a cookie or not. If not we need to send a
  509. * HelloVerifyRequest.
  510. */
  511. if (PACKET_remaining(&cookiepkt) == 0) {
  512. next = LISTEN_SEND_VERIFY_REQUEST;
  513. } else {
  514. /*
  515. * We have a cookie, so lets check it.
  516. */
  517. if (ssl->ctx->app_verify_cookie_cb == NULL) {
  518. ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
  519. /* This is fatal */
  520. ret = -1;
  521. goto end;
  522. }
  523. if (ssl->ctx->app_verify_cookie_cb(ssl, PACKET_data(&cookiepkt),
  524. (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
  525. /*
  526. * We treat invalid cookies in the same was as no cookie as
  527. * per RFC6347
  528. */
  529. next = LISTEN_SEND_VERIFY_REQUEST;
  530. } else {
  531. /* Cookie verification succeeded */
  532. next = LISTEN_SUCCESS;
  533. }
  534. }
  535. if (next == LISTEN_SEND_VERIFY_REQUEST) {
  536. WPACKET wpkt;
  537. unsigned int version;
  538. size_t wreclen;
  539. /*
  540. * There was no cookie in the ClientHello so we need to send a
  541. * HelloVerifyRequest. If this fails we do not worry about trying
  542. * to resend, we just drop it.
  543. */
  544. /* Generate the cookie */
  545. if (ssl->ctx->app_gen_cookie_cb == NULL ||
  546. ssl->ctx->app_gen_cookie_cb(ssl, cookie, &cookielen) == 0 ||
  547. cookielen > 255) {
  548. ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
  549. /* This is fatal */
  550. ret = -1;
  551. goto end;
  552. }
  553. /*
  554. * Special case: for hello verify request, client version 1.0 and we
  555. * haven't decided which version to use yet send back using version
  556. * 1.0 header: otherwise some clients will ignore it.
  557. */
  558. version = (ssl->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
  559. : s->version;
  560. /* Construct the record and message headers */
  561. if (!WPACKET_init_static_len(&wpkt,
  562. wbuf,
  563. ssl_get_max_send_fragment(s)
  564. + DTLS1_RT_HEADER_LENGTH,
  565. 0)
  566. || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
  567. || !WPACKET_put_bytes_u16(&wpkt, version)
  568. /*
  569. * Record sequence number is always the same as in the
  570. * received ClientHello
  571. */
  572. || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
  573. /* End of record, start sub packet for message */
  574. || !WPACKET_start_sub_packet_u16(&wpkt)
  575. /* Message type */
  576. || !WPACKET_put_bytes_u8(&wpkt,
  577. DTLS1_MT_HELLO_VERIFY_REQUEST)
  578. /*
  579. * Message length - doesn't follow normal TLS convention:
  580. * the length isn't the last thing in the message header.
  581. * We'll need to fill this in later when we know the
  582. * length. Set it to zero for now
  583. */
  584. || !WPACKET_put_bytes_u24(&wpkt, 0)
  585. /*
  586. * Message sequence number is always 0 for a
  587. * HelloVerifyRequest
  588. */
  589. || !WPACKET_put_bytes_u16(&wpkt, 0)
  590. /*
  591. * We never fragment a HelloVerifyRequest, so fragment
  592. * offset is 0
  593. */
  594. || !WPACKET_put_bytes_u24(&wpkt, 0)
  595. /*
  596. * Fragment length is the same as message length, but
  597. * this *is* the last thing in the message header so we
  598. * can just start a sub-packet. No need to come back
  599. * later for this one.
  600. */
  601. || !WPACKET_start_sub_packet_u24(&wpkt)
  602. /* Create the actual HelloVerifyRequest body */
  603. || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
  604. /* Close message body */
  605. || !WPACKET_close(&wpkt)
  606. /* Close record body */
  607. || !WPACKET_close(&wpkt)
  608. || !WPACKET_get_total_written(&wpkt, &wreclen)
  609. || !WPACKET_finish(&wpkt)) {
  610. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  611. WPACKET_cleanup(&wpkt);
  612. /* This is fatal */
  613. ret = -1;
  614. goto end;
  615. }
  616. /*
  617. * Fix up the message len in the message header. Its the same as the
  618. * fragment len which has been filled in by WPACKET, so just copy
  619. * that. Destination for the message len is after the record header
  620. * plus one byte for the message content type. The source is the
  621. * last 3 bytes of the message header
  622. */
  623. memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
  624. &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
  625. 3);
  626. if (s->msg_callback)
  627. s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
  628. DTLS1_RT_HEADER_LENGTH, ssl,
  629. s->msg_callback_arg);
  630. if ((tmpclient = BIO_ADDR_new()) == NULL) {
  631. ERR_raise(ERR_LIB_SSL, ERR_R_BIO_LIB);
  632. goto end;
  633. }
  634. /*
  635. * This is unnecessary if rbio and wbio are one and the same - but
  636. * maybe they're not. We ignore errors here - some BIOs do not
  637. * support this.
  638. */
  639. if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
  640. (void)BIO_dgram_set_peer(wbio, tmpclient);
  641. }
  642. BIO_ADDR_free(tmpclient);
  643. tmpclient = NULL;
  644. if (BIO_write(wbio, wbuf, wreclen) < (int)wreclen) {
  645. if (BIO_should_retry(wbio)) {
  646. /*
  647. * Non-blocking IO...but we're stateless, so we're just
  648. * going to drop this packet.
  649. */
  650. goto end;
  651. }
  652. ret = -1;
  653. goto end;
  654. }
  655. if (BIO_flush(wbio) <= 0) {
  656. if (BIO_should_retry(wbio)) {
  657. /*
  658. * Non-blocking IO...but we're stateless, so we're just
  659. * going to drop this packet.
  660. */
  661. goto end;
  662. }
  663. ret = -1;
  664. goto end;
  665. }
  666. }
  667. } while (next != LISTEN_SUCCESS);
  668. /*
  669. * Set expected sequence numbers to continue the handshake.
  670. */
  671. s->d1->handshake_read_seq = 1;
  672. s->d1->handshake_write_seq = 1;
  673. s->d1->next_handshake_write_seq = 1;
  674. s->rlayer.wrlmethod->increment_sequence_ctr(s->rlayer.wrl);
  675. /*
  676. * We are doing cookie exchange, so make sure we set that option in the
  677. * SSL object
  678. */
  679. SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
  680. /*
  681. * Tell the state machine that we've done the initial hello verify
  682. * exchange
  683. */
  684. ossl_statem_set_hello_verify_done(s);
  685. /*
  686. * Some BIOs may not support this. If we fail we clear the client address
  687. */
  688. if (BIO_dgram_get_peer(rbio, client) <= 0)
  689. BIO_ADDR_clear(client);
  690. /* Buffer the record for use by the record layer */
  691. if (BIO_write(s->rlayer.rrlnext, buf, n) != n) {
  692. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  693. ret = -1;
  694. goto end;
  695. }
  696. /*
  697. * Reset the record layer - but this time we can use the record we just
  698. * buffered in s->rlayer.rrlnext
  699. */
  700. if (!ssl_set_new_record_layer(s,
  701. DTLS_ANY_VERSION,
  702. OSSL_RECORD_DIRECTION_READ,
  703. OSSL_RECORD_PROTECTION_LEVEL_NONE,
  704. NULL, 0, NULL, 0, NULL, 0, NULL, 0,
  705. NID_undef, NULL, NULL)) {
  706. /* SSLfatal already called */
  707. ret = -1;
  708. goto end;
  709. }
  710. ret = 1;
  711. end:
  712. BIO_ADDR_free(tmpclient);
  713. OPENSSL_free(buf);
  714. OPENSSL_free(wbuf);
  715. return ret;
  716. }
  717. #endif
  718. static int dtls1_handshake_write(SSL_CONNECTION *s)
  719. {
  720. return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
  721. }
  722. int dtls1_shutdown(SSL *s)
  723. {
  724. int ret;
  725. #ifndef OPENSSL_NO_SCTP
  726. BIO *wbio;
  727. SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
  728. if (s == NULL)
  729. return -1;
  730. wbio = SSL_get_wbio(s);
  731. if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
  732. !(sc->shutdown & SSL_SENT_SHUTDOWN)) {
  733. ret = BIO_dgram_sctp_wait_for_dry(wbio);
  734. if (ret < 0)
  735. return -1;
  736. if (ret == 0)
  737. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
  738. NULL);
  739. }
  740. #endif
  741. ret = ssl3_shutdown(s);
  742. #ifndef OPENSSL_NO_SCTP
  743. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
  744. #endif
  745. return ret;
  746. }
  747. int dtls1_query_mtu(SSL_CONNECTION *s)
  748. {
  749. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  750. if (s->d1->link_mtu) {
  751. s->d1->mtu =
  752. s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
  753. s->d1->link_mtu = 0;
  754. }
  755. /* AHA! Figure out the MTU, and stick to the right size */
  756. if (s->d1->mtu < dtls1_min_mtu(s)) {
  757. if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  758. s->d1->mtu =
  759. BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  760. /*
  761. * I've seen the kernel return bogus numbers when it doesn't know
  762. * (initial write), so just make sure we have a reasonable number
  763. */
  764. if (s->d1->mtu < dtls1_min_mtu(s)) {
  765. /* Set to min mtu */
  766. s->d1->mtu = dtls1_min_mtu(s);
  767. BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU,
  768. (long)s->d1->mtu, NULL);
  769. }
  770. } else
  771. return 0;
  772. }
  773. return 1;
  774. }
  775. static size_t dtls1_link_min_mtu(void)
  776. {
  777. return (g_probable_mtu[(sizeof(g_probable_mtu) /
  778. sizeof(g_probable_mtu[0])) - 1]);
  779. }
  780. size_t dtls1_min_mtu(SSL_CONNECTION *s)
  781. {
  782. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  783. return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
  784. }
  785. size_t DTLS_get_data_mtu(const SSL *ssl)
  786. {
  787. size_t mac_overhead, int_overhead, blocksize, ext_overhead;
  788. const SSL_CIPHER *ciph = SSL_get_current_cipher(ssl);
  789. size_t mtu;
  790. const SSL_CONNECTION *s = SSL_CONNECTION_FROM_CONST_SSL_ONLY(ssl);
  791. if (s == NULL)
  792. return 0;
  793. mtu = s->d1->mtu;
  794. if (ciph == NULL)
  795. return 0;
  796. if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
  797. &blocksize, &ext_overhead))
  798. return 0;
  799. if (SSL_READ_ETM(s))
  800. ext_overhead += mac_overhead;
  801. else
  802. int_overhead += mac_overhead;
  803. /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
  804. if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
  805. return 0;
  806. mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
  807. /* Round encrypted payload down to cipher block size (for CBC etc.)
  808. * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
  809. if (blocksize)
  810. mtu -= (mtu % blocksize);
  811. /* Subtract internal overhead (e.g. CBC padding len byte) */
  812. if (int_overhead >= mtu)
  813. return 0;
  814. mtu -= int_overhead;
  815. return mtu;
  816. }
  817. void DTLS_set_timer_cb(SSL *ssl, DTLS_timer_cb cb)
  818. {
  819. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  820. if (s == NULL)
  821. return;
  822. s->d1->timer_cb = cb;
  823. }