rec_layer_s3.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. /*
  2. * Copyright 1995-2024 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 <stdio.h>
  10. #include <limits.h>
  11. #include <errno.h>
  12. #include <assert.h>
  13. #include "../ssl_local.h"
  14. #include "../quic/quic_local.h"
  15. #include <openssl/evp.h>
  16. #include <openssl/buffer.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/core_names.h>
  19. #include "record_local.h"
  20. #include "internal/packet.h"
  21. void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
  22. {
  23. rl->s = s;
  24. }
  25. int RECORD_LAYER_clear(RECORD_LAYER *rl)
  26. {
  27. int ret = 1;
  28. /* Clear any buffered records we no longer need */
  29. while (rl->curr_rec < rl->num_recs)
  30. ret &= ssl_release_record(rl->s,
  31. &(rl->tlsrecs[rl->curr_rec++]),
  32. 0);
  33. rl->wnum = 0;
  34. memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
  35. rl->handshake_fragment_len = 0;
  36. rl->wpend_tot = 0;
  37. rl->wpend_type = 0;
  38. rl->wpend_ret = 0;
  39. rl->wpend_buf = NULL;
  40. rl->alert_count = 0;
  41. rl->num_recs = 0;
  42. rl->curr_rec = 0;
  43. BIO_free(rl->rrlnext);
  44. rl->rrlnext = NULL;
  45. if (rl->rrlmethod != NULL)
  46. rl->rrlmethod->free(rl->rrl); /* Ignore return value */
  47. if (rl->wrlmethod != NULL)
  48. rl->wrlmethod->free(rl->wrl); /* Ignore return value */
  49. BIO_free(rl->rrlnext);
  50. rl->rrlmethod = NULL;
  51. rl->wrlmethod = NULL;
  52. rl->rrlnext = NULL;
  53. rl->rrl = NULL;
  54. rl->wrl = NULL;
  55. if (rl->d)
  56. DTLS_RECORD_LAYER_clear(rl);
  57. return ret;
  58. }
  59. int RECORD_LAYER_reset(RECORD_LAYER *rl)
  60. {
  61. int ret;
  62. ret = RECORD_LAYER_clear(rl);
  63. /* We try and reset both record layers even if one fails */
  64. ret &= ssl_set_new_record_layer(rl->s,
  65. SSL_CONNECTION_IS_DTLS(rl->s)
  66. ? DTLS_ANY_VERSION : TLS_ANY_VERSION,
  67. OSSL_RECORD_DIRECTION_READ,
  68. OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
  69. NULL, 0, NULL, 0, NULL, 0, NULL, 0,
  70. NID_undef, NULL, NULL, NULL);
  71. ret &= ssl_set_new_record_layer(rl->s,
  72. SSL_CONNECTION_IS_DTLS(rl->s)
  73. ? DTLS_ANY_VERSION : TLS_ANY_VERSION,
  74. OSSL_RECORD_DIRECTION_WRITE,
  75. OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
  76. NULL, 0, NULL, 0, NULL, 0, NULL, 0,
  77. NID_undef, NULL, NULL, NULL);
  78. /* SSLfatal already called in the event of failure */
  79. return ret;
  80. }
  81. /* Checks if we have unprocessed read ahead data pending */
  82. int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
  83. {
  84. return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
  85. }
  86. /* Checks if we have decrypted unread record data pending */
  87. int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
  88. {
  89. return (rl->curr_rec < rl->num_recs)
  90. || rl->rrlmethod->processed_read_pending(rl->rrl);
  91. }
  92. int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
  93. {
  94. return rl->wpend_tot > 0;
  95. }
  96. static uint32_t ossl_get_max_early_data(SSL_CONNECTION *s)
  97. {
  98. uint32_t max_early_data;
  99. SSL_SESSION *sess = s->session;
  100. /*
  101. * If we are a client then we always use the max_early_data from the
  102. * session/psksession. Otherwise we go with the lowest out of the max early
  103. * data set in the session and the configured max_early_data.
  104. */
  105. if (!s->server && sess->ext.max_early_data == 0) {
  106. if (!ossl_assert(s->psksession != NULL
  107. && s->psksession->ext.max_early_data > 0)) {
  108. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  109. return 0;
  110. }
  111. sess = s->psksession;
  112. }
  113. if (!s->server)
  114. max_early_data = sess->ext.max_early_data;
  115. else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
  116. max_early_data = s->recv_max_early_data;
  117. else
  118. max_early_data = s->recv_max_early_data < sess->ext.max_early_data
  119. ? s->recv_max_early_data : sess->ext.max_early_data;
  120. return max_early_data;
  121. }
  122. static int ossl_early_data_count_ok(SSL_CONNECTION *s, size_t length,
  123. size_t overhead, int send)
  124. {
  125. uint32_t max_early_data;
  126. max_early_data = ossl_get_max_early_data(s);
  127. if (max_early_data == 0) {
  128. SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
  129. SSL_R_TOO_MUCH_EARLY_DATA);
  130. return 0;
  131. }
  132. /* If we are dealing with ciphertext we need to allow for the overhead */
  133. max_early_data += overhead;
  134. if (s->early_data_count + length > max_early_data) {
  135. SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
  136. SSL_R_TOO_MUCH_EARLY_DATA);
  137. return 0;
  138. }
  139. s->early_data_count += length;
  140. return 1;
  141. }
  142. size_t ssl3_pending(const SSL *s)
  143. {
  144. size_t i, num = 0;
  145. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  146. if (sc == NULL)
  147. return 0;
  148. if (SSL_CONNECTION_IS_DTLS(sc)) {
  149. TLS_RECORD *rdata;
  150. pitem *item, *iter;
  151. iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
  152. while ((item = pqueue_next(&iter)) != NULL) {
  153. rdata = item->data;
  154. num += rdata->length;
  155. }
  156. }
  157. for (i = 0; i < sc->rlayer.num_recs; i++) {
  158. if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
  159. return num;
  160. num += sc->rlayer.tlsrecs[i].length;
  161. }
  162. num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
  163. return num;
  164. }
  165. void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
  166. {
  167. ctx->default_read_buf_len = len;
  168. }
  169. void SSL_set_default_read_buffer_len(SSL *s, size_t len)
  170. {
  171. SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
  172. if (sc == NULL || IS_QUIC(s))
  173. return;
  174. sc->rlayer.default_read_buf_len = len;
  175. }
  176. const char *SSL_rstate_string_long(const SSL *s)
  177. {
  178. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  179. const char *lng;
  180. if (sc == NULL)
  181. return NULL;
  182. if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
  183. return "unknown";
  184. sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
  185. return lng;
  186. }
  187. const char *SSL_rstate_string(const SSL *s)
  188. {
  189. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  190. const char *shrt;
  191. if (sc == NULL)
  192. return NULL;
  193. if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
  194. return "unknown";
  195. sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
  196. return shrt;
  197. }
  198. static int tls_write_check_pending(SSL_CONNECTION *s, uint8_t type,
  199. const unsigned char *buf, size_t len)
  200. {
  201. if (s->rlayer.wpend_tot == 0)
  202. return 0;
  203. /* We have pending data, so do some sanity checks */
  204. if ((s->rlayer.wpend_tot > len)
  205. || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
  206. && (s->rlayer.wpend_buf != buf))
  207. || (s->rlayer.wpend_type != type)) {
  208. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
  209. return -1;
  210. }
  211. return 1;
  212. }
  213. /*
  214. * Call this to write data in records of type 'type' It will return <= 0 if
  215. * not all data has been sent or non-blocking IO.
  216. */
  217. int ssl3_write_bytes(SSL *ssl, uint8_t type, const void *buf_, size_t len,
  218. size_t *written)
  219. {
  220. const unsigned char *buf = buf_;
  221. size_t tot;
  222. size_t n, max_send_fragment, split_send_fragment, maxpipes;
  223. int i;
  224. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  225. OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
  226. unsigned int recversion;
  227. if (s == NULL)
  228. return -1;
  229. s->rwstate = SSL_NOTHING;
  230. tot = s->rlayer.wnum;
  231. /*
  232. * ensure that if we end up with a smaller value of data to write out
  233. * than the original len from a write which didn't complete for
  234. * non-blocking I/O and also somehow ended up avoiding the check for
  235. * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
  236. * possible to end up with (len-tot) as a large number that will then
  237. * promptly send beyond the end of the users buffer ... so we trap and
  238. * report the error in a way the user will notice
  239. */
  240. if ((len < s->rlayer.wnum)
  241. || ((s->rlayer.wpend_tot != 0)
  242. && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
  243. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
  244. return -1;
  245. }
  246. if (s->early_data_state == SSL_EARLY_DATA_WRITING
  247. && !ossl_early_data_count_ok(s, len, 0, 1)) {
  248. /* SSLfatal() already called */
  249. return -1;
  250. }
  251. s->rlayer.wnum = 0;
  252. /*
  253. * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
  254. * into init unless we have writes pending - in which case we should finish
  255. * doing that first.
  256. */
  257. if (s->rlayer.wpend_tot == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
  258. || s->ext.extra_tickets_expected > 0))
  259. ossl_statem_set_in_init(s, 1);
  260. /*
  261. * When writing early data on the server side we could be "in_init" in
  262. * between receiving the EoED and the CF - but we don't want to handle those
  263. * messages yet.
  264. */
  265. if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
  266. && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
  267. i = s->handshake_func(ssl);
  268. /* SSLfatal() already called */
  269. if (i < 0)
  270. return i;
  271. if (i == 0) {
  272. return -1;
  273. }
  274. }
  275. i = tls_write_check_pending(s, type, buf, len);
  276. if (i < 0) {
  277. /* SSLfatal() already called */
  278. return i;
  279. } else if (i > 0) {
  280. /* Retry needed */
  281. i = HANDLE_RLAYER_WRITE_RETURN(s,
  282. s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl));
  283. if (i <= 0) {
  284. s->rlayer.wnum = tot;
  285. return i;
  286. }
  287. tot += s->rlayer.wpend_tot;
  288. s->rlayer.wpend_tot = 0;
  289. } /* else no retry required */
  290. if (tot == 0) {
  291. /*
  292. * We've not previously sent any data for this write so memorize
  293. * arguments so that we can detect bad write retries later
  294. */
  295. s->rlayer.wpend_tot = 0;
  296. s->rlayer.wpend_type = type;
  297. s->rlayer.wpend_buf = buf;
  298. s->rlayer.wpend_ret = len;
  299. }
  300. if (tot == len) { /* done? */
  301. *written = tot;
  302. return 1;
  303. }
  304. /* If we have an alert to send, lets send it */
  305. if (s->s3.alert_dispatch > 0) {
  306. i = ssl->method->ssl_dispatch_alert(ssl);
  307. if (i <= 0) {
  308. /* SSLfatal() already called if appropriate */
  309. s->rlayer.wnum = tot;
  310. return i;
  311. }
  312. /* if it went, fall through and send more stuff */
  313. }
  314. n = (len - tot);
  315. max_send_fragment = ssl_get_max_send_fragment(s);
  316. split_send_fragment = ssl_get_split_send_fragment(s);
  317. if (max_send_fragment == 0
  318. || split_send_fragment == 0
  319. || split_send_fragment > max_send_fragment) {
  320. /*
  321. * We should have prevented this when we set/get the split and max send
  322. * fragments so we shouldn't get here
  323. */
  324. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  325. return -1;
  326. }
  327. /*
  328. * Some servers hang if initial client hello is larger than 256 bytes
  329. * and record version number > TLS 1.0
  330. */
  331. recversion = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION : s->version;
  332. if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
  333. && !s->renegotiate
  334. && TLS1_get_version(ssl) > TLS1_VERSION
  335. && s->hello_retry_request == SSL_HRR_NONE)
  336. recversion = TLS1_VERSION;
  337. for (;;) {
  338. size_t tmppipelen, remain;
  339. size_t j, lensofar = 0;
  340. /*
  341. * Ask the record layer how it would like to split the amount of data
  342. * that we have, and how many of those records it would like in one go.
  343. */
  344. maxpipes = s->rlayer.wrlmethod->get_max_records(s->rlayer.wrl, type, n,
  345. max_send_fragment,
  346. &split_send_fragment);
  347. /*
  348. * If max_pipelines is 0 then this means "undefined" and we default to
  349. * whatever the record layer wants to do. Otherwise we use the smallest
  350. * value from the number requested by the record layer, and max number
  351. * configured by the user.
  352. */
  353. if (s->max_pipelines > 0 && maxpipes > s->max_pipelines)
  354. maxpipes = s->max_pipelines;
  355. if (maxpipes > SSL_MAX_PIPELINES)
  356. maxpipes = SSL_MAX_PIPELINES;
  357. if (split_send_fragment > max_send_fragment) {
  358. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  359. return -1;
  360. }
  361. if (n / maxpipes >= split_send_fragment) {
  362. /*
  363. * We have enough data to completely fill all available
  364. * pipelines
  365. */
  366. for (j = 0; j < maxpipes; j++) {
  367. tmpls[j].type = type;
  368. tmpls[j].version = recversion;
  369. tmpls[j].buf = &(buf[tot]) + (j * split_send_fragment);
  370. tmpls[j].buflen = split_send_fragment;
  371. }
  372. /* Remember how much data we are going to be sending */
  373. s->rlayer.wpend_tot = maxpipes * split_send_fragment;
  374. } else {
  375. /* We can partially fill all available pipelines */
  376. tmppipelen = n / maxpipes;
  377. remain = n % maxpipes;
  378. /*
  379. * If there is a remainder we add an extra byte to the first few
  380. * pipelines
  381. */
  382. if (remain > 0)
  383. tmppipelen++;
  384. for (j = 0; j < maxpipes; j++) {
  385. tmpls[j].type = type;
  386. tmpls[j].version = recversion;
  387. tmpls[j].buf = &(buf[tot]) + lensofar;
  388. tmpls[j].buflen = tmppipelen;
  389. lensofar += tmppipelen;
  390. if (j + 1 == remain)
  391. tmppipelen--;
  392. }
  393. /* Remember how much data we are going to be sending */
  394. s->rlayer.wpend_tot = n;
  395. }
  396. i = HANDLE_RLAYER_WRITE_RETURN(s,
  397. s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, maxpipes));
  398. if (i <= 0) {
  399. /* SSLfatal() already called if appropriate */
  400. s->rlayer.wnum = tot;
  401. return i;
  402. }
  403. if (s->rlayer.wpend_tot == n
  404. || (type == SSL3_RT_APPLICATION_DATA
  405. && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)) {
  406. *written = tot + s->rlayer.wpend_tot;
  407. s->rlayer.wpend_tot = 0;
  408. return 1;
  409. }
  410. n -= s->rlayer.wpend_tot;
  411. tot += s->rlayer.wpend_tot;
  412. }
  413. }
  414. int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
  415. char *file, int line)
  416. {
  417. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  418. if (ret == OSSL_RECORD_RETURN_RETRY) {
  419. s->rwstate = writing ? SSL_WRITING : SSL_READING;
  420. ret = -1;
  421. } else {
  422. s->rwstate = SSL_NOTHING;
  423. if (ret == OSSL_RECORD_RETURN_EOF) {
  424. if (writing) {
  425. /*
  426. * This shouldn't happen with a writing operation. We treat it
  427. * as fatal.
  428. */
  429. ERR_new();
  430. ERR_set_debug(file, line, 0);
  431. ossl_statem_fatal(s, SSL_AD_INTERNAL_ERROR,
  432. ERR_R_INTERNAL_ERROR, NULL);
  433. ret = OSSL_RECORD_RETURN_FATAL;
  434. } else if ((s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) != 0) {
  435. SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
  436. s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
  437. } else {
  438. ERR_new();
  439. ERR_set_debug(file, line, 0);
  440. /*
  441. * This reason code is part of the API and may be used by
  442. * applications for control flow decisions.
  443. */
  444. ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
  445. SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
  446. }
  447. } else if (ret == OSSL_RECORD_RETURN_FATAL) {
  448. int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
  449. if (al != SSL_AD_NO_ALERT) {
  450. ERR_new();
  451. ERR_set_debug(file, line, 0);
  452. ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
  453. }
  454. /*
  455. * else some failure but there is no alert code. We don't log an
  456. * error for this. The record layer should have logged an error
  457. * already or, if not, its due to some sys call error which will be
  458. * reported via SSL_ERROR_SYSCALL and errno.
  459. */
  460. }
  461. /*
  462. * The record layer distinguishes the cases of EOF, non-fatal
  463. * err and retry. Upper layers do not.
  464. * If we got a retry or success then *ret is already correct,
  465. * otherwise we need to convert the return value.
  466. */
  467. if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
  468. ret = 0;
  469. else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
  470. ret = -1;
  471. }
  472. return ret;
  473. }
  474. int ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr, size_t length)
  475. {
  476. assert(rr->length >= length);
  477. if (rr->rechandle != NULL) {
  478. if (length == 0)
  479. length = rr->length;
  480. /* The record layer allocated the buffers for this record */
  481. if (HANDLE_RLAYER_READ_RETURN(s,
  482. s->rlayer.rrlmethod->release_record(s->rlayer.rrl,
  483. rr->rechandle,
  484. length)) <= 0) {
  485. /* RLAYER_fatal already called */
  486. return 0;
  487. }
  488. if (length == rr->length)
  489. s->rlayer.curr_rec++;
  490. } else if (length == 0 || length == rr->length) {
  491. /* We allocated the buffers for this record (only happens with DTLS) */
  492. OPENSSL_free(rr->allocdata);
  493. rr->allocdata = NULL;
  494. }
  495. rr->length -= length;
  496. if (rr->length > 0)
  497. rr->off += length;
  498. else
  499. rr->off = 0;
  500. return 1;
  501. }
  502. /*-
  503. * Return up to 'len' payload bytes received in 'type' records.
  504. * 'type' is one of the following:
  505. *
  506. * - SSL3_RT_HANDSHAKE (when tls_get_message_header and tls_get_message_body
  507. * call us)
  508. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  509. * - 0 (during a shutdown, no data has to be returned)
  510. *
  511. * If we don't have stored data to work from, read a SSL/TLS record first
  512. * (possibly multiple records if we still don't have anything to return).
  513. *
  514. * This function must handle any surprises the peer may have for us, such as
  515. * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
  516. * messages are treated as if they were handshake messages *if* the |recvd_type|
  517. * argument is non NULL.
  518. * Also if record payloads contain fragments too small to process, we store
  519. * them until there is enough for the respective protocol (the record protocol
  520. * may use arbitrary fragmentation and even interleaving):
  521. * Change cipher spec protocol
  522. * just 1 byte needed, no need for keeping anything stored
  523. * Alert protocol
  524. * 2 bytes needed (AlertLevel, AlertDescription)
  525. * Handshake protocol
  526. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  527. * to detect unexpected Client Hello and Hello Request messages
  528. * here, anything else is handled by higher layers
  529. * Application data protocol
  530. * none of our business
  531. */
  532. int ssl3_read_bytes(SSL *ssl, uint8_t type, uint8_t *recvd_type,
  533. unsigned char *buf, size_t len,
  534. int peek, size_t *readbytes)
  535. {
  536. int i, j, ret;
  537. size_t n, curr_rec, totalbytes;
  538. TLS_RECORD *rr;
  539. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  540. int is_tls13;
  541. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  542. is_tls13 = SSL_CONNECTION_IS_TLS13(s);
  543. if ((type != 0
  544. && (type != SSL3_RT_APPLICATION_DATA)
  545. && (type != SSL3_RT_HANDSHAKE))
  546. || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  547. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  548. return -1;
  549. }
  550. if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
  551. /* (partially) satisfy request from storage */
  552. {
  553. unsigned char *src = s->rlayer.handshake_fragment;
  554. unsigned char *dst = buf;
  555. unsigned int k;
  556. /* peek == 0 */
  557. n = 0;
  558. while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
  559. *dst++ = *src++;
  560. len--;
  561. s->rlayer.handshake_fragment_len--;
  562. n++;
  563. }
  564. /* move any remaining fragment bytes: */
  565. for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
  566. s->rlayer.handshake_fragment[k] = *src++;
  567. if (recvd_type != NULL)
  568. *recvd_type = SSL3_RT_HANDSHAKE;
  569. *readbytes = n;
  570. return 1;
  571. }
  572. /*
  573. * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  574. */
  575. if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
  576. /* type == SSL3_RT_APPLICATION_DATA */
  577. i = s->handshake_func(ssl);
  578. /* SSLfatal() already called */
  579. if (i < 0)
  580. return i;
  581. if (i == 0)
  582. return -1;
  583. }
  584. start:
  585. s->rwstate = SSL_NOTHING;
  586. /*-
  587. * For each record 'i' up to |num_recs]
  588. * rr[i].type - is the type of record
  589. * rr[i].data, - data
  590. * rr[i].off, - offset into 'data' for next read
  591. * rr[i].length, - number of bytes.
  592. */
  593. /* get new records if necessary */
  594. if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
  595. s->rlayer.curr_rec = s->rlayer.num_recs = 0;
  596. do {
  597. rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
  598. ret = HANDLE_RLAYER_READ_RETURN(s,
  599. s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
  600. &rr->rechandle,
  601. &rr->version, &rr->type,
  602. &rr->data, &rr->length,
  603. NULL, NULL));
  604. if (ret <= 0) {
  605. /* SSLfatal() already called if appropriate */
  606. return ret;
  607. }
  608. rr->off = 0;
  609. s->rlayer.num_recs++;
  610. } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
  611. && s->rlayer.num_recs < SSL_MAX_PIPELINES);
  612. }
  613. rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
  614. if (s->rlayer.handshake_fragment_len > 0
  615. && rr->type != SSL3_RT_HANDSHAKE
  616. && SSL_CONNECTION_IS_TLS13(s)) {
  617. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  618. SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
  619. return -1;
  620. }
  621. /*
  622. * Reset the count of consecutive warning alerts if we've got a non-empty
  623. * record that isn't an alert.
  624. */
  625. if (rr->type != SSL3_RT_ALERT && rr->length != 0)
  626. s->rlayer.alert_count = 0;
  627. /* we now have a packet which can be read and processed */
  628. if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
  629. * reset by ssl3_get_finished */
  630. && (rr->type != SSL3_RT_HANDSHAKE)) {
  631. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  632. SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  633. return -1;
  634. }
  635. /*
  636. * If the other end has shut down, throw anything we read away (even in
  637. * 'peek' mode)
  638. */
  639. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  640. s->rlayer.curr_rec++;
  641. s->rwstate = SSL_NOTHING;
  642. return 0;
  643. }
  644. if (type == rr->type
  645. || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  646. && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
  647. && !is_tls13)) {
  648. /*
  649. * SSL3_RT_APPLICATION_DATA or
  650. * SSL3_RT_HANDSHAKE or
  651. * SSL3_RT_CHANGE_CIPHER_SPEC
  652. */
  653. /*
  654. * make sure that we are not getting application data when we are
  655. * doing a handshake for the first time
  656. */
  657. if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
  658. && SSL_IS_FIRST_HANDSHAKE(s)) {
  659. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
  660. return -1;
  661. }
  662. if (type == SSL3_RT_HANDSHAKE
  663. && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  664. && s->rlayer.handshake_fragment_len > 0) {
  665. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  666. return -1;
  667. }
  668. if (recvd_type != NULL)
  669. *recvd_type = rr->type;
  670. if (len == 0) {
  671. /*
  672. * Skip a zero length record. This ensures multiple calls to
  673. * SSL_read() with a zero length buffer will eventually cause
  674. * SSL_pending() to report data as being available.
  675. */
  676. if (rr->length == 0 && !ssl_release_record(s, rr, 0))
  677. return -1;
  678. return 0;
  679. }
  680. totalbytes = 0;
  681. curr_rec = s->rlayer.curr_rec;
  682. do {
  683. if (len - totalbytes > rr->length)
  684. n = rr->length;
  685. else
  686. n = len - totalbytes;
  687. memcpy(buf, &(rr->data[rr->off]), n);
  688. buf += n;
  689. if (peek) {
  690. /* Mark any zero length record as consumed CVE-2016-6305 */
  691. if (rr->length == 0 && !ssl_release_record(s, rr, 0))
  692. return -1;
  693. } else {
  694. if (!ssl_release_record(s, rr, n))
  695. return -1;
  696. }
  697. if (rr->length == 0
  698. || (peek && n == rr->length)) {
  699. rr++;
  700. curr_rec++;
  701. }
  702. totalbytes += n;
  703. } while (type == SSL3_RT_APPLICATION_DATA
  704. && curr_rec < s->rlayer.num_recs
  705. && totalbytes < len);
  706. if (totalbytes == 0) {
  707. /* We must have read empty records. Get more data */
  708. goto start;
  709. }
  710. *readbytes = totalbytes;
  711. return 1;
  712. }
  713. /*
  714. * If we get here, then type != rr->type; if we have a handshake message,
  715. * then it was unexpected (Hello Request or Client Hello) or invalid (we
  716. * were actually expecting a CCS).
  717. */
  718. /*
  719. * Lets just double check that we've not got an SSLv2 record
  720. */
  721. if (rr->version == SSL2_VERSION) {
  722. /*
  723. * Should never happen. ssl3_get_record() should only give us an SSLv2
  724. * record back if this is the first packet and we are looking for an
  725. * initial ClientHello. Therefore |type| should always be equal to
  726. * |rr->type|. If not then something has gone horribly wrong
  727. */
  728. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  729. return -1;
  730. }
  731. if (ssl->method->version == TLS_ANY_VERSION
  732. && (s->server || rr->type != SSL3_RT_ALERT)) {
  733. /*
  734. * If we've got this far and still haven't decided on what version
  735. * we're using then this must be a client side alert we're dealing
  736. * with. We shouldn't be receiving anything other than a ClientHello
  737. * if we are a server.
  738. */
  739. s->version = rr->version;
  740. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
  741. return -1;
  742. }
  743. /*-
  744. * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  745. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  746. */
  747. if (rr->type == SSL3_RT_ALERT) {
  748. unsigned int alert_level, alert_descr;
  749. const unsigned char *alert_bytes = rr->data + rr->off;
  750. PACKET alert;
  751. if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
  752. || !PACKET_get_1(&alert, &alert_level)
  753. || !PACKET_get_1(&alert, &alert_descr)
  754. || PACKET_remaining(&alert) != 0) {
  755. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
  756. return -1;
  757. }
  758. if (s->msg_callback)
  759. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
  760. s->msg_callback_arg);
  761. if (s->info_callback != NULL)
  762. cb = s->info_callback;
  763. else if (ssl->ctx->info_callback != NULL)
  764. cb = ssl->ctx->info_callback;
  765. if (cb != NULL) {
  766. j = (alert_level << 8) | alert_descr;
  767. cb(ssl, SSL_CB_READ_ALERT, j);
  768. }
  769. if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
  770. || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
  771. s->s3.warn_alert = alert_descr;
  772. if (!ssl_release_record(s, rr, 0))
  773. return -1;
  774. s->rlayer.alert_count++;
  775. if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
  776. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  777. SSL_R_TOO_MANY_WARN_ALERTS);
  778. return -1;
  779. }
  780. }
  781. /*
  782. * Apart from close_notify the only other warning alert in TLSv1.3
  783. * is user_cancelled - which we just ignore.
  784. */
  785. if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
  786. goto start;
  787. } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
  788. && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
  789. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  790. return 0;
  791. } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
  792. s->rwstate = SSL_NOTHING;
  793. s->s3.fatal_alert = alert_descr;
  794. SSLfatal_data(s, SSL_AD_NO_ALERT,
  795. SSL_AD_REASON_OFFSET + alert_descr,
  796. "SSL alert number %d", alert_descr);
  797. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  798. if (!ssl_release_record(s, rr, 0))
  799. return -1;
  800. SSL_CTX_remove_session(s->session_ctx, s->session);
  801. return 0;
  802. } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  803. /*
  804. * This is a warning but we receive it if we requested
  805. * renegotiation and the peer denied it. Terminate with a fatal
  806. * alert because if application tried to renegotiate it
  807. * presumably had a good reason and expects it to succeed. In
  808. * future we might have a renegotiation where we don't care if
  809. * the peer refused it where we carry on.
  810. */
  811. SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
  812. return -1;
  813. } else if (alert_level == SSL3_AL_WARNING) {
  814. /* We ignore any other warning alert in TLSv1.2 and below */
  815. goto start;
  816. }
  817. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
  818. return -1;
  819. }
  820. if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
  821. if (rr->type == SSL3_RT_HANDSHAKE) {
  822. BIO *rbio;
  823. /*
  824. * We ignore any handshake messages sent to us unless they are
  825. * TLSv1.3 in which case we want to process them. For all other
  826. * handshake messages we can't do anything reasonable with them
  827. * because we are unable to write any response due to having already
  828. * sent close_notify.
  829. */
  830. if (!SSL_CONNECTION_IS_TLS13(s)) {
  831. if (!ssl_release_record(s, rr, 0))
  832. return -1;
  833. if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
  834. goto start;
  835. s->rwstate = SSL_READING;
  836. rbio = SSL_get_rbio(ssl);
  837. BIO_clear_retry_flags(rbio);
  838. BIO_set_retry_read(rbio);
  839. return -1;
  840. }
  841. } else {
  842. /*
  843. * The peer is continuing to send application data, but we have
  844. * already sent close_notify. If this was expected we should have
  845. * been called via SSL_read() and this would have been handled
  846. * above.
  847. * No alert sent because we already sent close_notify
  848. */
  849. if (!ssl_release_record(s, rr, 0))
  850. return -1;
  851. SSLfatal(s, SSL_AD_NO_ALERT,
  852. SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
  853. return -1;
  854. }
  855. }
  856. /*
  857. * For handshake data we have 'fragment' storage, so fill that so that we
  858. * can process the header at a fixed place. This is done after the
  859. * "SHUTDOWN" code above to avoid filling the fragment storage with data
  860. * that we're just going to discard.
  861. */
  862. if (rr->type == SSL3_RT_HANDSHAKE) {
  863. size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
  864. unsigned char *dest = s->rlayer.handshake_fragment;
  865. size_t *dest_len = &s->rlayer.handshake_fragment_len;
  866. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  867. if (rr->length < n)
  868. n = rr->length; /* available bytes */
  869. /* now move 'n' bytes: */
  870. if (n > 0) {
  871. memcpy(dest + *dest_len, rr->data + rr->off, n);
  872. *dest_len += n;
  873. }
  874. /*
  875. * We release the number of bytes consumed, or the whole record if it
  876. * is zero length
  877. */
  878. if ((n > 0 || rr->length == 0) && !ssl_release_record(s, rr, n))
  879. return -1;
  880. if (*dest_len < dest_maxlen)
  881. goto start; /* fragment was too small */
  882. }
  883. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  884. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  885. return -1;
  886. }
  887. /*
  888. * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
  889. * protocol violation)
  890. */
  891. if ((s->rlayer.handshake_fragment_len >= 4)
  892. && !ossl_statem_get_in_handshake(s)) {
  893. int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
  894. /* We found handshake data, so we're going back into init */
  895. ossl_statem_set_in_init(s, 1);
  896. i = s->handshake_func(ssl);
  897. /* SSLfatal() already called if appropriate */
  898. if (i < 0)
  899. return i;
  900. if (i == 0) {
  901. return -1;
  902. }
  903. /*
  904. * If we were actually trying to read early data and we found a
  905. * handshake message, then we don't want to continue to try and read
  906. * the application data any more. It won't be "early" now.
  907. */
  908. if (ined)
  909. return -1;
  910. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  911. if (!RECORD_LAYER_read_pending(&s->rlayer)) {
  912. BIO *bio;
  913. /*
  914. * In the case where we try to read application data, but we
  915. * trigger an SSL handshake, we return -1 with the retry
  916. * option set. Otherwise renegotiation may cause nasty
  917. * problems in the blocking world
  918. */
  919. s->rwstate = SSL_READING;
  920. bio = SSL_get_rbio(ssl);
  921. BIO_clear_retry_flags(bio);
  922. BIO_set_retry_read(bio);
  923. return -1;
  924. }
  925. }
  926. goto start;
  927. }
  928. switch (rr->type) {
  929. default:
  930. /*
  931. * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
  932. * TLS 1.2 says you MUST send an unexpected message alert. We use the
  933. * TLS 1.2 behaviour for all protocol versions to prevent issues where
  934. * no progress is being made and the peer continually sends unrecognised
  935. * record types, using up resources processing them.
  936. */
  937. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  938. return -1;
  939. case SSL3_RT_CHANGE_CIPHER_SPEC:
  940. case SSL3_RT_ALERT:
  941. case SSL3_RT_HANDSHAKE:
  942. /*
  943. * we already handled all of these, with the possible exception of
  944. * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
  945. * that should not happen when type != rr->type
  946. */
  947. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
  948. return -1;
  949. case SSL3_RT_APPLICATION_DATA:
  950. /*
  951. * At this point, we were expecting handshake data, but have
  952. * application data. If the library was running inside ssl3_read()
  953. * (i.e. in_read_app_data is set) and it makes sense to read
  954. * application data at this point (session renegotiation not yet
  955. * started), we will indulge it.
  956. */
  957. if (ossl_statem_app_data_allowed(s)) {
  958. s->s3.in_read_app_data = 2;
  959. return -1;
  960. } else if (ossl_statem_skip_early_data(s)) {
  961. /*
  962. * This can happen after a client sends a CH followed by early_data,
  963. * but the server responds with a HelloRetryRequest. The server
  964. * reads the next record from the client expecting to find a
  965. * plaintext ClientHello but gets a record which appears to be
  966. * application data. The trial decrypt "works" because null
  967. * decryption was applied. We just skip it and move on to the next
  968. * record.
  969. */
  970. if (!ossl_early_data_count_ok(s, rr->length,
  971. EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
  972. /* SSLfatal() already called */
  973. return -1;
  974. }
  975. if (!ssl_release_record(s, rr, 0))
  976. return -1;
  977. goto start;
  978. } else {
  979. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  980. return -1;
  981. }
  982. }
  983. }
  984. /*
  985. * Returns true if the current rrec was sent in SSLv2 backwards compatible
  986. * format and false otherwise.
  987. */
  988. int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
  989. {
  990. if (SSL_CONNECTION_IS_DTLS(rl->s))
  991. return 0;
  992. return rl->tlsrecs[0].version == SSL2_VERSION;
  993. }
  994. static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
  995. static void rlayer_msg_callback_wrapper(int write_p, int version,
  996. int content_type, const void *buf,
  997. size_t len, void *cbarg)
  998. {
  999. SSL_CONNECTION *s = cbarg;
  1000. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1001. if (s->msg_callback != NULL)
  1002. s->msg_callback(write_p, version, content_type, buf, len, ssl,
  1003. s->msg_callback_arg);
  1004. }
  1005. static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
  1006. static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
  1007. void *other)
  1008. {
  1009. SSL_CONNECTION *s = cbarg;
  1010. return ssl_security(s, op, bits, nid, other);
  1011. }
  1012. static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
  1013. static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
  1014. {
  1015. SSL_CONNECTION *s = cbarg;
  1016. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1017. return s->rlayer.record_padding_cb(ssl, type, len,
  1018. s->rlayer.record_padding_arg);
  1019. }
  1020. static const OSSL_DISPATCH rlayer_dispatch[] = {
  1021. { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
  1022. { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
  1023. { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
  1024. { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
  1025. OSSL_DISPATCH_END
  1026. };
  1027. void ossl_ssl_set_custom_record_layer(SSL_CONNECTION *s,
  1028. const OSSL_RECORD_METHOD *meth,
  1029. void *rlarg)
  1030. {
  1031. s->rlayer.custom_rlmethod = meth;
  1032. s->rlayer.rlarg = rlarg;
  1033. }
  1034. static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
  1035. int direction,
  1036. int level)
  1037. {
  1038. if (s->rlayer.custom_rlmethod != NULL)
  1039. return s->rlayer.custom_rlmethod;
  1040. if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
  1041. if (SSL_CONNECTION_IS_DTLS(s))
  1042. return &ossl_dtls_record_method;
  1043. return &ossl_tls_record_method;
  1044. }
  1045. #ifndef OPENSSL_NO_KTLS
  1046. /* KTLS does not support renegotiation */
  1047. if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
  1048. && (s->options & SSL_OP_ENABLE_KTLS) != 0
  1049. && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
  1050. return &ossl_ktls_record_method;
  1051. #endif
  1052. /* Default to the current OSSL_RECORD_METHOD */
  1053. return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
  1054. : s->rlayer.wrlmethod;
  1055. }
  1056. static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
  1057. {
  1058. const OSSL_RECORD_METHOD *thismethod;
  1059. OSSL_RECORD_LAYER *thisrl;
  1060. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1061. thismethod = s->rlayer.rrlmethod;
  1062. thisrl = s->rlayer.rrl;
  1063. } else {
  1064. thismethod = s->rlayer.wrlmethod;
  1065. thisrl = s->rlayer.wrl;
  1066. }
  1067. #ifndef OPENSSL_NO_KTLS
  1068. {
  1069. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1070. if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
  1071. /* KTLS does not support renegotiation so disallow it */
  1072. SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
  1073. }
  1074. }
  1075. #endif
  1076. if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
  1077. thismethod->set_first_handshake(thisrl, 1);
  1078. if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
  1079. thismethod->set_max_pipelines(thisrl, s->max_pipelines);
  1080. return 1;
  1081. }
  1082. int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
  1083. int direction, int level,
  1084. unsigned char *secret, size_t secretlen,
  1085. unsigned char *key, size_t keylen,
  1086. unsigned char *iv, size_t ivlen,
  1087. unsigned char *mackey, size_t mackeylen,
  1088. const EVP_CIPHER *ciph, size_t taglen,
  1089. int mactype, const EVP_MD *md,
  1090. const SSL_COMP *comp, const EVP_MD *kdfdigest)
  1091. {
  1092. OSSL_PARAM options[5], *opts = options;
  1093. OSSL_PARAM settings[6], *set = settings;
  1094. const OSSL_RECORD_METHOD **thismethod;
  1095. OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
  1096. BIO *thisbio;
  1097. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  1098. const OSSL_RECORD_METHOD *meth;
  1099. int use_etm, stream_mac = 0, tlstree = 0;
  1100. unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
  1101. ? ssl_get_max_send_fragment(s)
  1102. : SSL3_RT_MAX_PLAIN_LENGTH;
  1103. int use_early_data = 0;
  1104. uint32_t max_early_data;
  1105. COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
  1106. meth = ssl_select_next_record_layer(s, direction, level);
  1107. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1108. thismethod = &s->rlayer.rrlmethod;
  1109. thisrl = &s->rlayer.rrl;
  1110. thisbio = s->rbio;
  1111. } else {
  1112. thismethod = &s->rlayer.wrlmethod;
  1113. thisrl = &s->rlayer.wrl;
  1114. thisbio = s->wbio;
  1115. }
  1116. if (meth == NULL)
  1117. meth = *thismethod;
  1118. if (!ossl_assert(meth != NULL)) {
  1119. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  1120. return 0;
  1121. }
  1122. /* Parameters that *may* be supported by a record layer if passed */
  1123. *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
  1124. &s->options);
  1125. *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
  1126. &s->mode);
  1127. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1128. *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
  1129. &s->rlayer.default_read_buf_len);
  1130. *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
  1131. &s->rlayer.read_ahead);
  1132. } else {
  1133. *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
  1134. &s->rlayer.block_padding);
  1135. }
  1136. *opts = OSSL_PARAM_construct_end();
  1137. /* Parameters that *must* be supported by a record layer if passed */
  1138. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1139. use_etm = SSL_READ_ETM(s) ? 1 : 0;
  1140. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
  1141. stream_mac = 1;
  1142. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
  1143. tlstree = 1;
  1144. } else {
  1145. use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
  1146. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
  1147. stream_mac = 1;
  1148. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
  1149. tlstree = 1;
  1150. }
  1151. if (use_etm)
  1152. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
  1153. &use_etm);
  1154. if (stream_mac)
  1155. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
  1156. &stream_mac);
  1157. if (tlstree)
  1158. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
  1159. &tlstree);
  1160. /*
  1161. * We only need to do this for the read side. The write side should already
  1162. * have the correct value due to the ssl_get_max_send_fragment() call above
  1163. */
  1164. if (direction == OSSL_RECORD_DIRECTION_READ
  1165. && s->session != NULL
  1166. && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
  1167. maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
  1168. if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
  1169. *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
  1170. &maxfrag);
  1171. /*
  1172. * The record layer must check the amount of early data sent or received
  1173. * using the early keys. A server also needs to worry about rejected early
  1174. * data that might arrive when the handshake keys are in force.
  1175. */
  1176. if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
  1177. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
  1178. || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
  1179. } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
  1180. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
  1181. }
  1182. if (use_early_data) {
  1183. max_early_data = ossl_get_max_early_data(s);
  1184. if (max_early_data != 0)
  1185. *set++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
  1186. &max_early_data);
  1187. }
  1188. *set = OSSL_PARAM_construct_end();
  1189. for (;;) {
  1190. int rlret;
  1191. BIO *prev = NULL;
  1192. BIO *next = NULL;
  1193. unsigned int epoch = 0;
  1194. OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
  1195. size_t i, j;
  1196. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1197. prev = s->rlayer.rrlnext;
  1198. if (SSL_CONNECTION_IS_DTLS(s)
  1199. && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1200. epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
  1201. #ifndef OPENSSL_NO_DGRAM
  1202. if (SSL_CONNECTION_IS_DTLS(s))
  1203. next = BIO_new(BIO_s_dgram_mem());
  1204. else
  1205. #endif
  1206. next = BIO_new(BIO_s_mem());
  1207. if (next == NULL) {
  1208. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1209. return 0;
  1210. }
  1211. s->rlayer.rrlnext = next;
  1212. } else {
  1213. if (SSL_CONNECTION_IS_DTLS(s)
  1214. && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1215. epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) + 1; /* new epoch */
  1216. }
  1217. /*
  1218. * Create a copy of the dispatch array, missing out wrappers for
  1219. * callbacks that we don't need.
  1220. */
  1221. for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
  1222. switch (rlayer_dispatch[i].function_id) {
  1223. case OSSL_FUNC_RLAYER_MSG_CALLBACK:
  1224. if (s->msg_callback == NULL)
  1225. continue;
  1226. break;
  1227. case OSSL_FUNC_RLAYER_PADDING:
  1228. if (s->rlayer.record_padding_cb == NULL)
  1229. continue;
  1230. break;
  1231. default:
  1232. break;
  1233. }
  1234. rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
  1235. }
  1236. rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
  1237. s->server, direction, level, epoch,
  1238. secret, secretlen, key, keylen, iv,
  1239. ivlen, mackey, mackeylen, ciph, taglen,
  1240. mactype, md, compm, kdfdigest, prev,
  1241. thisbio, next, NULL, NULL, settings,
  1242. options, rlayer_dispatch_tmp, s,
  1243. s->rlayer.rlarg, &newrl);
  1244. BIO_free(prev);
  1245. switch (rlret) {
  1246. case OSSL_RECORD_RETURN_FATAL:
  1247. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
  1248. return 0;
  1249. case OSSL_RECORD_RETURN_NON_FATAL_ERR:
  1250. if (*thismethod != meth && *thismethod != NULL) {
  1251. /*
  1252. * We tried a new record layer method, but it didn't work out,
  1253. * so we fallback to the original method and try again
  1254. */
  1255. meth = *thismethod;
  1256. continue;
  1257. }
  1258. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
  1259. return 0;
  1260. case OSSL_RECORD_RETURN_SUCCESS:
  1261. break;
  1262. default:
  1263. /* Should not happen */
  1264. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1265. return 0;
  1266. }
  1267. break;
  1268. }
  1269. /*
  1270. * Free the old record layer if we have one except in the case of DTLS when
  1271. * writing and there are still buffered sent messages in our queue. In that
  1272. * case the record layer is still referenced by those buffered messages for
  1273. * potential retransmit. Only when those buffered messages get freed do we
  1274. * free the record layer object (see dtls1_hm_fragment_free)
  1275. */
  1276. if (!SSL_CONNECTION_IS_DTLS(s)
  1277. || direction == OSSL_RECORD_DIRECTION_READ
  1278. || pqueue_peek(s->d1->sent_messages) == NULL) {
  1279. if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
  1280. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1281. return 0;
  1282. }
  1283. }
  1284. *thisrl = newrl;
  1285. *thismethod = meth;
  1286. return ssl_post_record_layer_select(s, direction);
  1287. }
  1288. int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
  1289. {
  1290. if (!ossl_assert(s->rlayer.rrlmethod != NULL)
  1291. || !ossl_assert(s->rlayer.wrlmethod != NULL))
  1292. return 0;
  1293. s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
  1294. s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);
  1295. return 1;
  1296. }