rec_layer_s3.c 49 KB

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