rec_layer_s3.c 51 KB

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