d1_lib.c 29 KB

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