2
0

d1_lib.c 29 KB

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