rec_layer_s3.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  1. /*
  2. * Copyright 1995-2022 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 "../ssl_local.h"
  13. #include <openssl/evp.h>
  14. #include <openssl/buffer.h>
  15. #include <openssl/rand.h>
  16. #include <openssl/core_names.h>
  17. #include "record_local.h"
  18. #include "internal/packet.h"
  19. #if defined(OPENSSL_SMALL_FOOTPRINT) || \
  20. !( defined(AES_ASM) && ( \
  21. defined(__x86_64) || defined(__x86_64__) || \
  22. defined(_M_AMD64) || defined(_M_X64) ) \
  23. )
  24. # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
  25. # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
  26. #endif
  27. void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
  28. {
  29. rl->s = s;
  30. }
  31. void RECORD_LAYER_clear(RECORD_LAYER *rl)
  32. {
  33. rl->wnum = 0;
  34. memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
  35. rl->handshake_fragment_len = 0;
  36. rl->wpend_tot = 0;
  37. rl->wpend_type = 0;
  38. rl->wpend_ret = 0;
  39. rl->wpend_buf = NULL;
  40. ssl3_release_write_buffer(rl->s);
  41. RECORD_LAYER_reset_write_sequence(rl);
  42. if (rl->rrlmethod != NULL)
  43. rl->rrlmethod->free(rl->rrl); /* Ignore return value */
  44. BIO_free(rl->rrlnext);
  45. rl->rrlmethod = NULL;
  46. rl->rrlnext = NULL;
  47. if (rl->d)
  48. DTLS_RECORD_LAYER_clear(rl);
  49. }
  50. void RECORD_LAYER_release(RECORD_LAYER *rl)
  51. {
  52. if (rl->numwpipes > 0)
  53. ssl3_release_write_buffer(rl->s);
  54. }
  55. /* Checks if we have unprocessed read ahead data pending */
  56. int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
  57. {
  58. return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
  59. }
  60. /* Checks if we have decrypted unread record data pending */
  61. int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
  62. {
  63. return (rl->curr_rec < rl->num_recs)
  64. || rl->rrlmethod->processed_read_pending(rl->rrl);
  65. }
  66. int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
  67. {
  68. return (rl->numwpipes > 0)
  69. && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
  70. }
  71. void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
  72. {
  73. memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
  74. }
  75. size_t ssl3_pending(const SSL *s)
  76. {
  77. size_t i, num = 0;
  78. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  79. if (sc == NULL)
  80. return 0;
  81. if (SSL_CONNECTION_IS_DTLS(sc)) {
  82. TLS_RECORD *rdata;
  83. pitem *item, *iter;
  84. iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
  85. while ((item = pqueue_next(&iter)) != NULL) {
  86. rdata = item->data;
  87. num += rdata->length;
  88. }
  89. }
  90. for (i = 0; i < sc->rlayer.num_recs; i++) {
  91. if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
  92. return num;
  93. num += sc->rlayer.tlsrecs[i].length;
  94. }
  95. num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
  96. return num;
  97. }
  98. void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
  99. {
  100. ctx->default_read_buf_len = len;
  101. }
  102. void SSL_set_default_read_buffer_len(SSL *s, size_t len)
  103. {
  104. SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
  105. if (sc == NULL)
  106. return;
  107. sc->rlayer.default_read_buf_len = len;
  108. }
  109. const char *SSL_rstate_string_long(const SSL *s)
  110. {
  111. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  112. const char *lng;
  113. if (sc == NULL)
  114. return NULL;
  115. if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
  116. return "unknown";
  117. sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
  118. return lng;
  119. }
  120. const char *SSL_rstate_string(const SSL *s)
  121. {
  122. const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
  123. const char *shrt;
  124. if (sc == NULL)
  125. return NULL;
  126. if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
  127. return "unknown";
  128. sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
  129. return shrt;
  130. }
  131. /*
  132. * Call this to write data in records of type 'type' It will return <= 0 if
  133. * not all data has been sent or non-blocking IO.
  134. */
  135. int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
  136. size_t *written)
  137. {
  138. const unsigned char *buf = buf_;
  139. size_t tot;
  140. size_t n, max_send_fragment, split_send_fragment, maxpipes;
  141. #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
  142. size_t nw;
  143. #endif
  144. SSL3_BUFFER *wb;
  145. int i;
  146. size_t tmpwrit;
  147. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  148. if (s == NULL)
  149. return -1;
  150. wb = &s->rlayer.wbuf[0];
  151. s->rwstate = SSL_NOTHING;
  152. tot = s->rlayer.wnum;
  153. /*
  154. * ensure that if we end up with a smaller value of data to write out
  155. * than the original len from a write which didn't complete for
  156. * non-blocking I/O and also somehow ended up avoiding the check for
  157. * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
  158. * possible to end up with (len-tot) as a large number that will then
  159. * promptly send beyond the end of the users buffer ... so we trap and
  160. * report the error in a way the user will notice
  161. */
  162. if ((len < s->rlayer.wnum)
  163. || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
  164. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
  165. return -1;
  166. }
  167. if (s->early_data_state == SSL_EARLY_DATA_WRITING
  168. && !ossl_early_data_count_ok(s, len, 0, 1)) {
  169. /* SSLfatal() already called */
  170. return -1;
  171. }
  172. s->rlayer.wnum = 0;
  173. /*
  174. * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
  175. * into init unless we have writes pending - in which case we should finish
  176. * doing that first.
  177. */
  178. if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
  179. || s->ext.extra_tickets_expected > 0))
  180. ossl_statem_set_in_init(s, 1);
  181. /*
  182. * When writing early data on the server side we could be "in_init" in
  183. * between receiving the EoED and the CF - but we don't want to handle those
  184. * messages yet.
  185. */
  186. if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
  187. && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
  188. i = s->handshake_func(ssl);
  189. /* SSLfatal() already called */
  190. if (i < 0)
  191. return i;
  192. if (i == 0) {
  193. return -1;
  194. }
  195. }
  196. /*
  197. * first check if there is a SSL3_BUFFER still being written out. This
  198. * will happen with non blocking IO
  199. */
  200. if (wb->left != 0) {
  201. /* SSLfatal() already called if appropriate */
  202. i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
  203. &tmpwrit);
  204. if (i <= 0) {
  205. /* XXX should we ssl3_release_write_buffer if i<0? */
  206. s->rlayer.wnum = tot;
  207. return i;
  208. }
  209. tot += tmpwrit; /* this might be last fragment */
  210. }
  211. #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
  212. /*
  213. * Depending on platform multi-block can deliver several *times*
  214. * better performance. Downside is that it has to allocate
  215. * jumbo buffer to accommodate up to 8 records, but the
  216. * compromise is considered worthy.
  217. */
  218. if (type == SSL3_RT_APPLICATION_DATA
  219. && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
  220. && s->compress == NULL
  221. && s->msg_callback == NULL
  222. && !SSL_WRITE_ETM(s)
  223. && SSL_USE_EXPLICIT_IV(s)
  224. && !BIO_get_ktls_send(s->wbio)
  225. && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
  226. & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
  227. unsigned char aad[13];
  228. EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
  229. size_t packlen;
  230. int packleni;
  231. /* minimize address aliasing conflicts */
  232. if ((max_send_fragment & 0xfff) == 0)
  233. max_send_fragment -= 512;
  234. if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
  235. ssl3_release_write_buffer(s);
  236. packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
  237. EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
  238. (int)max_send_fragment, NULL);
  239. if (len >= 8 * max_send_fragment)
  240. packlen *= 8;
  241. else
  242. packlen *= 4;
  243. if (!ssl3_setup_write_buffer(s, 1, packlen)) {
  244. /* SSLfatal() already called */
  245. return -1;
  246. }
  247. } else if (tot == len) { /* done? */
  248. /* free jumbo buffer */
  249. ssl3_release_write_buffer(s);
  250. *written = tot;
  251. return 1;
  252. }
  253. n = (len - tot);
  254. for (;;) {
  255. if (n < 4 * max_send_fragment) {
  256. /* free jumbo buffer */
  257. ssl3_release_write_buffer(s);
  258. break;
  259. }
  260. if (s->s3.alert_dispatch) {
  261. i = ssl->method->ssl_dispatch_alert(ssl);
  262. if (i <= 0) {
  263. /* SSLfatal() already called if appropriate */
  264. s->rlayer.wnum = tot;
  265. return i;
  266. }
  267. }
  268. if (n >= 8 * max_send_fragment)
  269. nw = max_send_fragment * (mb_param.interleave = 8);
  270. else
  271. nw = max_send_fragment * (mb_param.interleave = 4);
  272. memcpy(aad, s->rlayer.write_sequence, 8);
  273. aad[8] = type;
  274. aad[9] = (unsigned char)(s->version >> 8);
  275. aad[10] = (unsigned char)(s->version);
  276. aad[11] = 0;
  277. aad[12] = 0;
  278. mb_param.out = NULL;
  279. mb_param.inp = aad;
  280. mb_param.len = nw;
  281. packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
  282. EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
  283. sizeof(mb_param), &mb_param);
  284. packlen = (size_t)packleni;
  285. if (packleni <= 0 || packlen > wb->len) { /* never happens */
  286. /* free jumbo buffer */
  287. ssl3_release_write_buffer(s);
  288. break;
  289. }
  290. mb_param.out = wb->buf;
  291. mb_param.inp = &buf[tot];
  292. mb_param.len = nw;
  293. if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
  294. EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
  295. sizeof(mb_param), &mb_param) <= 0)
  296. return -1;
  297. s->rlayer.write_sequence[7] += mb_param.interleave;
  298. if (s->rlayer.write_sequence[7] < mb_param.interleave) {
  299. int j = 6;
  300. while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
  301. }
  302. wb->offset = 0;
  303. wb->left = packlen;
  304. s->rlayer.wpend_tot = nw;
  305. s->rlayer.wpend_buf = &buf[tot];
  306. s->rlayer.wpend_type = type;
  307. s->rlayer.wpend_ret = nw;
  308. i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
  309. if (i <= 0) {
  310. /* SSLfatal() already called if appropriate */
  311. if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
  312. /* free jumbo buffer */
  313. ssl3_release_write_buffer(s);
  314. }
  315. s->rlayer.wnum = tot;
  316. return i;
  317. }
  318. if (tmpwrit == n) {
  319. /* free jumbo buffer */
  320. ssl3_release_write_buffer(s);
  321. *written = tot + tmpwrit;
  322. return 1;
  323. }
  324. n -= tmpwrit;
  325. tot += tmpwrit;
  326. }
  327. } else
  328. #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
  329. if (tot == len) { /* done? */
  330. if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
  331. ssl3_release_write_buffer(s);
  332. *written = tot;
  333. return 1;
  334. }
  335. n = (len - tot);
  336. max_send_fragment = ssl_get_max_send_fragment(s);
  337. split_send_fragment = ssl_get_split_send_fragment(s);
  338. /*
  339. * If max_pipelines is 0 then this means "undefined" and we default to
  340. * 1 pipeline. Similarly if the cipher does not support pipelined
  341. * processing then we also only use 1 pipeline, or if we're not using
  342. * explicit IVs
  343. */
  344. maxpipes = s->max_pipelines;
  345. if (maxpipes > SSL_MAX_PIPELINES) {
  346. /*
  347. * We should have prevented this when we set max_pipelines so we
  348. * shouldn't get here
  349. */
  350. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  351. return -1;
  352. }
  353. if (maxpipes == 0
  354. || s->enc_write_ctx == NULL
  355. || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
  356. & EVP_CIPH_FLAG_PIPELINE) == 0
  357. || !SSL_USE_EXPLICIT_IV(s))
  358. maxpipes = 1;
  359. if (max_send_fragment == 0
  360. || split_send_fragment == 0
  361. || split_send_fragment > max_send_fragment) {
  362. /*
  363. * We should have prevented this when we set/get the split and max send
  364. * fragments so we shouldn't get here
  365. */
  366. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  367. return -1;
  368. }
  369. for (;;) {
  370. size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
  371. size_t numpipes, j;
  372. if (n == 0)
  373. numpipes = 1;
  374. else
  375. numpipes = ((n - 1) / split_send_fragment) + 1;
  376. if (numpipes > maxpipes)
  377. numpipes = maxpipes;
  378. if (n / numpipes >= max_send_fragment) {
  379. /*
  380. * We have enough data to completely fill all available
  381. * pipelines
  382. */
  383. for (j = 0; j < numpipes; j++) {
  384. pipelens[j] = max_send_fragment;
  385. }
  386. } else {
  387. /* We can partially fill all available pipelines */
  388. tmppipelen = n / numpipes;
  389. remain = n % numpipes;
  390. for (j = 0; j < numpipes; j++) {
  391. pipelens[j] = tmppipelen;
  392. if (j < remain)
  393. pipelens[j]++;
  394. }
  395. }
  396. i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
  397. &tmpwrit);
  398. if (i <= 0) {
  399. /* SSLfatal() already called if appropriate */
  400. /* XXX should we ssl3_release_write_buffer if i<0? */
  401. s->rlayer.wnum = tot;
  402. return i;
  403. }
  404. if (tmpwrit == n ||
  405. (type == SSL3_RT_APPLICATION_DATA &&
  406. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  407. /*
  408. * next chunk of data should get another prepended empty fragment
  409. * in ciphersuites with known-IV weakness:
  410. */
  411. s->s3.empty_fragment_done = 0;
  412. if (tmpwrit == n
  413. && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
  414. && !SSL_CONNECTION_IS_DTLS(s))
  415. ssl3_release_write_buffer(s);
  416. *written = tot + tmpwrit;
  417. return 1;
  418. }
  419. n -= tmpwrit;
  420. tot += tmpwrit;
  421. }
  422. }
  423. int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
  424. size_t *pipelens, size_t numpipes,
  425. int create_empty_fragment, size_t *written)
  426. {
  427. WPACKET pkt[SSL_MAX_PIPELINES];
  428. SSL3_RECORD wr[SSL_MAX_PIPELINES];
  429. WPACKET *thispkt;
  430. SSL3_RECORD *thiswr;
  431. unsigned char *recordstart;
  432. int i, mac_size, clear = 0;
  433. size_t prefix_len = 0;
  434. int eivlen = 0;
  435. size_t align = 0;
  436. SSL3_BUFFER *wb;
  437. SSL_SESSION *sess;
  438. size_t totlen = 0, len, wpinited = 0;
  439. size_t j;
  440. int using_ktls;
  441. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  442. for (j = 0; j < numpipes; j++)
  443. totlen += pipelens[j];
  444. /*
  445. * first check if there is a SSL3_BUFFER still being written out. This
  446. * will happen with non blocking IO
  447. */
  448. if (RECORD_LAYER_write_pending(&s->rlayer)) {
  449. /* Calls SSLfatal() as required */
  450. return ssl3_write_pending(s, type, buf, totlen, written);
  451. }
  452. /* If we have an alert to send, lets send it */
  453. if (s->s3.alert_dispatch) {
  454. i = ssl->method->ssl_dispatch_alert(ssl);
  455. if (i <= 0) {
  456. /* SSLfatal() already called if appropriate */
  457. return i;
  458. }
  459. /* if it went, fall through and send more stuff */
  460. }
  461. if (s->rlayer.numwpipes < numpipes) {
  462. if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
  463. /* SSLfatal() already called */
  464. return -1;
  465. }
  466. }
  467. if (totlen == 0 && !create_empty_fragment)
  468. return 0;
  469. sess = s->session;
  470. if ((sess == NULL)
  471. || (s->enc_write_ctx == NULL)
  472. || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
  473. clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
  474. mac_size = 0;
  475. } else {
  476. mac_size = EVP_MD_CTX_get_size(s->write_hash);
  477. if (mac_size < 0) {
  478. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  479. goto err;
  480. }
  481. }
  482. /*
  483. * 'create_empty_fragment' is true only when this function calls itself
  484. */
  485. if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
  486. /*
  487. * countermeasure against known-IV weakness in CBC ciphersuites (see
  488. * http://www.openssl.org/~bodo/tls-cbc.txt)
  489. */
  490. if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  491. /*
  492. * recursive function call with 'create_empty_fragment' set; this
  493. * prepares and buffers the data for an empty fragment (these
  494. * 'prefix_len' bytes are sent out later together with the actual
  495. * payload)
  496. */
  497. size_t tmppipelen = 0;
  498. int ret;
  499. ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
  500. if (ret <= 0) {
  501. /* SSLfatal() already called if appropriate */
  502. goto err;
  503. }
  504. if (prefix_len >
  505. (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
  506. /* insufficient space */
  507. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  508. goto err;
  509. }
  510. }
  511. s->s3.empty_fragment_done = 1;
  512. }
  513. using_ktls = BIO_get_ktls_send(s->wbio);
  514. if (using_ktls) {
  515. /*
  516. * ktls doesn't modify the buffer, but to avoid a warning we need to
  517. * discard the const qualifier.
  518. * This doesn't leak memory because the buffers have been released when
  519. * switching to ktls.
  520. */
  521. SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
  522. SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
  523. SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
  524. goto wpacket_init_complete;
  525. }
  526. if (create_empty_fragment) {
  527. wb = &s->rlayer.wbuf[0];
  528. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  529. /*
  530. * extra fragment would be couple of cipher blocks, which would be
  531. * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
  532. * payload, then we can just pretend we simply have two headers.
  533. */
  534. align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
  535. align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
  536. #endif
  537. SSL3_BUFFER_set_offset(wb, align);
  538. if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
  539. SSL3_BUFFER_get_len(wb), 0)
  540. || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
  541. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  542. goto err;
  543. }
  544. wpinited = 1;
  545. } else if (prefix_len) {
  546. wb = &s->rlayer.wbuf[0];
  547. if (!WPACKET_init_static_len(&pkt[0],
  548. SSL3_BUFFER_get_buf(wb),
  549. SSL3_BUFFER_get_len(wb), 0)
  550. || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
  551. + prefix_len, NULL)) {
  552. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  553. goto err;
  554. }
  555. wpinited = 1;
  556. } else {
  557. for (j = 0; j < numpipes; j++) {
  558. thispkt = &pkt[j];
  559. wb = &s->rlayer.wbuf[j];
  560. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
  561. align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
  562. align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
  563. #endif
  564. SSL3_BUFFER_set_offset(wb, align);
  565. if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
  566. SSL3_BUFFER_get_len(wb), 0)
  567. || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
  568. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  569. goto err;
  570. }
  571. wpinited++;
  572. }
  573. }
  574. /* Explicit IV length, block ciphers appropriate version flag */
  575. if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
  576. && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
  577. int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
  578. if (mode == EVP_CIPH_CBC_MODE) {
  579. eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
  580. if (eivlen < 0) {
  581. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
  582. goto err;
  583. }
  584. if (eivlen <= 1)
  585. eivlen = 0;
  586. } else if (mode == EVP_CIPH_GCM_MODE) {
  587. /* Need explicit part of IV for GCM mode */
  588. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  589. } else if (mode == EVP_CIPH_CCM_MODE) {
  590. eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
  591. }
  592. }
  593. wpacket_init_complete:
  594. totlen = 0;
  595. /* Clear our SSL3_RECORD structures */
  596. memset(wr, 0, sizeof(wr));
  597. for (j = 0; j < numpipes; j++) {
  598. unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
  599. : s->version;
  600. unsigned char *compressdata = NULL;
  601. size_t maxcomplen;
  602. unsigned int rectype;
  603. thispkt = &pkt[j];
  604. thiswr = &wr[j];
  605. /*
  606. * In TLSv1.3, once encrypting, we always use application data for the
  607. * record type
  608. */
  609. if (SSL_CONNECTION_TREAT_AS_TLS13(s)
  610. && s->enc_write_ctx != NULL
  611. && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
  612. || type != SSL3_RT_ALERT))
  613. rectype = SSL3_RT_APPLICATION_DATA;
  614. else
  615. rectype = type;
  616. SSL3_RECORD_set_type(thiswr, rectype);
  617. /*
  618. * Some servers hang if initial client hello is larger than 256 bytes
  619. * and record version number > TLS 1.0
  620. */
  621. if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
  622. && !s->renegotiate
  623. && TLS1_get_version(ssl) > TLS1_VERSION
  624. && s->hello_retry_request == SSL_HRR_NONE)
  625. version = TLS1_VERSION;
  626. SSL3_RECORD_set_rec_version(thiswr, version);
  627. maxcomplen = pipelens[j];
  628. if (s->compress != NULL)
  629. maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
  630. /*
  631. * When using offload kernel will write the header.
  632. * Otherwise write the header now
  633. */
  634. if (!using_ktls
  635. && (!WPACKET_put_bytes_u8(thispkt, rectype)
  636. || !WPACKET_put_bytes_u16(thispkt, version)
  637. || !WPACKET_start_sub_packet_u16(thispkt)
  638. || (eivlen > 0
  639. && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
  640. || (maxcomplen > 0
  641. && !WPACKET_reserve_bytes(thispkt, maxcomplen,
  642. &compressdata)))) {
  643. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  644. goto err;
  645. }
  646. /* lets setup the record stuff. */
  647. SSL3_RECORD_set_data(thiswr, compressdata);
  648. SSL3_RECORD_set_length(thiswr, pipelens[j]);
  649. SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
  650. totlen += pipelens[j];
  651. /*
  652. * we now 'read' from thiswr->input, thiswr->length bytes into
  653. * thiswr->data
  654. */
  655. /* first we compress */
  656. if (s->compress != NULL) {
  657. if (!ssl3_do_compress(s, thiswr)
  658. || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
  659. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
  660. goto err;
  661. }
  662. } else {
  663. if (using_ktls) {
  664. SSL3_RECORD_reset_data(&wr[j]);
  665. } else {
  666. if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
  667. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  668. goto err;
  669. }
  670. SSL3_RECORD_reset_input(&wr[j]);
  671. }
  672. }
  673. if (SSL_CONNECTION_TREAT_AS_TLS13(s)
  674. && !using_ktls
  675. && s->enc_write_ctx != NULL
  676. && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
  677. || type != SSL3_RT_ALERT)) {
  678. size_t rlen, max_send_fragment;
  679. if (!WPACKET_put_bytes_u8(thispkt, type)) {
  680. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  681. goto err;
  682. }
  683. SSL3_RECORD_add_length(thiswr, 1);
  684. /* Add TLS1.3 padding */
  685. max_send_fragment = ssl_get_max_send_fragment(s);
  686. rlen = SSL3_RECORD_get_length(thiswr);
  687. if (rlen < max_send_fragment) {
  688. size_t padding = 0;
  689. size_t max_padding = max_send_fragment - rlen;
  690. if (s->record_padding_cb != NULL) {
  691. padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
  692. } else if (s->block_padding > 0) {
  693. size_t mask = s->block_padding - 1;
  694. size_t remainder;
  695. /* optimize for power of 2 */
  696. if ((s->block_padding & mask) == 0)
  697. remainder = rlen & mask;
  698. else
  699. remainder = rlen % s->block_padding;
  700. /* don't want to add a block of padding if we don't have to */
  701. if (remainder == 0)
  702. padding = 0;
  703. else
  704. padding = s->block_padding - remainder;
  705. }
  706. if (padding > 0) {
  707. /* do not allow the record to exceed max plaintext length */
  708. if (padding > max_padding)
  709. padding = max_padding;
  710. if (!WPACKET_memset(thispkt, 0, padding)) {
  711. SSLfatal(s, SSL_AD_INTERNAL_ERROR,
  712. ERR_R_INTERNAL_ERROR);
  713. goto err;
  714. }
  715. SSL3_RECORD_add_length(thiswr, padding);
  716. }
  717. }
  718. }
  719. /*
  720. * we should still have the output to thiswr->data and the input from
  721. * wr->input. Length should be thiswr->length. thiswr->data still points
  722. * in the wb->buf
  723. */
  724. if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
  725. unsigned char *mac;
  726. if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
  727. || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
  728. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  729. goto err;
  730. }
  731. }
  732. /*
  733. * Reserve some bytes for any growth that may occur during encryption.
  734. * This will be at most one cipher block or the tag length if using
  735. * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
  736. */
  737. if (!using_ktls) {
  738. if (!WPACKET_reserve_bytes(thispkt,
  739. SSL_RT_MAX_CIPHER_BLOCK_SIZE,
  740. NULL)
  741. /*
  742. * We also need next the amount of bytes written to this
  743. * sub-packet
  744. */
  745. || !WPACKET_get_length(thispkt, &len)) {
  746. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  747. goto err;
  748. }
  749. /* Get a pointer to the start of this record excluding header */
  750. recordstart = WPACKET_get_curr(thispkt) - len;
  751. SSL3_RECORD_set_data(thiswr, recordstart);
  752. SSL3_RECORD_reset_input(thiswr);
  753. SSL3_RECORD_set_length(thiswr, len);
  754. }
  755. }
  756. if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
  757. /*
  758. * We haven't actually negotiated the version yet, but we're trying to
  759. * send early data - so we need to use the tls13enc function.
  760. */
  761. if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
  762. if (!ossl_statem_in_error(s)) {
  763. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  764. }
  765. goto err;
  766. }
  767. } else {
  768. if (!using_ktls) {
  769. if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
  770. mac_size) < 1) {
  771. if (!ossl_statem_in_error(s)) {
  772. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  773. }
  774. goto err;
  775. }
  776. }
  777. }
  778. for (j = 0; j < numpipes; j++) {
  779. size_t origlen;
  780. thispkt = &pkt[j];
  781. thiswr = &wr[j];
  782. if (using_ktls)
  783. goto mac_done;
  784. /* Allocate bytes for the encryption overhead */
  785. if (!WPACKET_get_length(thispkt, &origlen)
  786. /* Encryption should never shrink the data! */
  787. || origlen > thiswr->length
  788. || (thiswr->length > origlen
  789. && !WPACKET_allocate_bytes(thispkt,
  790. thiswr->length - origlen,
  791. NULL))) {
  792. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  793. goto err;
  794. }
  795. if (SSL_WRITE_ETM(s) && mac_size != 0) {
  796. unsigned char *mac;
  797. if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
  798. || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
  799. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  800. goto err;
  801. }
  802. SSL3_RECORD_add_length(thiswr, mac_size);
  803. }
  804. if (!WPACKET_get_length(thispkt, &len)
  805. || !WPACKET_close(thispkt)) {
  806. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  807. goto err;
  808. }
  809. if (s->msg_callback) {
  810. recordstart = WPACKET_get_curr(thispkt) - len
  811. - SSL3_RT_HEADER_LENGTH;
  812. s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
  813. SSL3_RT_HEADER_LENGTH, ssl,
  814. s->msg_callback_arg);
  815. if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
  816. unsigned char ctype = type;
  817. s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
  818. &ctype, 1, ssl, s->msg_callback_arg);
  819. }
  820. }
  821. if (!WPACKET_finish(thispkt)) {
  822. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  823. goto err;
  824. }
  825. /* header is added by the kernel when using offload */
  826. SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
  827. if (create_empty_fragment) {
  828. /*
  829. * we are in a recursive call; just return the length, don't write
  830. * out anything here
  831. */
  832. if (j > 0) {
  833. /* We should never be pipelining an empty fragment!! */
  834. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  835. goto err;
  836. }
  837. *written = SSL3_RECORD_get_length(thiswr);
  838. return 1;
  839. }
  840. mac_done:
  841. /*
  842. * we should now have thiswr->data pointing to the encrypted data, which
  843. * is thiswr->length long
  844. */
  845. SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
  846. * debugging */
  847. /* now let's set up wb */
  848. SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
  849. prefix_len + SSL3_RECORD_get_length(thiswr));
  850. }
  851. /*
  852. * memorize arguments so that ssl3_write_pending can detect bad write
  853. * retries later
  854. */
  855. s->rlayer.wpend_tot = totlen;
  856. s->rlayer.wpend_buf = buf;
  857. s->rlayer.wpend_type = type;
  858. s->rlayer.wpend_ret = totlen;
  859. /* we now just need to write the buffer */
  860. return ssl3_write_pending(s, type, buf, totlen, written);
  861. err:
  862. for (j = 0; j < wpinited; j++)
  863. WPACKET_cleanup(&pkt[j]);
  864. return -1;
  865. }
  866. /* if SSL3_BUFFER_get_left() != 0, we need to call this
  867. *
  868. * Return values are as per SSL_write()
  869. */
  870. int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
  871. size_t len, size_t *written)
  872. {
  873. int i;
  874. SSL3_BUFFER *wb = s->rlayer.wbuf;
  875. size_t currbuf = 0;
  876. size_t tmpwrit = 0;
  877. if ((s->rlayer.wpend_tot > len)
  878. || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
  879. && (s->rlayer.wpend_buf != buf))
  880. || (s->rlayer.wpend_type != type)) {
  881. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
  882. return -1;
  883. }
  884. for (;;) {
  885. /* Loop until we find a buffer we haven't written out yet */
  886. if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
  887. && currbuf < s->rlayer.numwpipes - 1) {
  888. currbuf++;
  889. continue;
  890. }
  891. clear_sys_error();
  892. if (s->wbio != NULL) {
  893. s->rwstate = SSL_WRITING;
  894. /*
  895. * To prevent coalescing of control and data messages,
  896. * such as in buffer_write, we flush the BIO
  897. */
  898. if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
  899. i = BIO_flush(s->wbio);
  900. if (i <= 0)
  901. return i;
  902. BIO_set_ktls_ctrl_msg(s->wbio, type);
  903. }
  904. i = BIO_write(s->wbio, (char *)
  905. &(SSL3_BUFFER_get_buf(&wb[currbuf])
  906. [SSL3_BUFFER_get_offset(&wb[currbuf])]),
  907. (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
  908. if (i >= 0)
  909. tmpwrit = i;
  910. } else {
  911. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
  912. i = -1;
  913. }
  914. /*
  915. * When an empty fragment is sent on a connection using KTLS,
  916. * it is sent as a write of zero bytes. If this zero byte
  917. * write succeeds, i will be 0 rather than a non-zero value.
  918. * Treat i == 0 as success rather than an error for zero byte
  919. * writes to permit this case.
  920. */
  921. if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
  922. SSL3_BUFFER_set_left(&wb[currbuf], 0);
  923. SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
  924. if (currbuf + 1 < s->rlayer.numwpipes)
  925. continue;
  926. s->rwstate = SSL_NOTHING;
  927. *written = s->rlayer.wpend_ret;
  928. return 1;
  929. } else if (i <= 0) {
  930. if (SSL_CONNECTION_IS_DTLS(s)) {
  931. /*
  932. * For DTLS, just drop it. That's kind of the whole point in
  933. * using a datagram service
  934. */
  935. SSL3_BUFFER_set_left(&wb[currbuf], 0);
  936. }
  937. return i;
  938. }
  939. SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
  940. SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
  941. }
  942. }
  943. int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
  944. int line)
  945. {
  946. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  947. if (ret == OSSL_RECORD_RETURN_RETRY) {
  948. s->rwstate = SSL_READING;
  949. ret = -1;
  950. } else {
  951. s->rwstate = SSL_NOTHING;
  952. if (ret == OSSL_RECORD_RETURN_EOF) {
  953. if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
  954. SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
  955. s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
  956. } else {
  957. ERR_new();
  958. ERR_set_debug(file, line, 0);
  959. ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
  960. SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
  961. }
  962. } else if (ret == OSSL_RECORD_RETURN_FATAL) {
  963. int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
  964. if (al != SSL_AD_NO_ALERT) {
  965. ERR_new();
  966. ERR_set_debug(file, line, 0);
  967. ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
  968. }
  969. /*
  970. * else some failure but there is no alert code. We don't log an
  971. * error for this. The record layer should have logged an error
  972. * already or, if not, its due to some sys call error which will be
  973. * reported via SSL_ERROR_SYSCALL and errno.
  974. */
  975. }
  976. /*
  977. * The record layer distinguishes the cases of EOF, non-fatal
  978. * err and retry. Upper layers do not.
  979. * If we got a retry or success then *ret is already correct,
  980. * otherwise we need to convert the return value.
  981. */
  982. if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
  983. ret = 0;
  984. else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
  985. ret = -1;
  986. }
  987. return ret;
  988. }
  989. void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
  990. {
  991. if (rr->rechandle != NULL) {
  992. /* The record layer allocated the buffers for this record */
  993. s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
  994. } else {
  995. /* We allocated the buffers for this record (only happens with DTLS) */
  996. OPENSSL_free(rr->data);
  997. }
  998. s->rlayer.curr_rec++;
  999. }
  1000. /*-
  1001. * Return up to 'len' payload bytes received in 'type' records.
  1002. * 'type' is one of the following:
  1003. *
  1004. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  1005. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  1006. * - 0 (during a shutdown, no data has to be returned)
  1007. *
  1008. * If we don't have stored data to work from, read a SSL/TLS record first
  1009. * (possibly multiple records if we still don't have anything to return).
  1010. *
  1011. * This function must handle any surprises the peer may have for us, such as
  1012. * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
  1013. * messages are treated as if they were handshake messages *if* the |recvd_type|
  1014. * argument is non NULL.
  1015. * Also if record payloads contain fragments too small to process, we store
  1016. * them until there is enough for the respective protocol (the record protocol
  1017. * may use arbitrary fragmentation and even interleaving):
  1018. * Change cipher spec protocol
  1019. * just 1 byte needed, no need for keeping anything stored
  1020. * Alert protocol
  1021. * 2 bytes needed (AlertLevel, AlertDescription)
  1022. * Handshake protocol
  1023. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  1024. * to detect unexpected Client Hello and Hello Request messages
  1025. * here, anything else is handled by higher layers
  1026. * Application data protocol
  1027. * none of our business
  1028. */
  1029. int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
  1030. size_t len, int peek, size_t *readbytes)
  1031. {
  1032. int i, j, ret;
  1033. size_t n, curr_rec, totalbytes;
  1034. TLS_RECORD *rr;
  1035. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  1036. int is_tls13;
  1037. SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
  1038. is_tls13 = SSL_CONNECTION_IS_TLS13(s);
  1039. if ((type != 0
  1040. && (type != SSL3_RT_APPLICATION_DATA)
  1041. && (type != SSL3_RT_HANDSHAKE))
  1042. || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  1043. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1044. return -1;
  1045. }
  1046. if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
  1047. /* (partially) satisfy request from storage */
  1048. {
  1049. unsigned char *src = s->rlayer.handshake_fragment;
  1050. unsigned char *dst = buf;
  1051. unsigned int k;
  1052. /* peek == 0 */
  1053. n = 0;
  1054. while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
  1055. *dst++ = *src++;
  1056. len--;
  1057. s->rlayer.handshake_fragment_len--;
  1058. n++;
  1059. }
  1060. /* move any remaining fragment bytes: */
  1061. for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
  1062. s->rlayer.handshake_fragment[k] = *src++;
  1063. if (recvd_type != NULL)
  1064. *recvd_type = SSL3_RT_HANDSHAKE;
  1065. *readbytes = n;
  1066. return 1;
  1067. }
  1068. /*
  1069. * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  1070. */
  1071. if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
  1072. /* type == SSL3_RT_APPLICATION_DATA */
  1073. i = s->handshake_func(ssl);
  1074. /* SSLfatal() already called */
  1075. if (i < 0)
  1076. return i;
  1077. if (i == 0)
  1078. return -1;
  1079. }
  1080. start:
  1081. s->rwstate = SSL_NOTHING;
  1082. /*-
  1083. * For each record 'i' up to |num_recs]
  1084. * rr[i].type - is the type of record
  1085. * rr[i].data, - data
  1086. * rr[i].off, - offset into 'data' for next read
  1087. * rr[i].length, - number of bytes.
  1088. */
  1089. /* get new records if necessary */
  1090. if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
  1091. s->rlayer.curr_rec = s->rlayer.num_recs = 0;
  1092. do {
  1093. rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
  1094. ret = HANDLE_RLAYER_RETURN(s,
  1095. s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
  1096. &rr->rechandle,
  1097. &rr->version, &rr->type,
  1098. &rr->data, &rr->length,
  1099. NULL, NULL));
  1100. if (ret <= 0) {
  1101. /* SSLfatal() already called if appropriate */
  1102. return ret;
  1103. }
  1104. rr->off = 0;
  1105. s->rlayer.num_recs++;
  1106. } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
  1107. && s->rlayer.num_recs < SSL_MAX_PIPELINES);
  1108. }
  1109. rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
  1110. if (s->rlayer.handshake_fragment_len > 0
  1111. && rr->type != SSL3_RT_HANDSHAKE
  1112. && SSL_CONNECTION_IS_TLS13(s)) {
  1113. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  1114. SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
  1115. return -1;
  1116. }
  1117. /*
  1118. * Reset the count of consecutive warning alerts if we've got a non-empty
  1119. * record that isn't an alert.
  1120. */
  1121. if (rr->type != SSL3_RT_ALERT && rr->length != 0)
  1122. s->rlayer.alert_count = 0;
  1123. /* we now have a packet which can be read and processed */
  1124. if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
  1125. * reset by ssl3_get_finished */
  1126. && (rr->type != SSL3_RT_HANDSHAKE)) {
  1127. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  1128. SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  1129. return -1;
  1130. }
  1131. /*
  1132. * If the other end has shut down, throw anything we read away (even in
  1133. * 'peek' mode)
  1134. */
  1135. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  1136. s->rlayer.curr_rec++;
  1137. s->rwstate = SSL_NOTHING;
  1138. return 0;
  1139. }
  1140. if (type == rr->type
  1141. || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  1142. && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
  1143. && !is_tls13)) {
  1144. /*
  1145. * SSL3_RT_APPLICATION_DATA or
  1146. * SSL3_RT_HANDSHAKE or
  1147. * SSL3_RT_CHANGE_CIPHER_SPEC
  1148. */
  1149. /*
  1150. * make sure that we are not getting application data when we are
  1151. * doing a handshake for the first time
  1152. */
  1153. if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
  1154. && s->enc_read_ctx == NULL) {
  1155. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
  1156. return -1;
  1157. }
  1158. if (type == SSL3_RT_HANDSHAKE
  1159. && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  1160. && s->rlayer.handshake_fragment_len > 0) {
  1161. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  1162. return -1;
  1163. }
  1164. if (recvd_type != NULL)
  1165. *recvd_type = rr->type;
  1166. if (len == 0) {
  1167. /*
  1168. * Skip a zero length record. This ensures multiple calls to
  1169. * SSL_read() with a zero length buffer will eventually cause
  1170. * SSL_pending() to report data as being available.
  1171. */
  1172. if (rr->length == 0)
  1173. ssl_release_record(s, rr);
  1174. return 0;
  1175. }
  1176. totalbytes = 0;
  1177. curr_rec = s->rlayer.curr_rec;
  1178. do {
  1179. if (len - totalbytes > rr->length)
  1180. n = rr->length;
  1181. else
  1182. n = len - totalbytes;
  1183. memcpy(buf, &(rr->data[rr->off]), n);
  1184. buf += n;
  1185. if (peek) {
  1186. /* Mark any zero length record as consumed CVE-2016-6305 */
  1187. if (rr->length == 0)
  1188. ssl_release_record(s, rr);
  1189. } else {
  1190. if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
  1191. OPENSSL_cleanse(&(rr->data[rr->off]), n);
  1192. rr->length -= n;
  1193. rr->off += n;
  1194. if (rr->length == 0)
  1195. ssl_release_record(s, rr);
  1196. }
  1197. if (rr->length == 0
  1198. || (peek && n == rr->length)) {
  1199. rr++;
  1200. curr_rec++;
  1201. }
  1202. totalbytes += n;
  1203. } while (type == SSL3_RT_APPLICATION_DATA
  1204. && curr_rec < s->rlayer.num_recs
  1205. && totalbytes < len);
  1206. if (totalbytes == 0) {
  1207. /* We must have read empty records. Get more data */
  1208. goto start;
  1209. }
  1210. *readbytes = totalbytes;
  1211. return 1;
  1212. }
  1213. /*
  1214. * If we get here, then type != rr->type; if we have a handshake message,
  1215. * then it was unexpected (Hello Request or Client Hello) or invalid (we
  1216. * were actually expecting a CCS).
  1217. */
  1218. /*
  1219. * Lets just double check that we've not got an SSLv2 record
  1220. */
  1221. if (rr->version == SSL2_VERSION) {
  1222. /*
  1223. * Should never happen. ssl3_get_record() should only give us an SSLv2
  1224. * record back if this is the first packet and we are looking for an
  1225. * initial ClientHello. Therefore |type| should always be equal to
  1226. * |rr->type|. If not then something has gone horribly wrong
  1227. */
  1228. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1229. return -1;
  1230. }
  1231. if (ssl->method->version == TLS_ANY_VERSION
  1232. && (s->server || rr->type != SSL3_RT_ALERT)) {
  1233. /*
  1234. * If we've got this far and still haven't decided on what version
  1235. * we're using then this must be a client side alert we're dealing
  1236. * with. We shouldn't be receiving anything other than a ClientHello
  1237. * if we are a server.
  1238. */
  1239. s->version = rr->version;
  1240. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
  1241. return -1;
  1242. }
  1243. /*-
  1244. * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  1245. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  1246. */
  1247. if (rr->type == SSL3_RT_ALERT) {
  1248. unsigned int alert_level, alert_descr;
  1249. unsigned char *alert_bytes = rr->data
  1250. + rr->off;
  1251. PACKET alert;
  1252. if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
  1253. || !PACKET_get_1(&alert, &alert_level)
  1254. || !PACKET_get_1(&alert, &alert_descr)
  1255. || PACKET_remaining(&alert) != 0) {
  1256. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
  1257. return -1;
  1258. }
  1259. if (s->msg_callback)
  1260. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
  1261. s->msg_callback_arg);
  1262. if (s->info_callback != NULL)
  1263. cb = s->info_callback;
  1264. else if (ssl->ctx->info_callback != NULL)
  1265. cb = ssl->ctx->info_callback;
  1266. if (cb != NULL) {
  1267. j = (alert_level << 8) | alert_descr;
  1268. cb(ssl, SSL_CB_READ_ALERT, j);
  1269. }
  1270. if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
  1271. || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
  1272. s->s3.warn_alert = alert_descr;
  1273. ssl_release_record(s, rr);
  1274. s->rlayer.alert_count++;
  1275. if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
  1276. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  1277. SSL_R_TOO_MANY_WARN_ALERTS);
  1278. return -1;
  1279. }
  1280. }
  1281. /*
  1282. * Apart from close_notify the only other warning alert in TLSv1.3
  1283. * is user_cancelled - which we just ignore.
  1284. */
  1285. if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
  1286. goto start;
  1287. } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
  1288. && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
  1289. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1290. return 0;
  1291. } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
  1292. s->rwstate = SSL_NOTHING;
  1293. s->s3.fatal_alert = alert_descr;
  1294. SSLfatal_data(s, SSL_AD_NO_ALERT,
  1295. SSL_AD_REASON_OFFSET + alert_descr,
  1296. "SSL alert number %d", alert_descr);
  1297. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1298. ssl_release_record(s, rr);
  1299. SSL_CTX_remove_session(s->session_ctx, s->session);
  1300. return 0;
  1301. } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  1302. /*
  1303. * This is a warning but we receive it if we requested
  1304. * renegotiation and the peer denied it. Terminate with a fatal
  1305. * alert because if application tried to renegotiate it
  1306. * presumably had a good reason and expects it to succeed. In
  1307. * future we might have a renegotiation where we don't care if
  1308. * the peer refused it where we carry on.
  1309. */
  1310. SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
  1311. return -1;
  1312. } else if (alert_level == SSL3_AL_WARNING) {
  1313. /* We ignore any other warning alert in TLSv1.2 and below */
  1314. goto start;
  1315. }
  1316. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
  1317. return -1;
  1318. }
  1319. if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
  1320. if (rr->type == SSL3_RT_HANDSHAKE) {
  1321. BIO *rbio;
  1322. /*
  1323. * We ignore any handshake messages sent to us unless they are
  1324. * TLSv1.3 in which case we want to process them. For all other
  1325. * handshake messages we can't do anything reasonable with them
  1326. * because we are unable to write any response due to having already
  1327. * sent close_notify.
  1328. */
  1329. if (!SSL_CONNECTION_IS_TLS13(s)) {
  1330. ssl_release_record(s, rr);
  1331. if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
  1332. goto start;
  1333. s->rwstate = SSL_READING;
  1334. rbio = SSL_get_rbio(ssl);
  1335. BIO_clear_retry_flags(rbio);
  1336. BIO_set_retry_read(rbio);
  1337. return -1;
  1338. }
  1339. } else {
  1340. /*
  1341. * The peer is continuing to send application data, but we have
  1342. * already sent close_notify. If this was expected we should have
  1343. * been called via SSL_read() and this would have been handled
  1344. * above.
  1345. * No alert sent because we already sent close_notify
  1346. */
  1347. ssl_release_record(s, rr);
  1348. SSLfatal(s, SSL_AD_NO_ALERT,
  1349. SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
  1350. return -1;
  1351. }
  1352. }
  1353. /*
  1354. * For handshake data we have 'fragment' storage, so fill that so that we
  1355. * can process the header at a fixed place. This is done after the
  1356. * "SHUTDOWN" code above to avoid filling the fragment storage with data
  1357. * that we're just going to discard.
  1358. */
  1359. if (rr->type == SSL3_RT_HANDSHAKE) {
  1360. size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
  1361. unsigned char *dest = s->rlayer.handshake_fragment;
  1362. size_t *dest_len = &s->rlayer.handshake_fragment_len;
  1363. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  1364. if (rr->length < n)
  1365. n = rr->length; /* available bytes */
  1366. /* now move 'n' bytes: */
  1367. memcpy(dest + *dest_len, rr->data + rr->off, n);
  1368. rr->off += n;
  1369. rr->length -= n;
  1370. *dest_len += n;
  1371. if (rr->length == 0)
  1372. ssl_release_record(s, rr);
  1373. if (*dest_len < dest_maxlen)
  1374. goto start; /* fragment was too small */
  1375. }
  1376. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1377. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  1378. return -1;
  1379. }
  1380. /*
  1381. * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
  1382. * protocol violation)
  1383. */
  1384. if ((s->rlayer.handshake_fragment_len >= 4)
  1385. && !ossl_statem_get_in_handshake(s)) {
  1386. int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
  1387. /* We found handshake data, so we're going back into init */
  1388. ossl_statem_set_in_init(s, 1);
  1389. i = s->handshake_func(ssl);
  1390. /* SSLfatal() already called if appropriate */
  1391. if (i < 0)
  1392. return i;
  1393. if (i == 0) {
  1394. return -1;
  1395. }
  1396. /*
  1397. * If we were actually trying to read early data and we found a
  1398. * handshake message, then we don't want to continue to try and read
  1399. * the application data any more. It won't be "early" now.
  1400. */
  1401. if (ined)
  1402. return -1;
  1403. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1404. if (!RECORD_LAYER_read_pending(&s->rlayer)) {
  1405. BIO *bio;
  1406. /*
  1407. * In the case where we try to read application data, but we
  1408. * trigger an SSL handshake, we return -1 with the retry
  1409. * option set. Otherwise renegotiation may cause nasty
  1410. * problems in the blocking world
  1411. */
  1412. s->rwstate = SSL_READING;
  1413. bio = SSL_get_rbio(ssl);
  1414. BIO_clear_retry_flags(bio);
  1415. BIO_set_retry_read(bio);
  1416. return -1;
  1417. }
  1418. }
  1419. goto start;
  1420. }
  1421. switch (rr->type) {
  1422. default:
  1423. /*
  1424. * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
  1425. * TLS 1.2 says you MUST send an unexpected message alert. We use the
  1426. * TLS 1.2 behaviour for all protocol versions to prevent issues where
  1427. * no progress is being made and the peer continually sends unrecognised
  1428. * record types, using up resources processing them.
  1429. */
  1430. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  1431. return -1;
  1432. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1433. case SSL3_RT_ALERT:
  1434. case SSL3_RT_HANDSHAKE:
  1435. /*
  1436. * we already handled all of these, with the possible exception of
  1437. * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
  1438. * that should not happen when type != rr->type
  1439. */
  1440. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
  1441. return -1;
  1442. case SSL3_RT_APPLICATION_DATA:
  1443. /*
  1444. * At this point, we were expecting handshake data, but have
  1445. * application data. If the library was running inside ssl3_read()
  1446. * (i.e. in_read_app_data is set) and it makes sense to read
  1447. * application data at this point (session renegotiation not yet
  1448. * started), we will indulge it.
  1449. */
  1450. if (ossl_statem_app_data_allowed(s)) {
  1451. s->s3.in_read_app_data = 2;
  1452. return -1;
  1453. } else if (ossl_statem_skip_early_data(s)) {
  1454. /*
  1455. * This can happen after a client sends a CH followed by early_data,
  1456. * but the server responds with a HelloRetryRequest. The server
  1457. * reads the next record from the client expecting to find a
  1458. * plaintext ClientHello but gets a record which appears to be
  1459. * application data. The trial decrypt "works" because null
  1460. * decryption was applied. We just skip it and move on to the next
  1461. * record.
  1462. */
  1463. if (!ossl_early_data_count_ok(s, rr->length,
  1464. EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
  1465. /* SSLfatal() already called */
  1466. return -1;
  1467. }
  1468. ssl_release_record(s, rr);
  1469. goto start;
  1470. } else {
  1471. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
  1472. return -1;
  1473. }
  1474. }
  1475. }
  1476. void ssl3_record_sequence_update(unsigned char *seq)
  1477. {
  1478. int i;
  1479. for (i = 7; i >= 0; i--) {
  1480. ++seq[i];
  1481. if (seq[i] != 0)
  1482. break;
  1483. }
  1484. }
  1485. /*
  1486. * Returns true if the current rrec was sent in SSLv2 backwards compatible
  1487. * format and false otherwise.
  1488. */
  1489. int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
  1490. {
  1491. if (SSL_CONNECTION_IS_DTLS(rl->s))
  1492. return 0;
  1493. return rl->tlsrecs[0].version == SSL2_VERSION;
  1494. }
  1495. static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
  1496. static void rlayer_msg_callback_wrapper(int write_p, int version,
  1497. int content_type, const void *buf,
  1498. size_t len, void *cbarg)
  1499. {
  1500. SSL_CONNECTION *s = cbarg;
  1501. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1502. if (s->msg_callback != NULL)
  1503. s->msg_callback(write_p, version, content_type, buf, len, ssl,
  1504. s->msg_callback_arg);
  1505. }
  1506. static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
  1507. static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
  1508. void *other)
  1509. {
  1510. SSL_CONNECTION *s = cbarg;
  1511. return ssl_security(s, op, bits, nid, other);
  1512. }
  1513. static const OSSL_DISPATCH rlayer_dispatch[] = {
  1514. { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
  1515. { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
  1516. { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
  1517. { 0, NULL }
  1518. };
  1519. static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
  1520. int level)
  1521. {
  1522. if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
  1523. if (SSL_CONNECTION_IS_DTLS(s))
  1524. return &ossl_dtls_record_method;
  1525. return &ossl_tls_record_method;
  1526. }
  1527. #ifndef OPENSSL_NO_KTLS
  1528. /* KTLS does not support renegotiation */
  1529. if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
  1530. && (s->options & SSL_OP_ENABLE_KTLS) != 0
  1531. && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
  1532. return &ossl_ktls_record_method;
  1533. #endif
  1534. /* Default to the current OSSL_RECORD_METHOD */
  1535. return s->rlayer.rrlmethod;
  1536. }
  1537. static int ssl_post_record_layer_select(SSL_CONNECTION *s)
  1538. {
  1539. #ifndef OPENSSL_NO_KTLS
  1540. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1541. if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
  1542. /* KTLS does not support renegotiation so disallow it */
  1543. SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
  1544. }
  1545. #endif
  1546. if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
  1547. s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
  1548. if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
  1549. s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
  1550. return 1;
  1551. }
  1552. int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
  1553. int direction, int level,
  1554. unsigned char *key, size_t keylen,
  1555. unsigned char *iv, size_t ivlen,
  1556. unsigned char *mackey, size_t mackeylen,
  1557. const EVP_CIPHER *ciph, size_t taglen,
  1558. int mactype, const EVP_MD *md,
  1559. const SSL_COMP *comp)
  1560. {
  1561. OSSL_PARAM options[5], *opts = options;
  1562. OSSL_PARAM settings[6], *set = settings;
  1563. const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
  1564. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  1565. const OSSL_RECORD_METHOD *meth;
  1566. int use_etm, stream_mac = 0, tlstree = 0;
  1567. unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
  1568. int use_early_data = 0;
  1569. uint32_t max_early_data;
  1570. meth = ssl_select_next_record_layer(s, level);
  1571. if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
  1572. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  1573. return 0;
  1574. }
  1575. s->rlayer.rrl = NULL;
  1576. if (meth != NULL)
  1577. s->rlayer.rrlmethod = meth;
  1578. if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
  1579. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  1580. return 0;
  1581. }
  1582. /* Parameters that *may* be supported by a record layer if passed */
  1583. *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
  1584. &s->options);
  1585. *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
  1586. &s->mode);
  1587. *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
  1588. &s->rlayer.default_read_buf_len);
  1589. *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
  1590. &s->rlayer.read_ahead);
  1591. *opts = OSSL_PARAM_construct_end();
  1592. /* Parameters that *must* be supported by a record layer if passed */
  1593. if (direction == OSSL_RECORD_DIRECTION_READ) {
  1594. use_etm = SSL_READ_ETM(s) ? 1 : 0;
  1595. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
  1596. stream_mac = 1;
  1597. if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
  1598. tlstree = 1;
  1599. } else {
  1600. use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
  1601. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
  1602. stream_mac = 1;
  1603. if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
  1604. tlstree = 1;
  1605. }
  1606. if (use_etm)
  1607. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
  1608. &use_etm);
  1609. if (stream_mac)
  1610. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
  1611. &stream_mac);
  1612. if (tlstree)
  1613. *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
  1614. &tlstree);
  1615. if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
  1616. maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
  1617. if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
  1618. *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
  1619. &maxfrag);
  1620. /*
  1621. * The record layer must check the amount of early data sent or received
  1622. * using the early keys. A server also needs to worry about rejected early
  1623. * data that might arrive when the handshake keys are in force.
  1624. */
  1625. /* TODO(RECLAYER): Check this when doing the "write" record layer */
  1626. if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
  1627. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
  1628. || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
  1629. } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
  1630. use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
  1631. }
  1632. if (use_early_data) {
  1633. max_early_data = ossl_get_max_early_data(s);
  1634. if (max_early_data != 0)
  1635. *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
  1636. &max_early_data);
  1637. }
  1638. *set = OSSL_PARAM_construct_end();
  1639. for (;;) {
  1640. int rlret;
  1641. BIO *prev = s->rlayer.rrlnext;
  1642. unsigned int epoch = 0;;
  1643. if (SSL_CONNECTION_IS_DTLS(s)
  1644. && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1645. epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
  1646. if (SSL_CONNECTION_IS_DTLS(s))
  1647. s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
  1648. else
  1649. s->rlayer.rrlnext = BIO_new(BIO_s_mem());
  1650. if (s->rlayer.rrlnext == NULL) {
  1651. BIO_free(prev);
  1652. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1653. return 0;
  1654. }
  1655. rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
  1656. sctx->propq,
  1657. version, s->server,
  1658. direction, level, epoch,
  1659. key, keylen, iv, ivlen,
  1660. mackey, mackeylen, ciph,
  1661. taglen, mactype, md, comp,
  1662. prev, s->rbio,
  1663. s->rlayer.rrlnext, NULL,
  1664. NULL, settings, options,
  1665. rlayer_dispatch, s,
  1666. &s->rlayer.rrl);
  1667. BIO_free(prev);
  1668. switch (rlret) {
  1669. case OSSL_RECORD_RETURN_FATAL:
  1670. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
  1671. return 0;
  1672. case OSSL_RECORD_RETURN_NON_FATAL_ERR:
  1673. if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
  1674. /*
  1675. * We tried a new record layer method, but it didn't work out,
  1676. * so we fallback to the original method and try again
  1677. */
  1678. s->rlayer.rrlmethod = origmeth;
  1679. continue;
  1680. }
  1681. SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
  1682. return 0;
  1683. case OSSL_RECORD_RETURN_SUCCESS:
  1684. break;
  1685. default:
  1686. /* Should not happen */
  1687. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1688. return 0;
  1689. }
  1690. break;
  1691. }
  1692. return ssl_post_record_layer_select(s);
  1693. }