d1_lib.c 29 KB

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