d1_both.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /*
  2. * DTLS implementation written by Nagendra Modadugu
  3. * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
  4. */
  5. /* ====================================================================
  6. * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. All advertising materials mentioning features or use of this
  21. * software must display the following acknowledgment:
  22. * "This product includes software developed by the OpenSSL Project
  23. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  24. *
  25. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  26. * endorse or promote products derived from this software without
  27. * prior written permission. For written permission, please contact
  28. * openssl-core@openssl.org.
  29. *
  30. * 5. Products derived from this software may not be called "OpenSSL"
  31. * nor may "OpenSSL" appear in their names without prior written
  32. * permission of the OpenSSL Project.
  33. *
  34. * 6. Redistributions of any form whatsoever must retain the following
  35. * acknowledgment:
  36. * "This product includes software developed by the OpenSSL Project
  37. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  38. *
  39. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  40. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  41. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  42. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  43. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  44. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  45. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  46. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  48. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  49. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  50. * OF THE POSSIBILITY OF SUCH DAMAGE.
  51. * ====================================================================
  52. *
  53. * This product includes cryptographic software written by Eric Young
  54. * (eay@cryptsoft.com). This product includes software written by Tim
  55. * Hudson (tjh@cryptsoft.com).
  56. *
  57. */
  58. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  59. * All rights reserved.
  60. *
  61. * This package is an SSL implementation written
  62. * by Eric Young (eay@cryptsoft.com).
  63. * The implementation was written so as to conform with Netscapes SSL.
  64. *
  65. * This library is free for commercial and non-commercial use as long as
  66. * the following conditions are aheared to. The following conditions
  67. * apply to all code found in this distribution, be it the RC4, RSA,
  68. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  69. * included with this distribution is covered by the same copyright terms
  70. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  71. *
  72. * Copyright remains Eric Young's, and as such any Copyright notices in
  73. * the code are not to be removed.
  74. * If this package is used in a product, Eric Young should be given attribution
  75. * as the author of the parts of the library used.
  76. * This can be in the form of a textual message at program startup or
  77. * in documentation (online or textual) provided with the package.
  78. *
  79. * Redistribution and use in source and binary forms, with or without
  80. * modification, are permitted provided that the following conditions
  81. * are met:
  82. * 1. Redistributions of source code must retain the copyright
  83. * notice, this list of conditions and the following disclaimer.
  84. * 2. Redistributions in binary form must reproduce the above copyright
  85. * notice, this list of conditions and the following disclaimer in the
  86. * documentation and/or other materials provided with the distribution.
  87. * 3. All advertising materials mentioning features or use of this software
  88. * must display the following acknowledgement:
  89. * "This product includes cryptographic software written by
  90. * Eric Young (eay@cryptsoft.com)"
  91. * The word 'cryptographic' can be left out if the rouines from the library
  92. * being used are not cryptographic related :-).
  93. * 4. If you include any Windows specific code (or a derivative thereof) from
  94. * the apps directory (application code) you must include an acknowledgement:
  95. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  96. *
  97. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  98. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  99. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  100. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  101. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  102. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  103. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  104. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  105. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  106. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  107. * SUCH DAMAGE.
  108. *
  109. * The licence and distribution terms for any publically available version or
  110. * derivative of this code cannot be changed. i.e. this code cannot simply be
  111. * copied and put under another distribution licence
  112. * [including the GNU Public Licence.] */
  113. #include <openssl/ssl.h>
  114. #include <assert.h>
  115. #include <limits.h>
  116. #include <string.h>
  117. #include <openssl/buf.h>
  118. #include <openssl/err.h>
  119. #include <openssl/evp.h>
  120. #include <openssl/mem.h>
  121. #include <openssl/rand.h>
  122. #include "../crypto/internal.h"
  123. #include "internal.h"
  124. BSSL_NAMESPACE_BEGIN
  125. // TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
  126. // for these values? Notably, why is kMinMTU a function of the transport
  127. // protocol's overhead rather than, say, what's needed to hold a minimally-sized
  128. // handshake fragment plus protocol overhead.
  129. // kMinMTU is the minimum acceptable MTU value.
  130. static const unsigned int kMinMTU = 256 - 28;
  131. // kDefaultMTU is the default MTU value to use if neither the user nor
  132. // the underlying BIO supplies one.
  133. static const unsigned int kDefaultMTU = 1500 - 28;
  134. // Receiving handshake messages.
  135. hm_fragment::~hm_fragment() {
  136. OPENSSL_free(data);
  137. OPENSSL_free(reassembly);
  138. }
  139. static UniquePtr<hm_fragment> dtls1_hm_fragment_new(
  140. const struct hm_header_st *msg_hdr) {
  141. ScopedCBB cbb;
  142. UniquePtr<hm_fragment> frag = MakeUnique<hm_fragment>();
  143. if (!frag) {
  144. return nullptr;
  145. }
  146. frag->type = msg_hdr->type;
  147. frag->seq = msg_hdr->seq;
  148. frag->msg_len = msg_hdr->msg_len;
  149. // Allocate space for the reassembled message and fill in the header.
  150. frag->data =
  151. (uint8_t *)OPENSSL_malloc(DTLS1_HM_HEADER_LENGTH + msg_hdr->msg_len);
  152. if (frag->data == NULL) {
  153. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  154. return nullptr;
  155. }
  156. if (!CBB_init_fixed(cbb.get(), frag->data, DTLS1_HM_HEADER_LENGTH) ||
  157. !CBB_add_u8(cbb.get(), msg_hdr->type) ||
  158. !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
  159. !CBB_add_u16(cbb.get(), msg_hdr->seq) ||
  160. !CBB_add_u24(cbb.get(), 0 /* frag_off */) ||
  161. !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
  162. !CBB_finish(cbb.get(), NULL, NULL)) {
  163. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  164. return nullptr;
  165. }
  166. // If the handshake message is empty, |frag->reassembly| is NULL.
  167. if (msg_hdr->msg_len > 0) {
  168. // Initialize reassembly bitmask.
  169. if (msg_hdr->msg_len + 7 < msg_hdr->msg_len) {
  170. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  171. return nullptr;
  172. }
  173. size_t bitmask_len = (msg_hdr->msg_len + 7) / 8;
  174. frag->reassembly = (uint8_t *)OPENSSL_malloc(bitmask_len);
  175. if (frag->reassembly == NULL) {
  176. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  177. return nullptr;
  178. }
  179. OPENSSL_memset(frag->reassembly, 0, bitmask_len);
  180. }
  181. return frag;
  182. }
  183. // bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  184. // exclusive, set.
  185. static uint8_t bit_range(size_t start, size_t end) {
  186. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  187. }
  188. // dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  189. // as received in |frag|. If |frag| becomes complete, it clears
  190. // |frag->reassembly|. The range must be within the bounds of |frag|'s message
  191. // and |frag->reassembly| must not be NULL.
  192. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  193. size_t end) {
  194. size_t msg_len = frag->msg_len;
  195. if (frag->reassembly == NULL || start > end || end > msg_len) {
  196. assert(0);
  197. return;
  198. }
  199. // A zero-length message will never have a pending reassembly.
  200. assert(msg_len > 0);
  201. if (start == end) {
  202. return;
  203. }
  204. if ((start >> 3) == (end >> 3)) {
  205. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  206. } else {
  207. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  208. for (size_t i = (start >> 3) + 1; i < (end >> 3); i++) {
  209. frag->reassembly[i] = 0xff;
  210. }
  211. if ((end & 7) != 0) {
  212. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  213. }
  214. }
  215. // Check if the fragment is complete.
  216. for (size_t i = 0; i < (msg_len >> 3); i++) {
  217. if (frag->reassembly[i] != 0xff) {
  218. return;
  219. }
  220. }
  221. if ((msg_len & 7) != 0 &&
  222. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  223. return;
  224. }
  225. OPENSSL_free(frag->reassembly);
  226. frag->reassembly = NULL;
  227. }
  228. // dtls1_is_current_message_complete returns whether the current handshake
  229. // message is complete.
  230. static bool dtls1_is_current_message_complete(const SSL *ssl) {
  231. size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  232. hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
  233. return frag != NULL && frag->reassembly == NULL;
  234. }
  235. // dtls1_get_incoming_message returns the incoming message corresponding to
  236. // |msg_hdr|. If none exists, it creates a new one and inserts it in the
  237. // queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  238. // returns NULL on failure. The caller does not take ownership of the result.
  239. static hm_fragment *dtls1_get_incoming_message(
  240. SSL *ssl, uint8_t *out_alert, const struct hm_header_st *msg_hdr) {
  241. if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
  242. msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
  243. *out_alert = SSL_AD_INTERNAL_ERROR;
  244. return NULL;
  245. }
  246. size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
  247. hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
  248. if (frag != NULL) {
  249. assert(frag->seq == msg_hdr->seq);
  250. // The new fragment must be compatible with the previous fragments from this
  251. // message.
  252. if (frag->type != msg_hdr->type ||
  253. frag->msg_len != msg_hdr->msg_len) {
  254. OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
  255. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  256. return NULL;
  257. }
  258. return frag;
  259. }
  260. // This is the first fragment from this message.
  261. ssl->d1->incoming_messages[idx] = dtls1_hm_fragment_new(msg_hdr);
  262. if (!ssl->d1->incoming_messages[idx]) {
  263. *out_alert = SSL_AD_INTERNAL_ERROR;
  264. return NULL;
  265. }
  266. return ssl->d1->incoming_messages[idx].get();
  267. }
  268. ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed,
  269. uint8_t *out_alert, Span<uint8_t> in) {
  270. uint8_t type;
  271. Span<uint8_t> record;
  272. auto ret = dtls_open_record(ssl, &type, &record, out_consumed, out_alert, in);
  273. if (ret != ssl_open_record_success) {
  274. return ret;
  275. }
  276. switch (type) {
  277. case SSL3_RT_APPLICATION_DATA:
  278. // Unencrypted application data records are always illegal.
  279. if (ssl->s3->aead_read_ctx->is_null_cipher()) {
  280. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  281. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  282. return ssl_open_record_error;
  283. }
  284. // Out-of-order application data may be received between ChangeCipherSpec
  285. // and finished. Discard it.
  286. return ssl_open_record_discard;
  287. case SSL3_RT_CHANGE_CIPHER_SPEC:
  288. // We do not support renegotiation, so encrypted ChangeCipherSpec records
  289. // are illegal.
  290. if (!ssl->s3->aead_read_ctx->is_null_cipher()) {
  291. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  292. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  293. return ssl_open_record_error;
  294. }
  295. if (record.size() != 1u || record[0] != SSL3_MT_CCS) {
  296. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  297. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  298. return ssl_open_record_error;
  299. }
  300. // Flag the ChangeCipherSpec for later.
  301. ssl->d1->has_change_cipher_spec = true;
  302. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC,
  303. record);
  304. return ssl_open_record_success;
  305. case SSL3_RT_HANDSHAKE:
  306. // Break out to main processing.
  307. break;
  308. default:
  309. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  310. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  311. return ssl_open_record_error;
  312. }
  313. CBS cbs;
  314. CBS_init(&cbs, record.data(), record.size());
  315. while (CBS_len(&cbs) > 0) {
  316. // Read a handshake fragment.
  317. struct hm_header_st msg_hdr;
  318. CBS body;
  319. if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
  320. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  321. *out_alert = SSL_AD_DECODE_ERROR;
  322. return ssl_open_record_error;
  323. }
  324. const size_t frag_off = msg_hdr.frag_off;
  325. const size_t frag_len = msg_hdr.frag_len;
  326. const size_t msg_len = msg_hdr.msg_len;
  327. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  328. frag_off + frag_len > msg_len ||
  329. msg_len > ssl_max_handshake_message_len(ssl)) {
  330. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  331. *out_alert = SSL_AD_ILLEGAL_PARAMETER;
  332. return ssl_open_record_error;
  333. }
  334. // The encrypted epoch in DTLS has only one handshake message.
  335. if (ssl->d1->r_epoch == 1 && msg_hdr.seq != ssl->d1->handshake_read_seq) {
  336. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  337. *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
  338. return ssl_open_record_error;
  339. }
  340. if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
  341. msg_hdr.seq >
  342. (unsigned)ssl->d1->handshake_read_seq + SSL_MAX_HANDSHAKE_FLIGHT) {
  343. // Ignore fragments from the past, or ones too far in the future.
  344. continue;
  345. }
  346. hm_fragment *frag = dtls1_get_incoming_message(ssl, out_alert, &msg_hdr);
  347. if (frag == NULL) {
  348. return ssl_open_record_error;
  349. }
  350. assert(frag->msg_len == msg_len);
  351. if (frag->reassembly == NULL) {
  352. // The message is already assembled.
  353. continue;
  354. }
  355. assert(msg_len > 0);
  356. // Copy the body into the fragment.
  357. OPENSSL_memcpy(frag->data + DTLS1_HM_HEADER_LENGTH + frag_off,
  358. CBS_data(&body), CBS_len(&body));
  359. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  360. }
  361. return ssl_open_record_success;
  362. }
  363. bool dtls1_get_message(const SSL *ssl, SSLMessage *out) {
  364. if (!dtls1_is_current_message_complete(ssl)) {
  365. return false;
  366. }
  367. size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  368. hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
  369. out->type = frag->type;
  370. CBS_init(&out->body, frag->data + DTLS1_HM_HEADER_LENGTH, frag->msg_len);
  371. CBS_init(&out->raw, frag->data, DTLS1_HM_HEADER_LENGTH + frag->msg_len);
  372. out->is_v2_hello = false;
  373. if (!ssl->s3->has_message) {
  374. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, out->raw);
  375. ssl->s3->has_message = true;
  376. }
  377. return true;
  378. }
  379. void dtls1_next_message(SSL *ssl) {
  380. assert(ssl->s3->has_message);
  381. assert(dtls1_is_current_message_complete(ssl));
  382. size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  383. ssl->d1->incoming_messages[index].reset();
  384. ssl->d1->handshake_read_seq++;
  385. ssl->s3->has_message = false;
  386. // If we previously sent a flight, mark it as having a reply, so
  387. // |on_handshake_complete| can manage post-handshake retransmission.
  388. if (ssl->d1->outgoing_messages_complete) {
  389. ssl->d1->flight_has_reply = true;
  390. }
  391. }
  392. bool dtls_has_unprocessed_handshake_data(const SSL *ssl) {
  393. if (ssl->d1->has_change_cipher_spec) {
  394. return true;
  395. }
  396. size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  397. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  398. // Skip the current message.
  399. if (ssl->s3->has_message && i == current) {
  400. assert(dtls1_is_current_message_complete(ssl));
  401. continue;
  402. }
  403. if (ssl->d1->incoming_messages[i] != nullptr) {
  404. return true;
  405. }
  406. }
  407. return false;
  408. }
  409. bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  410. CBS *out_body) {
  411. OPENSSL_memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  412. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  413. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  414. !CBS_get_u16(cbs, &out_hdr->seq) ||
  415. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  416. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  417. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  418. return false;
  419. }
  420. return true;
  421. }
  422. ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
  423. uint8_t *out_alert,
  424. Span<uint8_t> in) {
  425. if (!ssl->d1->has_change_cipher_spec) {
  426. // dtls1_open_handshake processes both handshake and ChangeCipherSpec.
  427. auto ret = dtls1_open_handshake(ssl, out_consumed, out_alert, in);
  428. if (ret != ssl_open_record_success) {
  429. return ret;
  430. }
  431. }
  432. if (ssl->d1->has_change_cipher_spec) {
  433. ssl->d1->has_change_cipher_spec = false;
  434. return ssl_open_record_success;
  435. }
  436. return ssl_open_record_discard;
  437. }
  438. // Sending handshake messages.
  439. void DTLS_OUTGOING_MESSAGE::Clear() {
  440. OPENSSL_free(data);
  441. data = nullptr;
  442. }
  443. void dtls_clear_outgoing_messages(SSL *ssl) {
  444. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  445. ssl->d1->outgoing_messages[i].Clear();
  446. }
  447. ssl->d1->outgoing_messages_len = 0;
  448. ssl->d1->outgoing_written = 0;
  449. ssl->d1->outgoing_offset = 0;
  450. ssl->d1->outgoing_messages_complete = false;
  451. ssl->d1->flight_has_reply = false;
  452. }
  453. bool dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  454. // Pick a modest size hint to save most of the |realloc| calls.
  455. if (!CBB_init(cbb, 64) ||
  456. !CBB_add_u8(cbb, type) ||
  457. !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
  458. !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
  459. !CBB_add_u24(cbb, 0 /* offset */) ||
  460. !CBB_add_u24_length_prefixed(cbb, body)) {
  461. return false;
  462. }
  463. return true;
  464. }
  465. bool dtls1_finish_message(SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg) {
  466. if (!CBBFinishArray(cbb, out_msg) ||
  467. out_msg->size() < DTLS1_HM_HEADER_LENGTH) {
  468. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  469. return false;
  470. }
  471. // Fix up the header. Copy the fragment length into the total message
  472. // length.
  473. OPENSSL_memcpy(out_msg->data() + 1,
  474. out_msg->data() + DTLS1_HM_HEADER_LENGTH - 3, 3);
  475. return true;
  476. }
  477. // ssl_size_t_greater_than_32_bits returns whether |v| exceeds the bounds of a
  478. // 32-bit value. The obvious thing doesn't work because, in some 32-bit build
  479. // configurations, the compiler warns that the test is always false and breaks
  480. // the build.
  481. static bool ssl_size_t_greater_than_32_bits(size_t v) {
  482. #if defined(OPENSSL_64_BIT)
  483. return v > 0xffffffff;
  484. #elif defined(OPENSSL_32_BIT)
  485. return false;
  486. #else
  487. #error "Building for neither 32- nor 64-bits."
  488. #endif
  489. }
  490. // add_outgoing adds a new handshake message or ChangeCipherSpec to the current
  491. // outgoing flight. It returns true on success and false on error.
  492. static bool add_outgoing(SSL *ssl, bool is_ccs, Array<uint8_t> data) {
  493. if (ssl->d1->outgoing_messages_complete) {
  494. // If we've begun writing a new flight, we received the peer flight. Discard
  495. // the timer and the our flight.
  496. dtls1_stop_timer(ssl);
  497. dtls_clear_outgoing_messages(ssl);
  498. }
  499. static_assert(SSL_MAX_HANDSHAKE_FLIGHT <
  500. (1 << 8 * sizeof(ssl->d1->outgoing_messages_len)),
  501. "outgoing_messages_len is too small");
  502. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT ||
  503. ssl_size_t_greater_than_32_bits(data.size())) {
  504. assert(false);
  505. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  506. return false;
  507. }
  508. if (!is_ccs) {
  509. // TODO(svaldez): Move this up a layer to fix abstraction for SSLTranscript
  510. // on hs.
  511. if (ssl->s3->hs != NULL &&
  512. !ssl->s3->hs->transcript.Update(data)) {
  513. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  514. return false;
  515. }
  516. ssl->d1->handshake_write_seq++;
  517. }
  518. DTLS_OUTGOING_MESSAGE *msg =
  519. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  520. size_t len;
  521. data.Release(&msg->data, &len);
  522. msg->len = len;
  523. msg->epoch = ssl->d1->w_epoch;
  524. msg->is_ccs = is_ccs;
  525. ssl->d1->outgoing_messages_len++;
  526. return true;
  527. }
  528. bool dtls1_add_message(SSL *ssl, Array<uint8_t> data) {
  529. return add_outgoing(ssl, false /* handshake */, std::move(data));
  530. }
  531. bool dtls1_add_change_cipher_spec(SSL *ssl) {
  532. return add_outgoing(ssl, true /* ChangeCipherSpec */, Array<uint8_t>());
  533. }
  534. // dtls1_update_mtu updates the current MTU from the BIO, ensuring it is above
  535. // the minimum.
  536. static void dtls1_update_mtu(SSL *ssl) {
  537. // TODO(davidben): No consumer implements |BIO_CTRL_DGRAM_SET_MTU| and the
  538. // only |BIO_CTRL_DGRAM_QUERY_MTU| implementation could use
  539. // |SSL_set_mtu|. Does this need to be so complex?
  540. if (ssl->d1->mtu < dtls1_min_mtu() &&
  541. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  542. long mtu = BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  543. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  544. ssl->d1->mtu = (unsigned)mtu;
  545. } else {
  546. ssl->d1->mtu = kDefaultMTU;
  547. BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  548. }
  549. }
  550. // The MTU should be above the minimum now.
  551. assert(ssl->d1->mtu >= dtls1_min_mtu());
  552. }
  553. enum seal_result_t {
  554. seal_error,
  555. seal_no_progress,
  556. seal_partial,
  557. seal_success,
  558. };
  559. // seal_next_message seals |msg|, which must be the next message, to |out|. If
  560. // progress was made, it returns |seal_partial| or |seal_success| and sets
  561. // |*out_len| to the number of bytes written.
  562. static enum seal_result_t seal_next_message(SSL *ssl, uint8_t *out,
  563. size_t *out_len, size_t max_out,
  564. const DTLS_OUTGOING_MESSAGE *msg) {
  565. assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
  566. assert(msg == &ssl->d1->outgoing_messages[ssl->d1->outgoing_written]);
  567. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  568. if (ssl->d1->w_epoch >= 1 && msg->epoch == ssl->d1->w_epoch - 1) {
  569. use_epoch = dtls1_use_previous_epoch;
  570. } else if (msg->epoch != ssl->d1->w_epoch) {
  571. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  572. return seal_error;
  573. }
  574. size_t overhead = dtls_max_seal_overhead(ssl, use_epoch);
  575. size_t prefix = dtls_seal_prefix_len(ssl, use_epoch);
  576. if (msg->is_ccs) {
  577. // Check there is room for the ChangeCipherSpec.
  578. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  579. if (max_out < sizeof(kChangeCipherSpec) + overhead) {
  580. return seal_no_progress;
  581. }
  582. if (!dtls_seal_record(ssl, out, out_len, max_out,
  583. SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  584. sizeof(kChangeCipherSpec), use_epoch)) {
  585. return seal_error;
  586. }
  587. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_CHANGE_CIPHER_SPEC,
  588. kChangeCipherSpec);
  589. return seal_success;
  590. }
  591. // DTLS messages are serialized as a single fragment in |msg|.
  592. CBS cbs, body;
  593. struct hm_header_st hdr;
  594. CBS_init(&cbs, msg->data, msg->len);
  595. if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
  596. hdr.frag_off != 0 ||
  597. hdr.frag_len != CBS_len(&body) ||
  598. hdr.msg_len != CBS_len(&body) ||
  599. !CBS_skip(&body, ssl->d1->outgoing_offset) ||
  600. CBS_len(&cbs) != 0) {
  601. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  602. return seal_error;
  603. }
  604. // Determine how much progress can be made.
  605. if (max_out < DTLS1_HM_HEADER_LENGTH + 1 + overhead || max_out < prefix) {
  606. return seal_no_progress;
  607. }
  608. size_t todo = CBS_len(&body);
  609. if (todo > max_out - DTLS1_HM_HEADER_LENGTH - overhead) {
  610. todo = max_out - DTLS1_HM_HEADER_LENGTH - overhead;
  611. }
  612. // Assemble a fragment, to be sealed in-place.
  613. ScopedCBB cbb;
  614. uint8_t *frag = out + prefix;
  615. size_t max_frag = max_out - prefix, frag_len;
  616. if (!CBB_init_fixed(cbb.get(), frag, max_frag) ||
  617. !CBB_add_u8(cbb.get(), hdr.type) ||
  618. !CBB_add_u24(cbb.get(), hdr.msg_len) ||
  619. !CBB_add_u16(cbb.get(), hdr.seq) ||
  620. !CBB_add_u24(cbb.get(), ssl->d1->outgoing_offset) ||
  621. !CBB_add_u24(cbb.get(), todo) ||
  622. !CBB_add_bytes(cbb.get(), CBS_data(&body), todo) ||
  623. !CBB_finish(cbb.get(), NULL, &frag_len)) {
  624. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  625. return seal_error;
  626. }
  627. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HANDSHAKE,
  628. MakeSpan(frag, frag_len));
  629. if (!dtls_seal_record(ssl, out, out_len, max_out, SSL3_RT_HANDSHAKE,
  630. out + prefix, frag_len, use_epoch)) {
  631. return seal_error;
  632. }
  633. if (todo == CBS_len(&body)) {
  634. // The next message is complete.
  635. ssl->d1->outgoing_offset = 0;
  636. return seal_success;
  637. }
  638. ssl->d1->outgoing_offset += todo;
  639. return seal_partial;
  640. }
  641. // seal_next_packet writes as much of the next flight as possible to |out| and
  642. // advances |ssl->d1->outgoing_written| and |ssl->d1->outgoing_offset| as
  643. // appropriate.
  644. static bool seal_next_packet(SSL *ssl, uint8_t *out, size_t *out_len,
  645. size_t max_out) {
  646. bool made_progress = false;
  647. size_t total = 0;
  648. assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
  649. for (; ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len;
  650. ssl->d1->outgoing_written++) {
  651. const DTLS_OUTGOING_MESSAGE *msg =
  652. &ssl->d1->outgoing_messages[ssl->d1->outgoing_written];
  653. size_t len;
  654. enum seal_result_t ret = seal_next_message(ssl, out, &len, max_out, msg);
  655. switch (ret) {
  656. case seal_error:
  657. return false;
  658. case seal_no_progress:
  659. goto packet_full;
  660. case seal_partial:
  661. case seal_success:
  662. out += len;
  663. max_out -= len;
  664. total += len;
  665. made_progress = true;
  666. if (ret == seal_partial) {
  667. goto packet_full;
  668. }
  669. break;
  670. }
  671. }
  672. packet_full:
  673. // The MTU was too small to make any progress.
  674. if (!made_progress) {
  675. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  676. return false;
  677. }
  678. *out_len = total;
  679. return true;
  680. }
  681. static int send_flight(SSL *ssl) {
  682. if (ssl->s3->write_shutdown != ssl_shutdown_none) {
  683. OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
  684. return -1;
  685. }
  686. dtls1_update_mtu(ssl);
  687. int ret = -1;
  688. uint8_t *packet = (uint8_t *)OPENSSL_malloc(ssl->d1->mtu);
  689. if (packet == NULL) {
  690. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  691. goto err;
  692. }
  693. while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len) {
  694. uint8_t old_written = ssl->d1->outgoing_written;
  695. uint32_t old_offset = ssl->d1->outgoing_offset;
  696. size_t packet_len;
  697. if (!seal_next_packet(ssl, packet, &packet_len, ssl->d1->mtu)) {
  698. goto err;
  699. }
  700. int bio_ret = BIO_write(ssl->wbio.get(), packet, packet_len);
  701. if (bio_ret <= 0) {
  702. // Retry this packet the next time around.
  703. ssl->d1->outgoing_written = old_written;
  704. ssl->d1->outgoing_offset = old_offset;
  705. ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
  706. ret = bio_ret;
  707. goto err;
  708. }
  709. }
  710. if (BIO_flush(ssl->wbio.get()) <= 0) {
  711. ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
  712. goto err;
  713. }
  714. ret = 1;
  715. err:
  716. OPENSSL_free(packet);
  717. return ret;
  718. }
  719. int dtls1_flush_flight(SSL *ssl) {
  720. ssl->d1->outgoing_messages_complete = true;
  721. // Start the retransmission timer for the next flight (if any).
  722. dtls1_start_timer(ssl);
  723. return send_flight(ssl);
  724. }
  725. int dtls1_retransmit_outgoing_messages(SSL *ssl) {
  726. // Rewind to the start of the flight and write it again.
  727. //
  728. // TODO(davidben): This does not allow retransmits to be resumed on
  729. // non-blocking write.
  730. ssl->d1->outgoing_written = 0;
  731. ssl->d1->outgoing_offset = 0;
  732. return send_flight(ssl);
  733. }
  734. unsigned int dtls1_min_mtu(void) {
  735. return kMinMTU;
  736. }
  737. BSSL_NAMESPACE_END