d1_lib.c 30 KB

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