tls_common.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160
  1. /*
  2. * Copyright 2022-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 <assert.h>
  10. #include <openssl/bio.h>
  11. #include <openssl/ssl.h>
  12. #include <openssl/err.h>
  13. #include <openssl/core_names.h>
  14. #include <openssl/comp.h>
  15. #include <openssl/ssl.h>
  16. #include "internal/e_os.h"
  17. #include "internal/packet.h"
  18. #include "internal/ssl3_cbc.h"
  19. #include "../../ssl_local.h"
  20. #include "../record_local.h"
  21. #include "recmethod_local.h"
  22. static void tls_int_free(OSSL_RECORD_LAYER *rl);
  23. void ossl_tls_buffer_release(TLS_BUFFER *b)
  24. {
  25. OPENSSL_free(b->buf);
  26. b->buf = NULL;
  27. }
  28. static void TLS_RL_RECORD_release(TLS_RL_RECORD *r, size_t num_recs)
  29. {
  30. size_t i;
  31. for (i = 0; i < num_recs; i++) {
  32. OPENSSL_free(r[i].comp);
  33. r[i].comp = NULL;
  34. }
  35. }
  36. void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r,
  37. const unsigned char *seq_num)
  38. {
  39. memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
  40. }
  41. void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
  42. const char *fmt, ...)
  43. {
  44. va_list args;
  45. va_start(args, fmt);
  46. ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
  47. va_end(args);
  48. rl->alert = al;
  49. }
  50. int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
  51. EVP_CIPHER_CTX *ctx,
  52. const EVP_CIPHER *ciph,
  53. const EVP_MD *md)
  54. {
  55. /*
  56. * Provided cipher, the TLS padding/MAC removal is performed provider
  57. * side so we need to tell the ctx about our TLS version and mac size
  58. */
  59. OSSL_PARAM params[3], *pprm = params;
  60. size_t macsize = 0;
  61. int imacsize = -1;
  62. if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
  63. && !rl->use_etm)
  64. imacsize = EVP_MD_get_size(md);
  65. if (imacsize >= 0)
  66. macsize = (size_t)imacsize;
  67. *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
  68. &rl->version);
  69. *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
  70. &macsize);
  71. *pprm = OSSL_PARAM_construct_end();
  72. if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
  73. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  74. return 0;
  75. }
  76. return 1;
  77. }
  78. /*
  79. * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
  80. * which ssl3_cbc_digest_record supports.
  81. */
  82. char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
  83. {
  84. switch (EVP_MD_CTX_get_type(ctx)) {
  85. case NID_md5:
  86. case NID_sha1:
  87. case NID_sha224:
  88. case NID_sha256:
  89. case NID_sha384:
  90. case NID_sha512:
  91. return 1;
  92. default:
  93. return 0;
  94. }
  95. }
  96. #ifndef OPENSSL_NO_COMP
  97. static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
  98. {
  99. if (rl->options & SSL_OP_NO_COMPRESSION)
  100. return 0;
  101. return rl->security == NULL
  102. || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
  103. }
  104. #endif
  105. static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
  106. {
  107. TLS_BUFFER *wb;
  108. size_t pipes;
  109. pipes = rl->numwpipes;
  110. while (pipes > start) {
  111. wb = &rl->wbuf[pipes - 1];
  112. if (TLS_BUFFER_is_app_buffer(wb))
  113. TLS_BUFFER_set_app_buffer(wb, 0);
  114. else
  115. OPENSSL_free(wb->buf);
  116. wb->buf = NULL;
  117. pipes--;
  118. }
  119. }
  120. int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
  121. size_t firstlen, size_t nextlen)
  122. {
  123. unsigned char *p;
  124. size_t align = 0, headerlen;
  125. TLS_BUFFER *wb;
  126. size_t currpipe;
  127. size_t defltlen = 0;
  128. size_t contenttypelen = 0;
  129. if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
  130. if (rl->isdtls)
  131. headerlen = DTLS1_RT_HEADER_LENGTH + 1;
  132. else
  133. headerlen = SSL3_RT_HEADER_LENGTH;
  134. /* TLSv1.3 adds an extra content type byte after payload data */
  135. if (rl->version == TLS1_3_VERSION)
  136. contenttypelen = 1;
  137. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
  138. align = SSL3_ALIGN_PAYLOAD - 1;
  139. #endif
  140. defltlen = align + headerlen + rl->eivlen + rl->max_frag_len
  141. + contenttypelen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
  142. #ifndef OPENSSL_NO_COMP
  143. if (tls_allow_compression(rl))
  144. defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
  145. #endif
  146. /*
  147. * We don't need to add eivlen here since empty fragments only occur
  148. * when we don't have an explicit IV. The contenttype byte will also
  149. * always be 0 in these protocol versions
  150. */
  151. if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0)
  152. defltlen += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
  153. }
  154. wb = rl->wbuf;
  155. for (currpipe = 0; currpipe < numwpipes; currpipe++) {
  156. TLS_BUFFER *thiswb = &wb[currpipe];
  157. size_t len = (currpipe == 0) ? firstlen : nextlen;
  158. if (len == 0)
  159. len = defltlen;
  160. if (thiswb->len != len) {
  161. OPENSSL_free(thiswb->buf);
  162. thiswb->buf = NULL; /* force reallocation */
  163. }
  164. p = thiswb->buf;
  165. if (p == NULL) {
  166. p = OPENSSL_malloc(len);
  167. if (p == NULL) {
  168. if (rl->numwpipes < currpipe)
  169. rl->numwpipes = currpipe;
  170. /*
  171. * We've got a malloc failure, and we're still initialising
  172. * buffers. We assume we're so doomed that we won't even be able
  173. * to send an alert.
  174. */
  175. RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
  176. return 0;
  177. }
  178. }
  179. memset(thiswb, 0, sizeof(TLS_BUFFER));
  180. thiswb->buf = p;
  181. thiswb->len = len;
  182. }
  183. /* Free any previously allocated buffers that we are no longer using */
  184. tls_release_write_buffer_int(rl, currpipe);
  185. rl->numwpipes = numwpipes;
  186. return 1;
  187. }
  188. static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
  189. {
  190. tls_release_write_buffer_int(rl, 0);
  191. rl->numwpipes = 0;
  192. }
  193. int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
  194. {
  195. unsigned char *p;
  196. size_t len, align = 0, headerlen;
  197. TLS_BUFFER *b;
  198. b = &rl->rbuf;
  199. if (rl->isdtls)
  200. headerlen = DTLS1_RT_HEADER_LENGTH;
  201. else
  202. headerlen = SSL3_RT_HEADER_LENGTH;
  203. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
  204. align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
  205. #endif
  206. if (b->buf == NULL) {
  207. len = rl->max_frag_len
  208. + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
  209. #ifndef OPENSSL_NO_COMP
  210. if (tls_allow_compression(rl))
  211. len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
  212. #endif
  213. /* Ensure our buffer is large enough to support all our pipelines */
  214. if (rl->max_pipelines > 1)
  215. len *= rl->max_pipelines;
  216. if (b->default_len > len)
  217. len = b->default_len;
  218. if ((p = OPENSSL_malloc(len)) == NULL) {
  219. /*
  220. * We've got a malloc failure, and we're still initialising buffers.
  221. * We assume we're so doomed that we won't even be able to send an
  222. * alert.
  223. */
  224. RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
  225. return 0;
  226. }
  227. b->buf = p;
  228. b->len = len;
  229. }
  230. return 1;
  231. }
  232. static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
  233. {
  234. TLS_BUFFER *b;
  235. b = &rl->rbuf;
  236. if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
  237. OPENSSL_cleanse(b->buf, b->len);
  238. OPENSSL_free(b->buf);
  239. b->buf = NULL;
  240. return 1;
  241. }
  242. /*
  243. * Return values are as per SSL_read()
  244. */
  245. int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
  246. int clearold, size_t *readbytes)
  247. {
  248. /*
  249. * If extend == 0, obtain new n-byte packet; if extend == 1, increase
  250. * packet by another n bytes. The packet will be in the sub-array of
  251. * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
  252. * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
  253. * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
  254. * packet to the start of the buffer; if clearold == 0 then leave any old
  255. * packets where they were
  256. */
  257. size_t len, left, align = 0;
  258. unsigned char *pkt;
  259. TLS_BUFFER *rb;
  260. if (n == 0)
  261. return OSSL_RECORD_RETURN_NON_FATAL_ERR;
  262. rb = &rl->rbuf;
  263. left = rb->left;
  264. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
  265. align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
  266. align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
  267. #endif
  268. if (!extend) {
  269. /* start with empty packet ... */
  270. if (left == 0)
  271. rb->offset = align;
  272. rl->packet = rb->buf + rb->offset;
  273. rl->packet_length = 0;
  274. /* ... now we can act as if 'extend' was set */
  275. }
  276. len = rl->packet_length;
  277. pkt = rb->buf + align;
  278. /*
  279. * Move any available bytes to front of buffer: 'len' bytes already
  280. * pointed to by 'packet', 'left' extra ones at the end
  281. */
  282. if (rl->packet != pkt && clearold == 1) {
  283. memmove(pkt, rl->packet, len + left);
  284. rl->packet = pkt;
  285. rb->offset = len + align;
  286. }
  287. /*
  288. * For DTLS/UDP reads should not span multiple packets because the read
  289. * operation returns the whole packet at once (as long as it fits into
  290. * the buffer).
  291. */
  292. if (rl->isdtls) {
  293. if (left == 0 && extend) {
  294. /*
  295. * We received a record with a header but no body data. This will
  296. * get dumped.
  297. */
  298. return OSSL_RECORD_RETURN_NON_FATAL_ERR;
  299. }
  300. if (left > 0 && n > left)
  301. n = left;
  302. }
  303. /* if there is enough in the buffer from a previous read, take some */
  304. if (left >= n) {
  305. rl->packet_length += n;
  306. rb->left = left - n;
  307. rb->offset += n;
  308. *readbytes = n;
  309. return OSSL_RECORD_RETURN_SUCCESS;
  310. }
  311. /* else we need to read more data */
  312. if (n > rb->len - rb->offset) {
  313. /* does not happen */
  314. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  315. return OSSL_RECORD_RETURN_FATAL;
  316. }
  317. /* We always act like read_ahead is set for DTLS */
  318. if (!rl->read_ahead && !rl->isdtls) {
  319. /* ignore max parameter */
  320. max = n;
  321. } else {
  322. if (max < n)
  323. max = n;
  324. if (max > rb->len - rb->offset)
  325. max = rb->len - rb->offset;
  326. }
  327. while (left < n) {
  328. size_t bioread = 0;
  329. int ret;
  330. BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
  331. /*
  332. * Now we have len+left bytes at the front of rl->rbuf.buf and
  333. * need to read in more until we have len + n (up to len + max if
  334. * possible)
  335. */
  336. clear_sys_error();
  337. if (bio != NULL) {
  338. ret = BIO_read(bio, pkt + len + left, max - left);
  339. if (ret > 0) {
  340. bioread = ret;
  341. ret = OSSL_RECORD_RETURN_SUCCESS;
  342. } else if (BIO_should_retry(bio)) {
  343. if (rl->prev != NULL) {
  344. /*
  345. * We were reading from the previous epoch. Now there is no
  346. * more data, so swap to the actual transport BIO
  347. */
  348. BIO_free(rl->prev);
  349. rl->prev = NULL;
  350. continue;
  351. }
  352. ret = OSSL_RECORD_RETURN_RETRY;
  353. } else if (BIO_eof(bio)) {
  354. ret = OSSL_RECORD_RETURN_EOF;
  355. } else {
  356. ret = OSSL_RECORD_RETURN_FATAL;
  357. }
  358. } else {
  359. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
  360. ret = OSSL_RECORD_RETURN_FATAL;
  361. }
  362. if (ret <= OSSL_RECORD_RETURN_RETRY) {
  363. rb->left = left;
  364. if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
  365. if (len + left == 0)
  366. tls_release_read_buffer(rl);
  367. return ret;
  368. }
  369. left += bioread;
  370. /*
  371. * reads should *never* span multiple packets for DTLS because the
  372. * underlying transport protocol is message oriented as opposed to
  373. * byte oriented as in the TLS case.
  374. */
  375. if (rl->isdtls) {
  376. if (n > left)
  377. n = left; /* makes the while condition false */
  378. }
  379. }
  380. /* done reading, now the book-keeping */
  381. rb->offset += n;
  382. rb->left = left - n;
  383. rl->packet_length += n;
  384. *readbytes = n;
  385. return OSSL_RECORD_RETURN_SUCCESS;
  386. }
  387. /*
  388. * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
  389. * for us in the buffer.
  390. */
  391. static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
  392. {
  393. TLS_BUFFER *rbuf;
  394. size_t left, len;
  395. unsigned char *p;
  396. rbuf = &rl->rbuf;
  397. p = TLS_BUFFER_get_buf(rbuf);
  398. if (p == NULL)
  399. return 0;
  400. left = TLS_BUFFER_get_left(rbuf);
  401. if (left < SSL3_RT_HEADER_LENGTH)
  402. return 0;
  403. p += TLS_BUFFER_get_offset(rbuf);
  404. /*
  405. * We only check the type and record length, we will sanity check version
  406. * etc later
  407. */
  408. if (*p != SSL3_RT_APPLICATION_DATA)
  409. return 0;
  410. p += 3;
  411. n2s(p, len);
  412. if (left < SSL3_RT_HEADER_LENGTH + len)
  413. return 0;
  414. return 1;
  415. }
  416. static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
  417. size_t overhead, int send)
  418. {
  419. uint32_t max_early_data = rl->max_early_data;
  420. if (max_early_data == 0) {
  421. RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
  422. SSL_R_TOO_MUCH_EARLY_DATA);
  423. return 0;
  424. }
  425. /* If we are dealing with ciphertext we need to allow for the overhead */
  426. max_early_data += overhead;
  427. if (rl->early_data_count + length > max_early_data) {
  428. RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
  429. SSL_R_TOO_MUCH_EARLY_DATA);
  430. return 0;
  431. }
  432. rl->early_data_count += length;
  433. return 1;
  434. }
  435. /*
  436. * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
  437. * will be processed per call to tls_get_more_records. Without this limit an
  438. * attacker could send empty records at a faster rate than we can process and
  439. * cause tls_get_more_records to loop forever.
  440. */
  441. #define MAX_EMPTY_RECORDS 32
  442. #define SSL2_RT_HEADER_LENGTH 2
  443. /*-
  444. * Call this to buffer new input records in rl->rrec.
  445. * It will return a OSSL_RECORD_RETURN_* value.
  446. * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
  447. * records have been decoded. For each record 'i':
  448. * rrec[i].type - is the type of record
  449. * rrec[i].data, - data
  450. * rrec[i].length, - number of bytes
  451. * Multiple records will only be returned if the record types are all
  452. * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
  453. * |max_pipelines|
  454. */
  455. int tls_get_more_records(OSSL_RECORD_LAYER *rl)
  456. {
  457. int enc_err, rret;
  458. int i;
  459. size_t more, n;
  460. TLS_RL_RECORD *rr, *thisrr;
  461. TLS_BUFFER *rbuf;
  462. unsigned char *p;
  463. unsigned char md[EVP_MAX_MD_SIZE];
  464. unsigned int version;
  465. size_t mac_size = 0;
  466. int imac_size;
  467. size_t num_recs = 0, max_recs, j;
  468. PACKET pkt, sslv2pkt;
  469. SSL_MAC_BUF *macbufs = NULL;
  470. int ret = OSSL_RECORD_RETURN_FATAL;
  471. rr = rl->rrec;
  472. rbuf = &rl->rbuf;
  473. if (rbuf->buf == NULL) {
  474. if (!tls_setup_read_buffer(rl)) {
  475. /* RLAYERfatal() already called */
  476. return OSSL_RECORD_RETURN_FATAL;
  477. }
  478. }
  479. max_recs = rl->max_pipelines;
  480. if (max_recs == 0)
  481. max_recs = 1;
  482. do {
  483. thisrr = &rr[num_recs];
  484. /* check if we have the header */
  485. if ((rl->rstate != SSL_ST_READ_BODY) ||
  486. (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
  487. size_t sslv2len;
  488. unsigned int type;
  489. rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
  490. TLS_BUFFER_get_len(rbuf), 0,
  491. num_recs == 0 ? 1 : 0, &n);
  492. if (rret < OSSL_RECORD_RETURN_SUCCESS)
  493. return rret; /* error or non-blocking */
  494. rl->rstate = SSL_ST_READ_BODY;
  495. p = rl->packet;
  496. if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
  497. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  498. return OSSL_RECORD_RETURN_FATAL;
  499. }
  500. sslv2pkt = pkt;
  501. if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
  502. || !PACKET_get_1(&sslv2pkt, &type)) {
  503. RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
  504. return OSSL_RECORD_RETURN_FATAL;
  505. }
  506. /*
  507. * The first record received by the server may be a V2ClientHello.
  508. */
  509. if (rl->role == OSSL_RECORD_ROLE_SERVER
  510. && rl->is_first_record
  511. && (sslv2len & 0x8000) != 0
  512. && (type == SSL2_MT_CLIENT_HELLO)) {
  513. /*
  514. * SSLv2 style record
  515. *
  516. * |num_recs| here will actually always be 0 because
  517. * |num_recs > 0| only ever occurs when we are processing
  518. * multiple app data records - which we know isn't the case here
  519. * because it is an SSLv2ClientHello. We keep it using
  520. * |num_recs| for the sake of consistency
  521. */
  522. thisrr->type = SSL3_RT_HANDSHAKE;
  523. thisrr->rec_version = SSL2_VERSION;
  524. thisrr->length = sslv2len & 0x7fff;
  525. if (thisrr->length > TLS_BUFFER_get_len(rbuf)
  526. - SSL2_RT_HEADER_LENGTH) {
  527. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
  528. SSL_R_PACKET_LENGTH_TOO_LONG);
  529. return OSSL_RECORD_RETURN_FATAL;
  530. }
  531. } else {
  532. /* SSLv3+ style record */
  533. /* Pull apart the header into the TLS_RL_RECORD */
  534. if (!PACKET_get_1(&pkt, &type)
  535. || !PACKET_get_net_2(&pkt, &version)
  536. || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
  537. if (rl->msg_callback != NULL)
  538. rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
  539. RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
  540. return OSSL_RECORD_RETURN_FATAL;
  541. }
  542. thisrr->type = type;
  543. thisrr->rec_version = version;
  544. /*
  545. * When we call validate_record_header() only records actually
  546. * received in SSLv2 format should have the record version set
  547. * to SSL2_VERSION. This way validate_record_header() can know
  548. * what format the record was in based on the version.
  549. */
  550. if (thisrr->rec_version == SSL2_VERSION) {
  551. RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
  552. SSL_R_WRONG_VERSION_NUMBER);
  553. return OSSL_RECORD_RETURN_FATAL;
  554. }
  555. if (rl->msg_callback != NULL)
  556. rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
  557. if (thisrr->length >
  558. TLS_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
  559. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
  560. SSL_R_PACKET_LENGTH_TOO_LONG);
  561. return OSSL_RECORD_RETURN_FATAL;
  562. }
  563. }
  564. if (!rl->funcs->validate_record_header(rl, thisrr)) {
  565. /* RLAYERfatal already called */
  566. return OSSL_RECORD_RETURN_FATAL;
  567. }
  568. /* now rl->rstate == SSL_ST_READ_BODY */
  569. }
  570. /*
  571. * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
  572. * how much more data we need to read for the rest of the record
  573. */
  574. if (thisrr->rec_version == SSL2_VERSION) {
  575. more = thisrr->length + SSL2_RT_HEADER_LENGTH
  576. - SSL3_RT_HEADER_LENGTH;
  577. } else {
  578. more = thisrr->length;
  579. }
  580. if (more > 0) {
  581. /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
  582. rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
  583. if (rret < OSSL_RECORD_RETURN_SUCCESS)
  584. return rret; /* error or non-blocking io */
  585. }
  586. /* set state for later operations */
  587. rl->rstate = SSL_ST_READ_HEADER;
  588. /*
  589. * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
  590. * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
  591. * + thisrr->length and we have that many bytes in rl->packet
  592. */
  593. if (thisrr->rec_version == SSL2_VERSION)
  594. thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
  595. else
  596. thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
  597. /*
  598. * ok, we can now read from 'rl->packet' data into 'thisrr'.
  599. * thisrr->input points at thisrr->length bytes, which need to be copied
  600. * into thisrr->data by either the decryption or by the decompression.
  601. * When the data is 'copied' into the thisrr->data buffer,
  602. * thisrr->input will be updated to point at the new buffer
  603. */
  604. /*
  605. * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  606. * thisrr->length bytes of encrypted compressed stuff.
  607. */
  608. /* decrypt in place in 'thisrr->input' */
  609. thisrr->data = thisrr->input;
  610. thisrr->orig_len = thisrr->length;
  611. num_recs++;
  612. /* we have pulled in a full packet so zero things */
  613. rl->packet_length = 0;
  614. rl->is_first_record = 0;
  615. } while (num_recs < max_recs
  616. && thisrr->type == SSL3_RT_APPLICATION_DATA
  617. && RLAYER_USE_EXPLICIT_IV(rl)
  618. && rl->enc_ctx != NULL
  619. && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
  620. & EVP_CIPH_FLAG_PIPELINE) != 0
  621. && tls_record_app_data_waiting(rl));
  622. if (num_recs == 1
  623. && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
  624. /* The following can happen in tlsany_meth after HRR */
  625. && rl->version == TLS1_3_VERSION
  626. && rl->is_first_handshake) {
  627. /*
  628. * CCS messages must be exactly 1 byte long, containing the value 0x01
  629. */
  630. if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
  631. RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
  632. SSL_R_INVALID_CCS_MESSAGE);
  633. return OSSL_RECORD_RETURN_FATAL;
  634. }
  635. /*
  636. * CCS messages are ignored in TLSv1.3. We treat it like an empty
  637. * handshake record
  638. */
  639. thisrr->type = SSL3_RT_HANDSHAKE;
  640. if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
  641. RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
  642. SSL_R_UNEXPECTED_CCS_MESSAGE);
  643. return OSSL_RECORD_RETURN_FATAL;
  644. }
  645. rl->num_recs = 0;
  646. rl->curr_rec = 0;
  647. rl->num_released = 0;
  648. return OSSL_RECORD_RETURN_SUCCESS;
  649. }
  650. if (rl->md_ctx != NULL) {
  651. const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
  652. if (tmpmd != NULL) {
  653. imac_size = EVP_MD_get_size(tmpmd);
  654. if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
  655. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  656. return OSSL_RECORD_RETURN_FATAL;
  657. }
  658. mac_size = (size_t)imac_size;
  659. }
  660. }
  661. /*
  662. * If in encrypt-then-mac mode calculate mac from encrypted record. All
  663. * the details below are public so no timing details can leak.
  664. */
  665. if (rl->use_etm && rl->md_ctx != NULL) {
  666. unsigned char *mac;
  667. for (j = 0; j < num_recs; j++) {
  668. thisrr = &rr[j];
  669. if (thisrr->length < mac_size) {
  670. RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
  671. return OSSL_RECORD_RETURN_FATAL;
  672. }
  673. thisrr->length -= mac_size;
  674. mac = thisrr->data + thisrr->length;
  675. i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
  676. if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
  677. RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
  678. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  679. return OSSL_RECORD_RETURN_FATAL;
  680. }
  681. }
  682. /*
  683. * We've handled the mac now - there is no MAC inside the encrypted
  684. * record
  685. */
  686. mac_size = 0;
  687. }
  688. if (mac_size > 0) {
  689. macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
  690. if (macbufs == NULL) {
  691. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
  692. return OSSL_RECORD_RETURN_FATAL;
  693. }
  694. }
  695. ERR_set_mark();
  696. enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
  697. /*-
  698. * enc_err is:
  699. * 0: if the record is publicly invalid, or an internal error, or AEAD
  700. * decryption failed, or ETM decryption failed.
  701. * 1: Success or MTE decryption failed (MAC will be randomised)
  702. */
  703. if (enc_err == 0) {
  704. if (rl->alert != SSL_AD_NO_ALERT) {
  705. /* RLAYERfatal() already got called */
  706. ERR_clear_last_mark();
  707. goto end;
  708. }
  709. if (num_recs == 1
  710. && rl->skip_early_data != NULL
  711. && rl->skip_early_data(rl->cbarg)) {
  712. /*
  713. * Valid early_data that we cannot decrypt will fail here. We treat
  714. * it like an empty record.
  715. */
  716. /*
  717. * Remove any errors from the stack. Decryption failures are normal
  718. * behaviour.
  719. */
  720. ERR_pop_to_mark();
  721. thisrr = &rr[0];
  722. if (!rlayer_early_data_count_ok(rl, thisrr->length,
  723. EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
  724. /* RLAYERfatal() already called */
  725. goto end;
  726. }
  727. thisrr->length = 0;
  728. rl->num_recs = 0;
  729. rl->curr_rec = 0;
  730. rl->num_released = 0;
  731. /* Reset the read sequence */
  732. memset(rl->sequence, 0, sizeof(rl->sequence));
  733. ret = 1;
  734. goto end;
  735. }
  736. ERR_clear_last_mark();
  737. RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
  738. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  739. goto end;
  740. } else {
  741. ERR_clear_last_mark();
  742. }
  743. OSSL_TRACE_BEGIN(TLS) {
  744. BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
  745. BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
  746. } OSSL_TRACE_END(TLS);
  747. /* r->length is now the compressed data plus mac */
  748. if (rl->enc_ctx != NULL
  749. && !rl->use_etm
  750. && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
  751. for (j = 0; j < num_recs; j++) {
  752. SSL_MAC_BUF *thismb = &macbufs[j];
  753. thisrr = &rr[j];
  754. i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
  755. if (i == 0 || thismb == NULL || thismb->mac == NULL
  756. || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
  757. enc_err = 0;
  758. if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
  759. enc_err = 0;
  760. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  761. if (enc_err == 0 && mac_size > 0 && thismb != NULL &&
  762. thismb->mac != NULL && (md[0] ^ thismb->mac[0]) != 0xFF) {
  763. enc_err = 1;
  764. }
  765. #endif
  766. }
  767. }
  768. if (enc_err == 0) {
  769. if (rl->alert != SSL_AD_NO_ALERT) {
  770. /* We already called RLAYERfatal() */
  771. goto end;
  772. }
  773. /*
  774. * A separate 'decryption_failed' alert was introduced with TLS 1.0,
  775. * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
  776. * failure is directly visible from the ciphertext anyway, we should
  777. * not reveal which kind of error occurred -- this might become
  778. * visible to an attacker (e.g. via a logfile)
  779. */
  780. RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
  781. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  782. goto end;
  783. }
  784. for (j = 0; j < num_recs; j++) {
  785. thisrr = &rr[j];
  786. if (!rl->funcs->post_process_record(rl, thisrr)) {
  787. /* RLAYERfatal already called */
  788. goto end;
  789. }
  790. /*
  791. * Record overflow checking (e.g. checking if
  792. * thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) is the responsibility of
  793. * the post_process_record() function above. However we check here if
  794. * the received packet overflows the current Max Fragment Length setting
  795. * if there is one.
  796. * Note: rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH and KTLS are
  797. * mutually exclusive. Also note that with KTLS thisrr->length can
  798. * be > SSL3_RT_MAX_PLAIN_LENGTH (and rl->max_frag_len must be ignored)
  799. */
  800. if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH
  801. && thisrr->length > rl->max_frag_len) {
  802. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
  803. goto end;
  804. }
  805. thisrr->off = 0;
  806. /*-
  807. * So at this point the following is true
  808. * thisrr->type is the type of record
  809. * thisrr->length == number of bytes in record
  810. * thisrr->off == offset to first valid byte
  811. * thisrr->data == where to take bytes from, increment after use :-).
  812. */
  813. /* just read a 0 length packet */
  814. if (thisrr->length == 0) {
  815. if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
  816. RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
  817. SSL_R_RECORD_TOO_SMALL);
  818. goto end;
  819. }
  820. } else {
  821. rl->empty_record_count = 0;
  822. }
  823. }
  824. if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
  825. thisrr = &rr[0];
  826. if (thisrr->type == SSL3_RT_APPLICATION_DATA
  827. && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
  828. /* RLAYERfatal already called */
  829. goto end;
  830. }
  831. }
  832. rl->num_recs = num_recs;
  833. rl->curr_rec = 0;
  834. rl->num_released = 0;
  835. ret = OSSL_RECORD_RETURN_SUCCESS;
  836. end:
  837. if (macbufs != NULL) {
  838. for (j = 0; j < num_recs; j++) {
  839. if (macbufs[j].alloced)
  840. OPENSSL_free(macbufs[j].mac);
  841. }
  842. OPENSSL_free(macbufs);
  843. }
  844. return ret;
  845. }
  846. /* Shared by ssl3_meth and tls1_meth */
  847. int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
  848. {
  849. size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
  850. if (rec->rec_version != rl->version) {
  851. RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
  852. return 0;
  853. }
  854. #ifndef OPENSSL_NO_COMP
  855. /*
  856. * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
  857. * does not include the compression overhead anyway.
  858. */
  859. if (rl->compctx == NULL)
  860. len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
  861. #endif
  862. if (rec->length > len) {
  863. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
  864. SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  865. return 0;
  866. }
  867. return 1;
  868. }
  869. int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr)
  870. {
  871. #ifndef OPENSSL_NO_COMP
  872. int i;
  873. i = COMP_compress_block(rl->compctx, wr->data,
  874. (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
  875. wr->input, (int)wr->length);
  876. if (i < 0)
  877. return 0;
  878. wr->length = i;
  879. wr->input = wr->data;
  880. return 1;
  881. #else
  882. return 0;
  883. #endif
  884. }
  885. int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
  886. {
  887. #ifndef OPENSSL_NO_COMP
  888. int i;
  889. if (rec->comp == NULL) {
  890. rec->comp = (unsigned char *)
  891. OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
  892. }
  893. if (rec->comp == NULL)
  894. return 0;
  895. i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
  896. rec->data, (int)rec->length);
  897. if (i < 0)
  898. return 0;
  899. else
  900. rec->length = i;
  901. rec->data = rec->comp;
  902. return 1;
  903. #else
  904. return 0;
  905. #endif
  906. }
  907. /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
  908. int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
  909. {
  910. if (rl->compctx != NULL) {
  911. if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
  912. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
  913. SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  914. return 0;
  915. }
  916. if (!tls_do_uncompress(rl, rec)) {
  917. RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
  918. SSL_R_BAD_DECOMPRESSION);
  919. return 0;
  920. }
  921. }
  922. if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
  923. RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
  924. return 0;
  925. }
  926. return 1;
  927. }
  928. /* Shared by tls13_meth and ktls_meth */
  929. int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
  930. {
  931. if (rec->type != SSL3_RT_APPLICATION_DATA
  932. && rec->type != SSL3_RT_ALERT
  933. && rec->type != SSL3_RT_HANDSHAKE) {
  934. RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
  935. return 0;
  936. }
  937. if (rl->msg_callback != NULL)
  938. rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
  939. 1, rl->cbarg);
  940. /*
  941. * TLSv1.3 alert and handshake records are required to be non-zero in
  942. * length.
  943. */
  944. if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
  945. && rec->length == 0) {
  946. RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
  947. return 0;
  948. }
  949. return 1;
  950. }
  951. int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
  952. uint8_t *type, const unsigned char **data, size_t *datalen,
  953. uint16_t *epoch, unsigned char *seq_num)
  954. {
  955. TLS_RL_RECORD *rec;
  956. /*
  957. * tls_get_more_records() can return success without actually reading
  958. * anything useful (i.e. if empty records are read). We loop here until
  959. * we have something useful. tls_get_more_records() will eventually fail if
  960. * too many sequential empty records are read.
  961. */
  962. while (rl->curr_rec >= rl->num_recs) {
  963. int ret;
  964. if (rl->num_released != rl->num_recs) {
  965. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
  966. return OSSL_RECORD_RETURN_FATAL;
  967. }
  968. ret = rl->funcs->get_more_records(rl);
  969. if (ret != OSSL_RECORD_RETURN_SUCCESS)
  970. return ret;
  971. }
  972. /*
  973. * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
  974. * points to the next one to read.
  975. */
  976. rec = &rl->rrec[rl->curr_rec++];
  977. *rechandle = rec;
  978. *rversion = rec->rec_version;
  979. *type = rec->type;
  980. *data = rec->data + rec->off;
  981. *datalen = rec->length;
  982. if (rl->isdtls) {
  983. *epoch = rec->epoch;
  984. memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
  985. }
  986. return OSSL_RECORD_RETURN_SUCCESS;
  987. }
  988. int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length)
  989. {
  990. TLS_RL_RECORD *rec = &rl->rrec[rl->num_released];
  991. if (!ossl_assert(rl->num_released < rl->curr_rec)
  992. || !ossl_assert(rechandle == rec)) {
  993. /* Should not happen */
  994. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
  995. return OSSL_RECORD_RETURN_FATAL;
  996. }
  997. if (rec->length < length) {
  998. /* Should not happen */
  999. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1000. return OSSL_RECORD_RETURN_FATAL;
  1001. }
  1002. if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
  1003. OPENSSL_cleanse(rec->data + rec->off, length);
  1004. rec->off += length;
  1005. rec->length -= length;
  1006. if (rec->length > 0)
  1007. return OSSL_RECORD_RETURN_SUCCESS;
  1008. rl->num_released++;
  1009. if (rl->curr_rec == rl->num_released
  1010. && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
  1011. && TLS_BUFFER_get_left(&rl->rbuf) == 0)
  1012. tls_release_read_buffer(rl);
  1013. return OSSL_RECORD_RETURN_SUCCESS;
  1014. }
  1015. int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
  1016. {
  1017. const OSSL_PARAM *p;
  1018. p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
  1019. if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
  1020. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1021. return 0;
  1022. }
  1023. p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
  1024. if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
  1025. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1026. return 0;
  1027. }
  1028. if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
  1029. p = OSSL_PARAM_locate_const(options,
  1030. OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
  1031. if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
  1032. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1033. return 0;
  1034. }
  1035. } else {
  1036. p = OSSL_PARAM_locate_const(options,
  1037. OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
  1038. if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
  1039. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1040. return 0;
  1041. }
  1042. }
  1043. if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
  1044. /*
  1045. * We ignore any read_ahead setting prior to the application protection
  1046. * level. Otherwise we may read ahead data in a lower protection level
  1047. * that is destined for a higher protection level. To simplify the logic
  1048. * we don't support that at this stage.
  1049. */
  1050. p = OSSL_PARAM_locate_const(options,
  1051. OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
  1052. if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
  1053. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1054. return 0;
  1055. }
  1056. }
  1057. return 1;
  1058. }
  1059. int
  1060. tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
  1061. int role, int direction, int level,
  1062. const EVP_CIPHER *ciph, size_t taglen,
  1063. const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
  1064. BIO *transport, BIO *next, const OSSL_PARAM *settings,
  1065. const OSSL_PARAM *options,
  1066. const OSSL_DISPATCH *fns, void *cbarg,
  1067. OSSL_RECORD_LAYER **retrl)
  1068. {
  1069. OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
  1070. const OSSL_PARAM *p;
  1071. *retrl = NULL;
  1072. if (rl == NULL)
  1073. return OSSL_RECORD_RETURN_FATAL;
  1074. /*
  1075. * Default the value for max_frag_len. This may be overridden by the
  1076. * settings
  1077. */
  1078. rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
  1079. /* Loop through all the settings since they must all be understood */
  1080. if (settings != NULL) {
  1081. for (p = settings; p->key != NULL; p++) {
  1082. if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
  1083. if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
  1084. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1085. goto err;
  1086. }
  1087. } else if (strcmp(p->key,
  1088. OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
  1089. if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
  1090. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1091. goto err;
  1092. }
  1093. } else if (strcmp(p->key,
  1094. OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
  1095. if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
  1096. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1097. goto err;
  1098. }
  1099. } else if (strcmp(p->key,
  1100. OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
  1101. if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
  1102. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1103. goto err;
  1104. }
  1105. } else if (strcmp(p->key,
  1106. OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
  1107. if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
  1108. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1109. goto err;
  1110. }
  1111. } else {
  1112. ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
  1113. goto err;
  1114. }
  1115. }
  1116. }
  1117. rl->libctx = libctx;
  1118. rl->propq = propq;
  1119. rl->version = vers;
  1120. rl->role = role;
  1121. rl->direction = direction;
  1122. rl->level = level;
  1123. rl->taglen = taglen;
  1124. rl->md = md;
  1125. rl->alert = SSL_AD_NO_ALERT;
  1126. rl->rstate = SSL_ST_READ_HEADER;
  1127. if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
  1128. rl->is_first_record = 1;
  1129. if (!tls_set1_bio(rl, transport))
  1130. goto err;
  1131. if (prev != NULL && !BIO_up_ref(prev))
  1132. goto err;
  1133. rl->prev = prev;
  1134. if (next != NULL && !BIO_up_ref(next))
  1135. goto err;
  1136. rl->next = next;
  1137. rl->cbarg = cbarg;
  1138. if (fns != NULL) {
  1139. for (; fns->function_id != 0; fns++) {
  1140. switch (fns->function_id) {
  1141. case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
  1142. rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
  1143. break;
  1144. case OSSL_FUNC_RLAYER_MSG_CALLBACK:
  1145. rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
  1146. break;
  1147. case OSSL_FUNC_RLAYER_SECURITY:
  1148. rl->security = OSSL_FUNC_rlayer_security(fns);
  1149. break;
  1150. case OSSL_FUNC_RLAYER_PADDING:
  1151. rl->padding = OSSL_FUNC_rlayer_padding(fns);
  1152. default:
  1153. /* Just ignore anything we don't understand */
  1154. break;
  1155. }
  1156. }
  1157. }
  1158. if (!tls_set_options(rl, options)) {
  1159. ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
  1160. goto err;
  1161. }
  1162. if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
  1163. && rl->version <= TLS1_VERSION
  1164. && !EVP_CIPHER_is_a(ciph, "NULL")
  1165. && !EVP_CIPHER_is_a(ciph, "RC4")) {
  1166. /*
  1167. * Enable vulnerability countermeasure for CBC ciphers with known-IV
  1168. * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
  1169. */
  1170. rl->need_empty_fragments = 1;
  1171. }
  1172. *retrl = rl;
  1173. return OSSL_RECORD_RETURN_SUCCESS;
  1174. err:
  1175. tls_int_free(rl);
  1176. return OSSL_RECORD_RETURN_FATAL;
  1177. }
  1178. static int
  1179. tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
  1180. int role, int direction, int level, uint16_t epoch,
  1181. unsigned char *secret, size_t secretlen,
  1182. unsigned char *key, size_t keylen, unsigned char *iv,
  1183. size_t ivlen, unsigned char *mackey, size_t mackeylen,
  1184. const EVP_CIPHER *ciph, size_t taglen,
  1185. int mactype,
  1186. const EVP_MD *md, COMP_METHOD *comp,
  1187. const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
  1188. BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
  1189. const OSSL_PARAM *settings, const OSSL_PARAM *options,
  1190. const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
  1191. OSSL_RECORD_LAYER **retrl)
  1192. {
  1193. int ret;
  1194. ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
  1195. ciph, taglen, md, comp, prev,
  1196. transport, next, settings,
  1197. options, fns, cbarg, retrl);
  1198. if (ret != OSSL_RECORD_RETURN_SUCCESS)
  1199. return ret;
  1200. switch (vers) {
  1201. case TLS_ANY_VERSION:
  1202. (*retrl)->funcs = &tls_any_funcs;
  1203. break;
  1204. case TLS1_3_VERSION:
  1205. (*retrl)->funcs = &tls_1_3_funcs;
  1206. break;
  1207. case TLS1_2_VERSION:
  1208. case TLS1_1_VERSION:
  1209. case TLS1_VERSION:
  1210. (*retrl)->funcs = &tls_1_funcs;
  1211. break;
  1212. case SSL3_VERSION:
  1213. (*retrl)->funcs = &ssl_3_0_funcs;
  1214. break;
  1215. default:
  1216. /* Should not happen */
  1217. ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
  1218. ret = OSSL_RECORD_RETURN_FATAL;
  1219. goto err;
  1220. }
  1221. ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
  1222. ivlen, mackey, mackeylen, ciph,
  1223. taglen, mactype, md, comp);
  1224. err:
  1225. if (ret != OSSL_RECORD_RETURN_SUCCESS) {
  1226. tls_int_free(*retrl);
  1227. *retrl = NULL;
  1228. }
  1229. return ret;
  1230. }
  1231. static void tls_int_free(OSSL_RECORD_LAYER *rl)
  1232. {
  1233. BIO_free(rl->prev);
  1234. BIO_free(rl->bio);
  1235. BIO_free(rl->next);
  1236. ossl_tls_buffer_release(&rl->rbuf);
  1237. tls_release_write_buffer(rl);
  1238. EVP_CIPHER_CTX_free(rl->enc_ctx);
  1239. EVP_MD_CTX_free(rl->md_ctx);
  1240. #ifndef OPENSSL_NO_COMP
  1241. COMP_CTX_free(rl->compctx);
  1242. #endif
  1243. if (rl->version == SSL3_VERSION)
  1244. OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
  1245. TLS_RL_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
  1246. OPENSSL_free(rl);
  1247. }
  1248. int tls_free(OSSL_RECORD_LAYER *rl)
  1249. {
  1250. TLS_BUFFER *rbuf;
  1251. size_t left, written;
  1252. int ret = 1;
  1253. if (rl == NULL)
  1254. return 1;
  1255. rbuf = &rl->rbuf;
  1256. left = TLS_BUFFER_get_left(rbuf);
  1257. if (left > 0) {
  1258. /*
  1259. * This record layer is closing but we still have data left in our
  1260. * buffer. It must be destined for the next epoch - so push it there.
  1261. */
  1262. ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
  1263. }
  1264. tls_int_free(rl);
  1265. return ret;
  1266. }
  1267. int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
  1268. {
  1269. return TLS_BUFFER_get_left(&rl->rbuf) != 0;
  1270. }
  1271. int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
  1272. {
  1273. return rl->curr_rec < rl->num_recs;
  1274. }
  1275. size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
  1276. {
  1277. size_t i;
  1278. size_t num = 0;
  1279. for (i = rl->curr_rec; i < rl->num_recs; i++) {
  1280. if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
  1281. return num;
  1282. num += rl->rrec[i].length;
  1283. }
  1284. return num;
  1285. }
  1286. size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type,
  1287. size_t len,
  1288. size_t maxfrag, size_t *preffrag)
  1289. {
  1290. /*
  1291. * If we have a pipeline capable cipher, and we have been configured to use
  1292. * it, then return the preferred number of pipelines.
  1293. */
  1294. if (rl->max_pipelines > 0
  1295. && rl->enc_ctx != NULL
  1296. && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
  1297. & EVP_CIPH_FLAG_PIPELINE) != 0
  1298. && RLAYER_USE_EXPLICIT_IV(rl)) {
  1299. size_t pipes;
  1300. if (len == 0)
  1301. return 1;
  1302. pipes = ((len - 1) / *preffrag) + 1;
  1303. return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
  1304. }
  1305. return 1;
  1306. }
  1307. size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
  1308. size_t maxfrag, size_t *preffrag)
  1309. {
  1310. return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
  1311. }
  1312. int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
  1313. OSSL_RECORD_TEMPLATE *templates,
  1314. size_t numtempl,
  1315. size_t *prefix)
  1316. {
  1317. if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
  1318. /* RLAYERfatal() already called */
  1319. return 0;
  1320. }
  1321. return 1;
  1322. }
  1323. int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
  1324. OSSL_RECORD_TEMPLATE *templates,
  1325. size_t numtempl,
  1326. OSSL_RECORD_TEMPLATE *prefixtempl,
  1327. WPACKET *pkt,
  1328. TLS_BUFFER *bufs,
  1329. size_t *wpinited)
  1330. {
  1331. WPACKET *thispkt;
  1332. size_t j, align;
  1333. TLS_BUFFER *wb;
  1334. for (j = 0; j < numtempl; j++) {
  1335. thispkt = &pkt[j];
  1336. wb = &bufs[j];
  1337. wb->type = templates[j].type;
  1338. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
  1339. align = (size_t)TLS_BUFFER_get_buf(wb);
  1340. align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
  1341. align = SSL3_ALIGN_PAYLOAD - 1
  1342. - ((align - 1) % SSL3_ALIGN_PAYLOAD);
  1343. #endif
  1344. TLS_BUFFER_set_offset(wb, align);
  1345. if (!WPACKET_init_static_len(thispkt, TLS_BUFFER_get_buf(wb),
  1346. TLS_BUFFER_get_len(wb), 0)) {
  1347. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1348. return 0;
  1349. }
  1350. (*wpinited)++;
  1351. if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
  1352. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1353. return 0;
  1354. }
  1355. }
  1356. return 1;
  1357. }
  1358. int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
  1359. WPACKET *thispkt,
  1360. OSSL_RECORD_TEMPLATE *templ,
  1361. uint8_t rectype,
  1362. unsigned char **recdata)
  1363. {
  1364. size_t maxcomplen;
  1365. *recdata = NULL;
  1366. maxcomplen = templ->buflen;
  1367. if (rl->compctx != NULL)
  1368. maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
  1369. if (!WPACKET_put_bytes_u8(thispkt, rectype)
  1370. || !WPACKET_put_bytes_u16(thispkt, templ->version)
  1371. || !WPACKET_start_sub_packet_u16(thispkt)
  1372. || (rl->eivlen > 0
  1373. && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
  1374. || (maxcomplen > 0
  1375. && !WPACKET_reserve_bytes(thispkt, maxcomplen,
  1376. recdata))) {
  1377. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1378. return 0;
  1379. }
  1380. return 1;
  1381. }
  1382. int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
  1383. size_t mac_size,
  1384. WPACKET *thispkt,
  1385. TLS_RL_RECORD *thiswr)
  1386. {
  1387. size_t len;
  1388. unsigned char *recordstart;
  1389. /*
  1390. * we should still have the output to thiswr->data and the input from
  1391. * wr->input. Length should be thiswr->length. thiswr->data still points
  1392. * in the wb->buf
  1393. */
  1394. if (!rl->use_etm && mac_size != 0) {
  1395. unsigned char *mac;
  1396. if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
  1397. || !rl->funcs->mac(rl, thiswr, mac, 1)) {
  1398. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1399. return 0;
  1400. }
  1401. }
  1402. /*
  1403. * Reserve some bytes for any growth that may occur during encryption. If
  1404. * we are adding the MAC independently of the cipher algorithm, then the
  1405. * max encrypted overhead does not need to include an allocation for that
  1406. * MAC
  1407. */
  1408. if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
  1409. - mac_size, NULL)
  1410. /*
  1411. * We also need next the amount of bytes written to this
  1412. * sub-packet
  1413. */
  1414. || !WPACKET_get_length(thispkt, &len)) {
  1415. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1416. return 0;
  1417. }
  1418. /* Get a pointer to the start of this record excluding header */
  1419. recordstart = WPACKET_get_curr(thispkt) - len;
  1420. TLS_RL_RECORD_set_data(thiswr, recordstart);
  1421. TLS_RL_RECORD_reset_input(thiswr);
  1422. TLS_RL_RECORD_set_length(thiswr, len);
  1423. return 1;
  1424. }
  1425. int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
  1426. size_t mac_size,
  1427. OSSL_RECORD_TEMPLATE *thistempl,
  1428. WPACKET *thispkt,
  1429. TLS_RL_RECORD *thiswr)
  1430. {
  1431. size_t origlen, len;
  1432. size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
  1433. : SSL3_RT_HEADER_LENGTH;
  1434. /* Allocate bytes for the encryption overhead */
  1435. if (!WPACKET_get_length(thispkt, &origlen)
  1436. /* Check we allowed enough room for the encryption growth */
  1437. || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
  1438. - mac_size >= thiswr->length)
  1439. /* Encryption should never shrink the data! */
  1440. || origlen > thiswr->length
  1441. || (thiswr->length > origlen
  1442. && !WPACKET_allocate_bytes(thispkt,
  1443. thiswr->length - origlen,
  1444. NULL))) {
  1445. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1446. return 0;
  1447. }
  1448. if (rl->use_etm && mac_size != 0) {
  1449. unsigned char *mac;
  1450. if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
  1451. || !rl->funcs->mac(rl, thiswr, mac, 1)) {
  1452. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1453. return 0;
  1454. }
  1455. TLS_RL_RECORD_add_length(thiswr, mac_size);
  1456. }
  1457. if (!WPACKET_get_length(thispkt, &len)
  1458. || !WPACKET_close(thispkt)) {
  1459. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1460. return 0;
  1461. }
  1462. if (rl->msg_callback != NULL) {
  1463. unsigned char *recordstart;
  1464. const int version1_3 = rl->isdtls ? DTLS1_3_VERSION : TLS1_3_VERSION;
  1465. recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
  1466. rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
  1467. headerlen, rl->cbarg);
  1468. if (rl->version == version1_3 && rl->enc_ctx != NULL) {
  1469. unsigned char ctype = thistempl->type;
  1470. rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
  1471. &ctype, 1, rl->cbarg);
  1472. }
  1473. }
  1474. if (!WPACKET_finish(thispkt)) {
  1475. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1476. return 0;
  1477. }
  1478. TLS_RL_RECORD_add_length(thiswr, headerlen);
  1479. return 1;
  1480. }
  1481. int tls_write_records_default(OSSL_RECORD_LAYER *rl,
  1482. OSSL_RECORD_TEMPLATE *templates,
  1483. size_t numtempl)
  1484. {
  1485. WPACKET pkt[SSL_MAX_PIPELINES + 1];
  1486. TLS_RL_RECORD wr[SSL_MAX_PIPELINES + 1];
  1487. WPACKET *thispkt;
  1488. TLS_RL_RECORD *thiswr;
  1489. int mac_size = 0, ret = 0;
  1490. size_t wpinited = 0;
  1491. size_t j, prefix = 0;
  1492. OSSL_RECORD_TEMPLATE prefixtempl;
  1493. OSSL_RECORD_TEMPLATE *thistempl;
  1494. if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
  1495. mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
  1496. if (mac_size < 0) {
  1497. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1498. goto err;
  1499. }
  1500. }
  1501. if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
  1502. /* RLAYERfatal() already called */
  1503. goto err;
  1504. }
  1505. if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
  1506. &prefixtempl, pkt, rl->wbuf,
  1507. &wpinited)) {
  1508. /* RLAYERfatal() already called */
  1509. goto err;
  1510. }
  1511. /* Clear our TLS_RL_RECORD structures */
  1512. memset(wr, 0, sizeof(wr));
  1513. for (j = 0; j < numtempl + prefix; j++) {
  1514. unsigned char *compressdata = NULL;
  1515. uint8_t rectype;
  1516. thispkt = &pkt[j];
  1517. thiswr = &wr[j];
  1518. thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
  1519. /*
  1520. * Default to the record type as specified in the template unless the
  1521. * protocol implementation says differently.
  1522. */
  1523. if (rl->funcs->get_record_type != NULL)
  1524. rectype = rl->funcs->get_record_type(rl, thistempl);
  1525. else
  1526. rectype = thistempl->type;
  1527. TLS_RL_RECORD_set_type(thiswr, rectype);
  1528. TLS_RL_RECORD_set_rec_version(thiswr, thistempl->version);
  1529. if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
  1530. &compressdata)) {
  1531. /* RLAYERfatal() already called */
  1532. goto err;
  1533. }
  1534. /* lets setup the record stuff. */
  1535. TLS_RL_RECORD_set_data(thiswr, compressdata);
  1536. TLS_RL_RECORD_set_length(thiswr, thistempl->buflen);
  1537. TLS_RL_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
  1538. /*
  1539. * we now 'read' from thiswr->input, thiswr->length bytes into
  1540. * thiswr->data
  1541. */
  1542. /* first we compress */
  1543. if (rl->compctx != NULL) {
  1544. if (!tls_do_compress(rl, thiswr)
  1545. || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
  1546. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
  1547. goto err;
  1548. }
  1549. } else if (compressdata != NULL) {
  1550. if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
  1551. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1552. goto err;
  1553. }
  1554. TLS_RL_RECORD_reset_input(&wr[j]);
  1555. }
  1556. if (rl->funcs->add_record_padding != NULL
  1557. && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
  1558. thiswr)) {
  1559. /* RLAYERfatal() already called */
  1560. goto err;
  1561. }
  1562. if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
  1563. /* RLAYERfatal() already called */
  1564. goto err;
  1565. }
  1566. }
  1567. if (prefix) {
  1568. if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
  1569. if (rl->alert == SSL_AD_NO_ALERT) {
  1570. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1571. }
  1572. goto err;
  1573. }
  1574. }
  1575. if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
  1576. if (rl->alert == SSL_AD_NO_ALERT) {
  1577. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1578. }
  1579. goto err;
  1580. }
  1581. for (j = 0; j < numtempl + prefix; j++) {
  1582. thispkt = &pkt[j];
  1583. thiswr = &wr[j];
  1584. thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
  1585. if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
  1586. thispkt, thiswr)) {
  1587. /* RLAYERfatal() already called */
  1588. goto err;
  1589. }
  1590. /* now let's set up wb */
  1591. TLS_BUFFER_set_left(&rl->wbuf[j], TLS_RL_RECORD_get_length(thiswr));
  1592. }
  1593. ret = 1;
  1594. err:
  1595. for (j = 0; j < wpinited; j++)
  1596. WPACKET_cleanup(&pkt[j]);
  1597. return ret;
  1598. }
  1599. int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
  1600. size_t numtempl)
  1601. {
  1602. /* Check we don't have pending data waiting to write */
  1603. if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
  1604. || TLS_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
  1605. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1606. return OSSL_RECORD_RETURN_FATAL;
  1607. }
  1608. if (!rl->funcs->write_records(rl, templates, numtempl)) {
  1609. /* RLAYERfatal already called */
  1610. return OSSL_RECORD_RETURN_FATAL;
  1611. }
  1612. rl->nextwbuf = 0;
  1613. /* we now just need to write the buffers */
  1614. return tls_retry_write_records(rl);
  1615. }
  1616. int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
  1617. {
  1618. int i, ret;
  1619. TLS_BUFFER *thiswb;
  1620. size_t tmpwrit = 0;
  1621. if (rl->nextwbuf >= rl->numwpipes)
  1622. return OSSL_RECORD_RETURN_SUCCESS;
  1623. for (;;) {
  1624. thiswb = &rl->wbuf[rl->nextwbuf];
  1625. clear_sys_error();
  1626. if (rl->bio != NULL) {
  1627. if (rl->funcs->prepare_write_bio != NULL) {
  1628. ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
  1629. if (ret != OSSL_RECORD_RETURN_SUCCESS)
  1630. return ret;
  1631. }
  1632. i = BIO_write(rl->bio, (char *)
  1633. &(TLS_BUFFER_get_buf(thiswb)
  1634. [TLS_BUFFER_get_offset(thiswb)]),
  1635. (unsigned int)TLS_BUFFER_get_left(thiswb));
  1636. if (i >= 0) {
  1637. tmpwrit = i;
  1638. if (i == 0 && BIO_should_retry(rl->bio))
  1639. ret = OSSL_RECORD_RETURN_RETRY;
  1640. else
  1641. ret = OSSL_RECORD_RETURN_SUCCESS;
  1642. } else {
  1643. if (BIO_should_retry(rl->bio))
  1644. ret = OSSL_RECORD_RETURN_RETRY;
  1645. else
  1646. ret = OSSL_RECORD_RETURN_FATAL;
  1647. }
  1648. } else {
  1649. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
  1650. ret = OSSL_RECORD_RETURN_FATAL;
  1651. i = -1;
  1652. }
  1653. /*
  1654. * When an empty fragment is sent on a connection using KTLS,
  1655. * it is sent as a write of zero bytes. If this zero byte
  1656. * write succeeds, i will be 0 rather than a non-zero value.
  1657. * Treat i == 0 as success rather than an error for zero byte
  1658. * writes to permit this case.
  1659. */
  1660. if (i >= 0 && tmpwrit == TLS_BUFFER_get_left(thiswb)) {
  1661. TLS_BUFFER_set_left(thiswb, 0);
  1662. TLS_BUFFER_add_offset(thiswb, tmpwrit);
  1663. if (++(rl->nextwbuf) < rl->numwpipes)
  1664. continue;
  1665. if (rl->nextwbuf == rl->numwpipes
  1666. && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
  1667. tls_release_write_buffer(rl);
  1668. return OSSL_RECORD_RETURN_SUCCESS;
  1669. } else if (i <= 0) {
  1670. if (rl->isdtls) {
  1671. /*
  1672. * For DTLS, just drop it. That's kind of the whole point in
  1673. * using a datagram service
  1674. */
  1675. TLS_BUFFER_set_left(thiswb, 0);
  1676. if (++(rl->nextwbuf) == rl->numwpipes
  1677. && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
  1678. tls_release_write_buffer(rl);
  1679. }
  1680. return ret;
  1681. }
  1682. TLS_BUFFER_add_offset(thiswb, tmpwrit);
  1683. TLS_BUFFER_sub_left(thiswb, tmpwrit);
  1684. }
  1685. }
  1686. int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
  1687. {
  1688. return rl->alert;
  1689. }
  1690. int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
  1691. {
  1692. if (bio != NULL && !BIO_up_ref(bio))
  1693. return 0;
  1694. BIO_free(rl->bio);
  1695. rl->bio = bio;
  1696. return 1;
  1697. }
  1698. /* Shared by most methods except tlsany_meth */
  1699. int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
  1700. {
  1701. if (rl->version != version)
  1702. return 0;
  1703. return 1;
  1704. }
  1705. int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
  1706. {
  1707. return rl->funcs->set_protocol_version(rl, version);
  1708. }
  1709. void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
  1710. {
  1711. rl->allow_plain_alerts = allow;
  1712. }
  1713. void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
  1714. {
  1715. rl->is_first_handshake = first;
  1716. }
  1717. void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
  1718. {
  1719. rl->max_pipelines = max_pipelines;
  1720. if (max_pipelines > 1)
  1721. rl->read_ahead = 1;
  1722. }
  1723. void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
  1724. const char **longstr)
  1725. {
  1726. const char *shrt, *lng;
  1727. switch (rl->rstate) {
  1728. case SSL_ST_READ_HEADER:
  1729. shrt = "RH";
  1730. lng = "read header";
  1731. break;
  1732. case SSL_ST_READ_BODY:
  1733. shrt = "RB";
  1734. lng = "read body";
  1735. break;
  1736. default:
  1737. shrt = lng = "unknown";
  1738. break;
  1739. }
  1740. if (shortstr != NULL)
  1741. *shortstr = shrt;
  1742. if (longstr != NULL)
  1743. *longstr = lng;
  1744. }
  1745. const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
  1746. {
  1747. #ifndef OPENSSL_NO_COMP
  1748. return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
  1749. #else
  1750. return NULL;
  1751. #endif
  1752. }
  1753. void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
  1754. {
  1755. rl->max_frag_len = max_frag_len;
  1756. /*
  1757. * We don't need to adjust buffer sizes. Write buffer sizes are
  1758. * automatically checked anyway. We should only be changing the read buffer
  1759. * size during the handshake, so we will create a new buffer when we create
  1760. * the new record layer. We can't change the existing buffer because it may
  1761. * already have data in it.
  1762. */
  1763. }
  1764. int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
  1765. {
  1766. int i;
  1767. /* Increment the sequence counter */
  1768. for (i = SEQ_NUM_SIZE; i > 0; i--) {
  1769. ++(rl->sequence[i - 1]);
  1770. if (rl->sequence[i - 1] != 0)
  1771. break;
  1772. }
  1773. if (i == 0) {
  1774. /* Sequence has wrapped */
  1775. RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
  1776. return 0;
  1777. }
  1778. return 1;
  1779. }
  1780. int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
  1781. {
  1782. if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
  1783. /* If we have a pending write then buffers are already allocated */
  1784. if (rl->nextwbuf < rl->numwpipes)
  1785. return 1;
  1786. /*
  1787. * We assume 1 pipe with default sized buffer. If what we need ends up
  1788. * being a different size to that then it will be reallocated on demand.
  1789. * If we need more than 1 pipe then that will also be allocated on
  1790. * demand
  1791. */
  1792. if (!tls_setup_write_buffer(rl, 1, 0, 0))
  1793. return 0;
  1794. /*
  1795. * Normally when we allocate write buffers we immediately write
  1796. * something into it. In this case we're not doing that so mark the
  1797. * buffer as empty.
  1798. */
  1799. TLS_BUFFER_set_left(&rl->wbuf[0], 0);
  1800. return 1;
  1801. }
  1802. /* Read direction */
  1803. /* If we have pending data to be read then buffers are already allocated */
  1804. if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
  1805. return 1;
  1806. return tls_setup_read_buffer(rl);
  1807. }
  1808. int tls_free_buffers(OSSL_RECORD_LAYER *rl)
  1809. {
  1810. if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
  1811. if (rl->nextwbuf < rl->numwpipes) {
  1812. /*
  1813. * We may have pending data. If we've just got one empty buffer
  1814. * allocated then it has probably just been alloc'd via
  1815. * tls_alloc_buffers, and it is fine to free it. Otherwise this
  1816. * looks like real pending data and it is an error.
  1817. */
  1818. if (rl->nextwbuf != 0
  1819. || rl->numwpipes != 1
  1820. || TLS_BUFFER_get_left(&rl->wbuf[0]) != 0)
  1821. return 0;
  1822. }
  1823. tls_release_write_buffer(rl);
  1824. return 1;
  1825. }
  1826. /* Read direction */
  1827. /* If we have pending data to be read then fail */
  1828. if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
  1829. return 0;
  1830. return tls_release_read_buffer(rl);
  1831. }
  1832. const OSSL_RECORD_METHOD ossl_tls_record_method = {
  1833. tls_new_record_layer,
  1834. tls_free,
  1835. tls_unprocessed_read_pending,
  1836. tls_processed_read_pending,
  1837. tls_app_data_pending,
  1838. tls_get_max_records,
  1839. tls_write_records,
  1840. tls_retry_write_records,
  1841. tls_read_record,
  1842. tls_release_record,
  1843. tls_get_alert_code,
  1844. tls_set1_bio,
  1845. tls_set_protocol_version,
  1846. tls_set_plain_alerts,
  1847. tls_set_first_handshake,
  1848. tls_set_max_pipelines,
  1849. NULL,
  1850. tls_get_state,
  1851. tls_set_options,
  1852. tls_get_compression,
  1853. tls_set_max_frag_len,
  1854. NULL,
  1855. tls_increment_sequence_ctr,
  1856. tls_alloc_buffers,
  1857. tls_free_buffers
  1858. };