rec_layer_s3.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. /*
  2. * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include <limits.h>
  11. #include <errno.h>
  12. #include <assert.h>
  13. #include "../ssl_local.h"
  14. #include "../quic/quic_local.h"
  15. #include <openssl/evp.h>
  16. #include <openssl/buffer.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/core_names.h>
  19. #include "record_local.h"
  20. #include "internal/packet.h"
  21. void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
  22. {
  23. rl->s = s;
  24. }
  25. int RECORD_LAYER_clear(RECORD_LAYER *rl)
  26. {
  27. int ret = 1;
  28. /* Clear any buffered records we no longer need */
  29. while (rl->curr_rec < rl->num_recs)
  30. ret &= ssl_release_record(rl->s,
  31. &(rl->tlsrecs[rl->curr_rec++]),
  32. 0);
  33. rl->wnum = 0;
  34. memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
  35. rl->handshake_fragment_len = 0;
  36. rl->wpend_tot = 0;
  37. rl->wpend_type = 0;
  38. rl->wpend_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. int ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr, size_t length)
  473. {
  474. assert(rr->length >= length);
  475. if (rr->rechandle != NULL) {
  476. if (length == 0)
  477. length = rr->length;
  478. /* The record layer allocated the buffers for this record */
  479. if (HANDLE_RLAYER_READ_RETURN(s,
  480. s->rlayer.rrlmethod->release_record(s->rlayer.rrl,
  481. rr->rechandle,
  482. length)) <= 0) {
  483. /* RLAYER_fatal already called */
  484. return 0;
  485. }
  486. if (length == rr->length)
  487. s->rlayer.curr_rec++;
  488. } else if (length == 0 || length == rr->length) {
  489. /* We allocated the buffers for this record (only happens with DTLS) */
  490. OPENSSL_free(rr->allocdata);
  491. rr->allocdata = NULL;
  492. }
  493. rr->length -= length;
  494. if (rr->length > 0)
  495. rr->off += length;
  496. else
  497. rr->off = 0;
  498. return 1;
  499. }
  500. /*-
  501. * Return up to 'len' payload bytes received in 'type' records.
  502. * 'type' is one of the following:
  503. *
  504. * - SSL3_RT_HANDSHAKE (when tls_get_message_header and tls_get_message_body
  505. * call us)
  506. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  507. * - 0 (during a shutdown, no data has to be returned)
  508. *
  509. * If we don't have stored data to work from, read a SSL/TLS record first
  510. * (possibly multiple records if we still don't have anything to return).
  511. *
  512. * This function must handle any surprises the peer may have for us, such as
  513. * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
  514. * messages are treated as if they were handshake messages *if* the |recvd_type|
  515. * argument is non NULL.
  516. * Also if record payloads contain fragments too small to process, we store
  517. * them until there is enough for the respective protocol (the record protocol
  518. * may use arbitrary fragmentation and even interleaving):
  519. * Change cipher spec protocol
  520. * just 1 byte needed, no need for keeping anything stored
  521. * Alert protocol
  522. * 2 bytes needed (AlertLevel, AlertDescription)
  523. * Handshake protocol
  524. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  525. * to detect unexpected Client Hello and Hello Request messages
  526. * here, anything else is handled by higher layers
  527. * Application data protocol
  528. * none of our business
  529. */
  530. int ssl3_read_bytes(SSL *ssl, uint8_t type, uint8_t *recvd_type,
  531. unsigned char *buf, size_t len,
  532. int peek, size_t *readbytes)
  533. {
  534. int i, j, ret;
  535. size_t n, curr_rec, totalbytes;
  536. TLS_RECORD *rr;
  537. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  538. int is_tls13;
  539. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  540. is_tls13 = SSL_CONNECTION_IS_TLS13(s);
  541. if ((type != 0
  542. && (type != SSL3_RT_APPLICATION_DATA)
  543. && (type != SSL3_RT_HANDSHAKE))
  544. || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  545. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  546. return -1;
  547. }
  548. if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
  549. /* (partially) satisfy request from storage */
  550. {
  551. unsigned char *src = s->rlayer.handshake_fragment;
  552. unsigned char *dst = buf;
  553. unsigned int k;
  554. /* peek == 0 */
  555. n = 0;
  556. while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
  557. *dst++ = *src++;
  558. len--;
  559. s->rlayer.handshake_fragment_len--;
  560. n++;
  561. }
  562. /* move any remaining fragment bytes: */
  563. for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
  564. s->rlayer.handshake_fragment[k] = *src++;
  565. if (recvd_type != NULL)
  566. *recvd_type = SSL3_RT_HANDSHAKE;
  567. *readbytes = n;
  568. return 1;
  569. }
  570. /*
  571. * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  572. */
  573. if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
  574. /* type == SSL3_RT_APPLICATION_DATA */
  575. i = s->handshake_func(ssl);
  576. /* SSLfatal() already called */
  577. if (i < 0)
  578. return i;
  579. if (i == 0)
  580. return -1;
  581. }
  582. start:
  583. s->rwstate = SSL_NOTHING;
  584. /*-
  585. * For each record 'i' up to |num_recs]
  586. * rr[i].type - is the type of record
  587. * rr[i].data, - data
  588. * rr[i].off, - offset into 'data' for next read
  589. * rr[i].length, - number of bytes.
  590. */
  591. /* get new records if necessary */
  592. if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
  593. s->rlayer.curr_rec = s->rlayer.num_recs = 0;
  594. do {
  595. rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
  596. ret = HANDLE_RLAYER_READ_RETURN(s,
  597. s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
  598. &rr->rechandle,
  599. &rr->version, &rr->type,
  600. &rr->data, &rr->length,
  601. NULL, NULL));
  602. if (ret <= 0) {
  603. /* SSLfatal() already called if appropriate */
  604. return ret;
  605. }
  606. rr->off = 0;
  607. s->rlayer.num_recs++;
  608. } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
  609. && s->rlayer.num_recs < SSL_MAX_PIPELINES);
  610. }
  611. rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
  612. if (s->rlayer.handshake_fragment_len > 0
  613. && rr->type != SSL3_RT_HANDSHAKE
  614. && SSL_CONNECTION_IS_TLS13(s)) {
  615. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  616. SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
  617. return -1;
  618. }
  619. /*
  620. * Reset the count of consecutive warning alerts if we've got a non-empty
  621. * record that isn't an alert.
  622. */
  623. if (rr->type != SSL3_RT_ALERT && rr->length != 0)
  624. s->rlayer.alert_count = 0;
  625. /* we now have a packet which can be read and processed */
  626. if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
  627. * reset by ssl3_get_finished */
  628. && (rr->type != SSL3_RT_HANDSHAKE)) {
  629. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  630. SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  631. return -1;
  632. }
  633. /*
  634. * If the other end has shut down, throw anything we read away (even in
  635. * 'peek' mode)
  636. */
  637. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  638. s->rlayer.curr_rec++;
  639. s->rwstate = SSL_NOTHING;
  640. return 0;
  641. }
  642. if (type == rr->type
  643. || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  644. && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
  645. && !is_tls13)) {
  646. /*
  647. * SSL3_RT_APPLICATION_DATA or
  648. * SSL3_RT_HANDSHAKE or
  649. * SSL3_RT_CHANGE_CIPHER_SPEC
  650. */
  651. /*
  652. * make sure that we are not getting application data when we are
  653. * doing a handshake for the first time
  654. */
  655. if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
  656. && SSL_IS_FIRST_HANDSHAKE(s)) {
  657. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
  658. return -1;
  659. }
  660. if (type == SSL3_RT_HANDSHAKE
  661. && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  662. && s->rlayer.handshake_fragment_len > 0) {
  663. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  664. return -1;
  665. }
  666. if (recvd_type != NULL)
  667. *recvd_type = rr->type;
  668. if (len == 0) {
  669. /*
  670. * Skip a zero length record. This ensures multiple calls to
  671. * SSL_read() with a zero length buffer will eventually cause
  672. * SSL_pending() to report data as being available.
  673. */
  674. if (rr->length == 0 && !ssl_release_record(s, rr, 0))
  675. return -1;
  676. return 0;
  677. }
  678. totalbytes = 0;
  679. curr_rec = s->rlayer.curr_rec;
  680. do {
  681. if (len - totalbytes > rr->length)
  682. n = rr->length;
  683. else
  684. n = len - totalbytes;
  685. memcpy(buf, &(rr->data[rr->off]), n);
  686. buf += n;
  687. if (peek) {
  688. /* Mark any zero length record as consumed CVE-2016-6305 */
  689. if (rr->length == 0 && !ssl_release_record(s, rr, 0))
  690. return -1;
  691. } else {
  692. if (!ssl_release_record(s, rr, n))
  693. return -1;
  694. }
  695. if (rr->length == 0
  696. || (peek && n == rr->length)) {
  697. rr++;
  698. curr_rec++;
  699. }
  700. totalbytes += n;
  701. } while (type == SSL3_RT_APPLICATION_DATA
  702. && curr_rec < s->rlayer.num_recs
  703. && totalbytes < len);
  704. if (totalbytes == 0) {
  705. /* We must have read empty records. Get more data */
  706. goto start;
  707. }
  708. *readbytes = totalbytes;
  709. return 1;
  710. }
  711. /*
  712. * If we get here, then type != rr->type; if we have a handshake message,
  713. * then it was unexpected (Hello Request or Client Hello) or invalid (we
  714. * were actually expecting a CCS).
  715. */
  716. /*
  717. * Lets just double check that we've not got an SSLv2 record
  718. */
  719. if (rr->version == SSL2_VERSION) {
  720. /*
  721. * Should never happen. ssl3_get_record() should only give us an SSLv2
  722. * record back if this is the first packet and we are looking for an
  723. * initial ClientHello. Therefore |type| should always be equal to
  724. * |rr->type|. If not then something has gone horribly wrong
  725. */
  726. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  727. return -1;
  728. }
  729. if (ssl->method->version == TLS_ANY_VERSION
  730. && (s->server || rr->type != SSL3_RT_ALERT)) {
  731. /*
  732. * If we've got this far and still haven't decided on what version
  733. * we're using then this must be a client side alert we're dealing
  734. * with. We shouldn't be receiving anything other than a ClientHello
  735. * if we are a server.
  736. */
  737. s->version = rr->version;
  738. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
  739. return -1;
  740. }
  741. /*-
  742. * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  743. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  744. */
  745. if (rr->type == SSL3_RT_ALERT) {
  746. unsigned int alert_level, alert_descr;
  747. const unsigned char *alert_bytes = rr->data + rr->off;
  748. PACKET alert;
  749. if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
  750. || !PACKET_get_1(&alert, &alert_level)
  751. || !PACKET_get_1(&alert, &alert_descr)
  752. || PACKET_remaining(&alert) != 0) {
  753. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
  754. return -1;
  755. }
  756. if (s->msg_callback)
  757. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
  758. s->msg_callback_arg);
  759. if (s->info_callback != NULL)
  760. cb = s->info_callback;
  761. else if (ssl->ctx->info_callback != NULL)
  762. cb = ssl->ctx->info_callback;
  763. if (cb != NULL) {
  764. j = (alert_level << 8) | alert_descr;
  765. cb(ssl, SSL_CB_READ_ALERT, j);
  766. }
  767. if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
  768. || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
  769. s->s3.warn_alert = alert_descr;
  770. if (!ssl_release_record(s, rr, 0))
  771. return -1;
  772. s->rlayer.alert_count++;
  773. if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
  774. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  775. SSL_R_TOO_MANY_WARN_ALERTS);
  776. return -1;
  777. }
  778. }
  779. /*
  780. * Apart from close_notify the only other warning alert in TLSv1.3
  781. * is user_cancelled - which we just ignore.
  782. */
  783. if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
  784. goto start;
  785. } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
  786. && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
  787. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  788. return 0;
  789. } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
  790. s->rwstate = SSL_NOTHING;
  791. s->s3.fatal_alert = alert_descr;
  792. SSLfatal_data(s, SSL_AD_NO_ALERT,
  793. SSL_AD_REASON_OFFSET + alert_descr,
  794. "SSL alert number %d", alert_descr);
  795. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  796. if (!ssl_release_record(s, rr, 0))
  797. return -1;
  798. SSL_CTX_remove_session(s->session_ctx, s->session);
  799. return 0;
  800. } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  801. /*
  802. * This is a warning but we receive it if we requested
  803. * renegotiation and the peer denied it. Terminate with a fatal
  804. * alert because if application tried to renegotiate it
  805. * presumably had a good reason and expects it to succeed. In
  806. * future we might have a renegotiation where we don't care if
  807. * the peer refused it where we carry on.
  808. */
  809. SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
  810. return -1;
  811. } else if (alert_level == SSL3_AL_WARNING) {
  812. /* We ignore any other warning alert in TLSv1.2 and below */
  813. goto start;
  814. }
  815. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
  816. return -1;
  817. }
  818. if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
  819. if (rr->type == SSL3_RT_HANDSHAKE) {
  820. BIO *rbio;
  821. /*
  822. * We ignore any handshake messages sent to us unless they are
  823. * TLSv1.3 in which case we want to process them. For all other
  824. * handshake messages we can't do anything reasonable with them
  825. * because we are unable to write any response due to having already
  826. * sent close_notify.
  827. */
  828. if (!SSL_CONNECTION_IS_TLS13(s)) {
  829. if (!ssl_release_record(s, rr, 0))
  830. return -1;
  831. if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
  832. goto start;
  833. s->rwstate = SSL_READING;
  834. rbio = SSL_get_rbio(ssl);
  835. BIO_clear_retry_flags(rbio);
  836. BIO_set_retry_read(rbio);
  837. return -1;
  838. }
  839. } else {
  840. /*
  841. * The peer is continuing to send application data, but we have
  842. * already sent close_notify. If this was expected we should have
  843. * been called via SSL_read() and this would have been handled
  844. * above.
  845. * No alert sent because we already sent close_notify
  846. */
  847. if (!ssl_release_record(s, rr, 0))
  848. return -1;
  849. SSLfatal(s, SSL_AD_NO_ALERT,
  850. SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
  851. return -1;
  852. }
  853. }
  854. /*
  855. * For handshake data we have 'fragment' storage, so fill that so that we
  856. * can process the header at a fixed place. This is done after the
  857. * "SHUTDOWN" code above to avoid filling the fragment storage with data
  858. * that we're just going to discard.
  859. */
  860. if (rr->type == SSL3_RT_HANDSHAKE) {
  861. size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
  862. unsigned char *dest = s->rlayer.handshake_fragment;
  863. size_t *dest_len = &s->rlayer.handshake_fragment_len;
  864. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  865. if (rr->length < n)
  866. n = rr->length; /* available bytes */
  867. /* now move 'n' bytes: */
  868. if (n > 0) {
  869. memcpy(dest + *dest_len, rr->data + rr->off, n);
  870. *dest_len += n;
  871. }
  872. /*
  873. * We release the number of bytes consumed, or the whole record if it
  874. * is zero length
  875. */
  876. if ((n > 0 || rr->length == 0) && !ssl_release_record(s, rr, n))
  877. return -1;
  878. if (*dest_len < dest_maxlen)
  879. goto start; /* fragment was too small */
  880. }
  881. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  882. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  883. return -1;
  884. }
  885. /*
  886. * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
  887. * protocol violation)
  888. */
  889. if ((s->rlayer.handshake_fragment_len >= 4)
  890. && !ossl_statem_get_in_handshake(s)) {
  891. int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
  892. /* We found handshake data, so we're going back into init */
  893. ossl_statem_set_in_init(s, 1);
  894. i = s->handshake_func(ssl);
  895. /* SSLfatal() already called if appropriate */
  896. if (i < 0)
  897. return i;
  898. if (i == 0) {
  899. return -1;
  900. }
  901. /*
  902. * If we were actually trying to read early data and we found a
  903. * handshake message, then we don't want to continue to try and read
  904. * the application data any more. It won't be "early" now.
  905. */
  906. if (ined)
  907. return -1;
  908. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  909. if (!RECORD_LAYER_read_pending(&s->rlayer)) {
  910. BIO *bio;
  911. /*
  912. * In the case where we try to read application data, but we
  913. * trigger an SSL handshake, we return -1 with the retry
  914. * option set. Otherwise renegotiation may cause nasty
  915. * problems in the blocking world
  916. */
  917. s->rwstate = SSL_READING;
  918. bio = SSL_get_rbio(ssl);
  919. BIO_clear_retry_flags(bio);
  920. BIO_set_retry_read(bio);
  921. return -1;
  922. }
  923. }
  924. goto start;
  925. }
  926. switch (rr->type) {
  927. default:
  928. /*
  929. * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
  930. * TLS 1.2 says you MUST send an unexpected message alert. We use the
  931. * TLS 1.2 behaviour for all protocol versions to prevent issues where
  932. * no progress is being made and the peer continually sends unrecognised
  933. * record types, using up resources processing them.
  934. */
  935. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  936. return -1;
  937. case SSL3_RT_CHANGE_CIPHER_SPEC:
  938. case SSL3_RT_ALERT:
  939. case SSL3_RT_HANDSHAKE:
  940. /*
  941. * we already handled all of these, with the possible exception of
  942. * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
  943. * that should not happen when type != rr->type
  944. */
  945. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
  946. return -1;
  947. case SSL3_RT_APPLICATION_DATA:
  948. /*
  949. * At this point, we were expecting handshake data, but have
  950. * application data. If the library was running inside ssl3_read()
  951. * (i.e. in_read_app_data is set) and it makes sense to read
  952. * application data at this point (session renegotiation not yet
  953. * started), we will indulge it.
  954. */
  955. if (ossl_statem_app_data_allowed(s)) {
  956. s->s3.in_read_app_data = 2;
  957. return -1;
  958. } else if (ossl_statem_skip_early_data(s)) {
  959. /*
  960. * This can happen after a client sends a CH followed by early_data,
  961. * but the server responds with a HelloRetryRequest. The server
  962. * reads the next record from the client expecting to find a
  963. * plaintext ClientHello but gets a record which appears to be
  964. * application data. The trial decrypt "works" because null
  965. * decryption was applied. We just skip it and move on to the next
  966. * record.
  967. */
  968. if (!ossl_early_data_count_ok(s, rr->length,
  969. EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
  970. /* SSLfatal() already called */
  971. return -1;
  972. }
  973. if (!ssl_release_record(s, rr, 0))
  974. return -1;
  975. goto start;
  976. } else {
  977. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  978. return -1;
  979. }
  980. }
  981. }
  982. /*
  983. * Returns true if the current rrec was sent in SSLv2 backwards compatible
  984. * format and false otherwise.
  985. */
  986. int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
  987. {
  988. if (SSL_CONNECTION_IS_DTLS(rl->s))
  989. return 0;
  990. return rl->tlsrecs[0].version == SSL2_VERSION;
  991. }
  992. static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
  993. static void rlayer_msg_callback_wrapper(int write_p, int version,
  994. int content_type, const void *buf,
  995. size_t len, void *cbarg)
  996. {
  997. SSL_CONNECTION *s = cbarg;
  998. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  999. if (s->msg_callback != NULL)
  1000. s->msg_callback(write_p, version, content_type, buf, len, ssl,
  1001. s->msg_callback_arg);
  1002. }
  1003. static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
  1004. static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
  1005. void *other)
  1006. {
  1007. SSL_CONNECTION *s = cbarg;
  1008. return ssl_security(s, op, bits, nid, other);
  1009. }
  1010. static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
  1011. static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
  1012. {
  1013. SSL_CONNECTION *s = cbarg;
  1014. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1015. return s->rlayer.record_padding_cb(ssl, type, len,
  1016. s->rlayer.record_padding_arg);
  1017. }
  1018. static const OSSL_DISPATCH rlayer_dispatch[] = {
  1019. { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
  1020. { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
  1021. { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
  1022. { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
  1023. OSSL_DISPATCH_END
  1024. };
  1025. void ossl_ssl_set_custom_record_layer(SSL_CONNECTION *s,
  1026. const OSSL_RECORD_METHOD *meth,
  1027. void *rlarg)
  1028. {
  1029. s->rlayer.custom_rlmethod = meth;
  1030. s->rlayer.rlarg = rlarg;
  1031. }
  1032. static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
  1033. int direction,
  1034. int level)
  1035. {
  1036. if (s->rlayer.custom_rlmethod != NULL)
  1037. return s->rlayer.custom_rlmethod;
  1038. if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
  1039. if (SSL_CONNECTION_IS_DTLS(s))
  1040. return &ossl_dtls_record_method;
  1041. return &ossl_tls_record_method;
  1042. }
  1043. #ifndef OPENSSL_NO_KTLS
  1044. /* KTLS does not support renegotiation */
  1045. if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
  1046. && (s->options & SSL_OP_ENABLE_KTLS) != 0
  1047. && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
  1048. return &ossl_ktls_record_method;
  1049. #endif
  1050. /* Default to the current OSSL_RECORD_METHOD */
  1051. return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
  1052. : s->rlayer.wrlmethod;
  1053. }
  1054. static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
  1055. {
  1056. const OSSL_RECORD_METHOD *thismethod;
  1057. OSSL_RECORD_LAYER *thisrl;
  1058. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1059. thismethod = s->rlayer.rrlmethod;
  1060. thisrl = s->rlayer.rrl;
  1061. } else {
  1062. thismethod = s->rlayer.wrlmethod;
  1063. thisrl = s->rlayer.wrl;
  1064. }
  1065. #ifndef OPENSSL_NO_KTLS
  1066. {
  1067. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1068. if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
  1069. /* KTLS does not support renegotiation so disallow it */
  1070. SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
  1071. }
  1072. }
  1073. #endif
  1074. if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
  1075. thismethod->set_first_handshake(thisrl, 1);
  1076. if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
  1077. thismethod->set_max_pipelines(thisrl, s->max_pipelines);
  1078. return 1;
  1079. }
  1080. int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
  1081. int direction, int level,
  1082. unsigned char *secret, size_t secretlen,
  1083. unsigned char *key, size_t keylen,
  1084. unsigned char *iv, size_t ivlen,
  1085. unsigned char *mackey, size_t mackeylen,
  1086. const EVP_CIPHER *ciph, size_t taglen,
  1087. int mactype, const EVP_MD *md,
  1088. const SSL_COMP *comp, const EVP_MD *kdfdigest)
  1089. {
  1090. OSSL_PARAM options[5], *opts = options;
  1091. OSSL_PARAM settings[6], *set = settings;
  1092. const OSSL_RECORD_METHOD **thismethod;
  1093. OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
  1094. BIO *thisbio;
  1095. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  1096. const OSSL_RECORD_METHOD *meth;
  1097. int use_etm, stream_mac = 0, tlstree = 0;
  1098. unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
  1099. ? ssl_get_max_send_fragment(s)
  1100. : SSL3_RT_MAX_PLAIN_LENGTH;
  1101. int use_early_data = 0;
  1102. uint32_t max_early_data;
  1103. COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
  1104. meth = ssl_select_next_record_layer(s, direction, level);
  1105. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1106. thismethod = &s->rlayer.rrlmethod;
  1107. thisrl = &s->rlayer.rrl;
  1108. thisbio = s->rbio;
  1109. } else {
  1110. thismethod = &s->rlayer.wrlmethod;
  1111. thisrl = &s->rlayer.wrl;
  1112. thisbio = s->wbio;
  1113. }
  1114. if (meth == NULL)
  1115. meth = *thismethod;
  1116. if (!ossl_assert(meth != NULL)) {
  1117. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  1118. return 0;
  1119. }
  1120. /* Parameters that *may* be supported by a record layer if passed */
  1121. *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
  1122. &s->options);
  1123. *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
  1124. &s->mode);
  1125. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1126. *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
  1127. &s->rlayer.default_read_buf_len);
  1128. *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
  1129. &s->rlayer.read_ahead);
  1130. } else {
  1131. *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
  1132. &s->rlayer.block_padding);
  1133. }
  1134. *opts = OSSL_PARAM_construct_end();
  1135. /* Parameters that *must* be supported by a record layer if passed */
  1136. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1137. use_etm = SSL_READ_ETM(s) ? 1 : 0;
  1138. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
  1139. stream_mac = 1;
  1140. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
  1141. tlstree = 1;
  1142. } else {
  1143. use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
  1144. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
  1145. stream_mac = 1;
  1146. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
  1147. tlstree = 1;
  1148. }
  1149. if (use_etm)
  1150. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
  1151. &use_etm);
  1152. if (stream_mac)
  1153. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
  1154. &stream_mac);
  1155. if (tlstree)
  1156. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
  1157. &tlstree);
  1158. /*
  1159. * We only need to do this for the read side. The write side should already
  1160. * have the correct value due to the ssl_get_max_send_fragment() call above
  1161. */
  1162. if (direction == OSSL_RECORD_DIRECTION_READ
  1163. && s->session != NULL
  1164. && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
  1165. maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
  1166. if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
  1167. *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
  1168. &maxfrag);
  1169. /*
  1170. * The record layer must check the amount of early data sent or received
  1171. * using the early keys. A server also needs to worry about rejected early
  1172. * data that might arrive when the handshake keys are in force.
  1173. */
  1174. if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
  1175. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
  1176. || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
  1177. } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
  1178. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
  1179. }
  1180. if (use_early_data) {
  1181. max_early_data = ossl_get_max_early_data(s);
  1182. if (max_early_data != 0)
  1183. *set++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
  1184. &max_early_data);
  1185. }
  1186. *set = OSSL_PARAM_construct_end();
  1187. for (;;) {
  1188. int rlret;
  1189. BIO *prev = NULL;
  1190. BIO *next = NULL;
  1191. unsigned int epoch = 0;
  1192. OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
  1193. size_t i, j;
  1194. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1195. prev = s->rlayer.rrlnext;
  1196. if (SSL_CONNECTION_IS_DTLS(s)
  1197. && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1198. epoch = dtls1_get_epoch(s, SSL3_CC_READ); /* new epoch */
  1199. #ifndef OPENSSL_NO_DGRAM
  1200. if (SSL_CONNECTION_IS_DTLS(s))
  1201. next = BIO_new(BIO_s_dgram_mem());
  1202. else
  1203. #endif
  1204. next = BIO_new(BIO_s_mem());
  1205. if (next == NULL) {
  1206. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1207. return 0;
  1208. }
  1209. s->rlayer.rrlnext = next;
  1210. } else {
  1211. if (SSL_CONNECTION_IS_DTLS(s)
  1212. && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1213. epoch = dtls1_get_epoch(s, SSL3_CC_WRITE); /* new epoch */
  1214. }
  1215. /*
  1216. * Create a copy of the dispatch array, missing out wrappers for
  1217. * callbacks that we don't need.
  1218. */
  1219. for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
  1220. switch (rlayer_dispatch[i].function_id) {
  1221. case OSSL_FUNC_RLAYER_MSG_CALLBACK:
  1222. if (s->msg_callback == NULL)
  1223. continue;
  1224. break;
  1225. case OSSL_FUNC_RLAYER_PADDING:
  1226. if (s->rlayer.record_padding_cb == NULL)
  1227. continue;
  1228. break;
  1229. default:
  1230. break;
  1231. }
  1232. rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
  1233. }
  1234. rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
  1235. s->server, direction, level, epoch,
  1236. secret, secretlen, key, keylen, iv,
  1237. ivlen, mackey, mackeylen, ciph, taglen,
  1238. mactype, md, compm, kdfdigest, prev,
  1239. thisbio, next, NULL, NULL, settings,
  1240. options, rlayer_dispatch_tmp, s,
  1241. s->rlayer.rlarg, &newrl);
  1242. BIO_free(prev);
  1243. switch (rlret) {
  1244. case OSSL_RECORD_RETURN_FATAL:
  1245. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
  1246. return 0;
  1247. case OSSL_RECORD_RETURN_NON_FATAL_ERR:
  1248. if (*thismethod != meth && *thismethod != NULL) {
  1249. /*
  1250. * We tried a new record layer method, but it didn't work out,
  1251. * so we fallback to the original method and try again
  1252. */
  1253. meth = *thismethod;
  1254. continue;
  1255. }
  1256. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
  1257. return 0;
  1258. case OSSL_RECORD_RETURN_SUCCESS:
  1259. break;
  1260. default:
  1261. /* Should not happen */
  1262. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1263. return 0;
  1264. }
  1265. break;
  1266. }
  1267. /*
  1268. * Free the old record layer if we have one except in the case of DTLS when
  1269. * writing and there are still buffered sent messages in our queue. In that
  1270. * case the record layer is still referenced by those buffered messages for
  1271. * potential retransmit. Only when those buffered messages get freed do we
  1272. * free the record layer object (see dtls1_hm_fragment_free)
  1273. */
  1274. if (!SSL_CONNECTION_IS_DTLS(s)
  1275. || direction == OSSL_RECORD_DIRECTION_READ
  1276. || pqueue_peek(s->d1->sent_messages) == NULL) {
  1277. if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
  1278. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1279. return 0;
  1280. }
  1281. }
  1282. *thisrl = newrl;
  1283. *thismethod = meth;
  1284. return ssl_post_record_layer_select(s, direction);
  1285. }
  1286. int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
  1287. {
  1288. if (!ossl_assert(s->rlayer.rrlmethod != NULL)
  1289. || !ossl_assert(s->rlayer.wrlmethod != NULL))
  1290. return 0;
  1291. s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
  1292. s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);
  1293. return 1;
  1294. }