rec_layer_s3.c 50 KB

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