ssl3_record.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. /* ssl/record/ssl3_record.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* ====================================================================
  59. * Copyright (c) 1998-2015 The OpenSSL Project. All rights reserved.
  60. *
  61. * Redistribution and use in source and binary forms, with or without
  62. * modification, are permitted provided that the following conditions
  63. * are met:
  64. *
  65. * 1. Redistributions of source code must retain the above copyright
  66. * notice, this list of conditions and the following disclaimer.
  67. *
  68. * 2. Redistributions in binary form must reproduce the above copyright
  69. * notice, this list of conditions and the following disclaimer in
  70. * the documentation and/or other materials provided with the
  71. * distribution.
  72. *
  73. * 3. All advertising materials mentioning features or use of this
  74. * software must display the following acknowledgment:
  75. * "This product includes software developed by the OpenSSL Project
  76. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  77. *
  78. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  79. * endorse or promote products derived from this software without
  80. * prior written permission. For written permission, please contact
  81. * openssl-core@openssl.org.
  82. *
  83. * 5. Products derived from this software may not be called "OpenSSL"
  84. * nor may "OpenSSL" appear in their names without prior written
  85. * permission of the OpenSSL Project.
  86. *
  87. * 6. Redistributions of any form whatsoever must retain the following
  88. * acknowledgment:
  89. * "This product includes software developed by the OpenSSL Project
  90. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  91. *
  92. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  93. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  95. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  96. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  97. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  98. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  99. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  100. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  101. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  102. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  103. * OF THE POSSIBILITY OF SUCH DAMAGE.
  104. * ====================================================================
  105. *
  106. * This product includes cryptographic software written by Eric Young
  107. * (eay@cryptsoft.com). This product includes software written by Tim
  108. * Hudson (tjh@cryptsoft.com).
  109. *
  110. */
  111. #include "../ssl_locl.h"
  112. #include "internal/constant_time_locl.h"
  113. #include <openssl/rand.h>
  114. #include "record_locl.h"
  115. static const unsigned char ssl3_pad_1[48] = {
  116. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  117. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  118. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  119. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  120. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  121. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
  122. };
  123. static const unsigned char ssl3_pad_2[48] = {
  124. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  125. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  126. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  127. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  128. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  129. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
  130. };
  131. /*
  132. * Clear the contents of an SSL3_RECORD but retain any memory allocated
  133. */
  134. void SSL3_RECORD_clear(SSL3_RECORD *r)
  135. {
  136. unsigned char *comp = r->comp;
  137. memset(r, 0, sizeof(*r));
  138. r->comp = comp;
  139. }
  140. void SSL3_RECORD_release(SSL3_RECORD *r)
  141. {
  142. OPENSSL_free(r->comp);
  143. r->comp = NULL;
  144. }
  145. int SSL3_RECORD_setup(SSL3_RECORD *r)
  146. {
  147. if (r->comp == NULL)
  148. r->comp = (unsigned char *)
  149. OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
  150. if (r->comp == NULL)
  151. return 0;
  152. return 1;
  153. }
  154. void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
  155. {
  156. memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
  157. }
  158. /*
  159. * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
  160. * will be processed per call to ssl3_get_record. Without this limit an
  161. * attacker could send empty records at a faster rate than we can process and
  162. * cause ssl3_get_record to loop forever.
  163. */
  164. #define MAX_EMPTY_RECORDS 32
  165. #define SSL2_RT_HEADER_LENGTH 2
  166. /*-
  167. * Call this to get a new input record.
  168. * It will return <= 0 if more data is needed, normally due to an error
  169. * or non-blocking IO.
  170. * When it finishes, one packet has been decoded and can be found in
  171. * ssl->s3->rrec.type - is the type of record
  172. * ssl->s3->rrec.data, - data
  173. * ssl->s3->rrec.length, - number of bytes
  174. */
  175. /* used only by ssl3_read_bytes */
  176. int ssl3_get_record(SSL *s)
  177. {
  178. int ssl_major, ssl_minor, al;
  179. int enc_err, n, i, ret = -1;
  180. SSL3_RECORD *rr;
  181. SSL_SESSION *sess;
  182. unsigned char *p;
  183. unsigned char md[EVP_MAX_MD_SIZE];
  184. short version;
  185. unsigned mac_size;
  186. unsigned empty_record_count = 0;
  187. rr = RECORD_LAYER_get_rrec(&s->rlayer);
  188. sess = s->session;
  189. again:
  190. /* check if we have the header */
  191. if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
  192. (RECORD_LAYER_get_packet_length(&s->rlayer) < SSL3_RT_HEADER_LENGTH)) {
  193. n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
  194. SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
  195. if (n <= 0)
  196. return (n); /* error or non-blocking */
  197. RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
  198. p = RECORD_LAYER_get_packet(&s->rlayer);
  199. /*
  200. * Check whether this is a regular record or an SSLv2 style record. The
  201. * latter is only used in an initial ClientHello for old clients. We
  202. * check s->read_hash and s->enc_read_ctx to ensure this does not apply
  203. * during renegotiation
  204. */
  205. if (s->first_packet && s->server && !s->read_hash && !s->enc_read_ctx
  206. && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
  207. /* SSLv2 style record */
  208. rr->type = SSL3_RT_HANDSHAKE;
  209. rr->rec_version = SSL2_VERSION;
  210. rr->length = ((p[0] & 0x7f) << 8) | p[1];
  211. if (rr->length > SSL3_BUFFER_get_len(&s->rlayer.rbuf)
  212. - SSL2_RT_HEADER_LENGTH) {
  213. al = SSL_AD_RECORD_OVERFLOW;
  214. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
  215. goto f_err;
  216. }
  217. if (rr->length < MIN_SSL2_RECORD_LEN) {
  218. al = SSL_AD_HANDSHAKE_FAILURE;
  219. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
  220. goto f_err;
  221. }
  222. } else {
  223. /* SSLv3+ style record */
  224. if (s->msg_callback)
  225. s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
  226. s->msg_callback_arg);
  227. /* Pull apart the header into the SSL3_RECORD */
  228. rr->type = *(p++);
  229. ssl_major = *(p++);
  230. ssl_minor = *(p++);
  231. version = (ssl_major << 8) | ssl_minor;
  232. rr->rec_version = version;
  233. n2s(p, rr->length);
  234. /* Lets check version */
  235. if (!s->first_packet && version != s->version) {
  236. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  237. if ((s->version & 0xFF00) == (version & 0xFF00)
  238. && !s->enc_write_ctx && !s->write_hash) {
  239. if (rr->type == SSL3_RT_ALERT) {
  240. /*
  241. * The record is using an incorrect version number, but
  242. * what we've got appears to be an alert. We haven't
  243. * read the body yet to check whether its a fatal or
  244. * not - but chances are it is. We probably shouldn't
  245. * send a fatal alert back. We'll just end.
  246. */
  247. goto err;
  248. }
  249. /*
  250. * Send back error using their minor version number :-)
  251. */
  252. s->version = (unsigned short)version;
  253. }
  254. al = SSL_AD_PROTOCOL_VERSION;
  255. goto f_err;
  256. }
  257. if ((version >> 8) != SSL3_VERSION_MAJOR) {
  258. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  259. goto err;
  260. }
  261. if (rr->length >
  262. SSL3_BUFFER_get_len(&s->rlayer.rbuf)
  263. - SSL3_RT_HEADER_LENGTH) {
  264. al = SSL_AD_RECORD_OVERFLOW;
  265. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
  266. goto f_err;
  267. }
  268. }
  269. /* now s->rlayer.rstate == SSL_ST_READ_BODY */
  270. }
  271. /*
  272. * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
  273. * Calculate how much more data we need to read for the rest of the record
  274. */
  275. if (rr->rec_version == SSL2_VERSION) {
  276. i = rr->length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH;
  277. } else {
  278. i = rr->length;
  279. }
  280. if (i > 0) {
  281. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  282. n = ssl3_read_n(s, i, i, 1);
  283. if (n <= 0)
  284. return (n); /* error or non-blocking io */
  285. }
  286. /* set state for later operations */
  287. RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
  288. /*
  289. * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
  290. * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
  291. * and we have that many bytes in s->packet
  292. */
  293. if(rr->rec_version == SSL2_VERSION) {
  294. rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
  295. } else {
  296. rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
  297. }
  298. /*
  299. * ok, we can now read from 's->packet' data into 'rr' rr->input points
  300. * at rr->length bytes, which need to be copied into rr->data by either
  301. * the decryption or by the decompression When the data is 'copied' into
  302. * the rr->data buffer, rr->input will be pointed at the new buffer
  303. */
  304. /*
  305. * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
  306. * bytes of encrypted compressed stuff.
  307. */
  308. /* check is not needed I believe */
  309. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  310. al = SSL_AD_RECORD_OVERFLOW;
  311. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  312. goto f_err;
  313. }
  314. /* decrypt in place in 'rr->input' */
  315. rr->data = rr->input;
  316. rr->orig_len = rr->length;
  317. /*
  318. * If in encrypt-then-mac mode calculate mac from encrypted record. All
  319. * the details below are public so no timing details can leak.
  320. */
  321. if (SSL_USE_ETM(s) && s->read_hash) {
  322. unsigned char *mac;
  323. mac_size = EVP_MD_CTX_size(s->read_hash);
  324. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  325. if (rr->length < mac_size) {
  326. al = SSL_AD_DECODE_ERROR;
  327. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
  328. goto f_err;
  329. }
  330. rr->length -= mac_size;
  331. mac = rr->data + rr->length;
  332. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  333. if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
  334. al = SSL_AD_BAD_RECORD_MAC;
  335. SSLerr(SSL_F_SSL3_GET_RECORD,
  336. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  337. goto f_err;
  338. }
  339. }
  340. enc_err = s->method->ssl3_enc->enc(s, 0);
  341. /*-
  342. * enc_err is:
  343. * 0: (in non-constant time) if the record is publically invalid.
  344. * 1: if the padding is valid
  345. * -1: if the padding is invalid
  346. */
  347. if (enc_err == 0) {
  348. al = SSL_AD_DECRYPTION_FAILED;
  349. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
  350. goto f_err;
  351. }
  352. #ifdef TLS_DEBUG
  353. printf("dec %d\n", rr->length);
  354. {
  355. unsigned int z;
  356. for (z = 0; z < rr->length; z++)
  357. printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
  358. }
  359. printf("\n");
  360. #endif
  361. /* r->length is now the compressed data plus mac */
  362. if ((sess != NULL) &&
  363. (s->enc_read_ctx != NULL) &&
  364. (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
  365. /* s->read_hash != NULL => mac_size != -1 */
  366. unsigned char *mac = NULL;
  367. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  368. mac_size = EVP_MD_CTX_size(s->read_hash);
  369. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  370. /*
  371. * orig_len is the length of the record before any padding was
  372. * removed. This is public information, as is the MAC in use,
  373. * therefore we can safely process the record in a different amount
  374. * of time if it's too short to possibly contain a MAC.
  375. */
  376. if (rr->orig_len < mac_size ||
  377. /* CBC records must have a padding length byte too. */
  378. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  379. rr->orig_len < mac_size + 1)) {
  380. al = SSL_AD_DECODE_ERROR;
  381. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
  382. goto f_err;
  383. }
  384. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
  385. /*
  386. * We update the length so that the TLS header bytes can be
  387. * constructed correctly but we need to extract the MAC in
  388. * constant time from within the record, without leaking the
  389. * contents of the padding bytes.
  390. */
  391. mac = mac_tmp;
  392. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
  393. rr->length -= mac_size;
  394. } else {
  395. /*
  396. * In this case there's no padding, so |rec->orig_len| equals
  397. * |rec->length| and we checked that there's enough bytes for
  398. * |mac_size| above.
  399. */
  400. rr->length -= mac_size;
  401. mac = &rr->data[rr->length];
  402. }
  403. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  404. if (i < 0 || mac == NULL
  405. || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  406. enc_err = -1;
  407. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
  408. enc_err = -1;
  409. }
  410. if (enc_err < 0) {
  411. /*
  412. * A separate 'decryption_failed' alert was introduced with TLS 1.0,
  413. * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
  414. * failure is directly visible from the ciphertext anyway, we should
  415. * not reveal which kind of error occurred -- this might become
  416. * visible to an attacker (e.g. via a logfile)
  417. */
  418. al = SSL_AD_BAD_RECORD_MAC;
  419. SSLerr(SSL_F_SSL3_GET_RECORD,
  420. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  421. goto f_err;
  422. }
  423. /* r->length is now just compressed */
  424. if (s->expand != NULL) {
  425. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
  426. al = SSL_AD_RECORD_OVERFLOW;
  427. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  428. goto f_err;
  429. }
  430. if (!ssl3_do_uncompress(s)) {
  431. al = SSL_AD_DECOMPRESSION_FAILURE;
  432. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
  433. goto f_err;
  434. }
  435. }
  436. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
  437. al = SSL_AD_RECORD_OVERFLOW;
  438. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
  439. goto f_err;
  440. }
  441. rr->off = 0;
  442. /*-
  443. * So at this point the following is true
  444. * ssl->s3->rrec.type is the type of record
  445. * ssl->s3->rrec.length == number of bytes in record
  446. * ssl->s3->rrec.off == offset to first valid byte
  447. * ssl->s3->rrec.data == where to take bytes from, increment
  448. * after use :-).
  449. */
  450. /* we have pulled in a full packet so zero things */
  451. RECORD_LAYER_reset_packet_length(&s->rlayer);
  452. /* just read a 0 length packet */
  453. if (rr->length == 0) {
  454. empty_record_count++;
  455. if (empty_record_count > MAX_EMPTY_RECORDS) {
  456. al = SSL_AD_UNEXPECTED_MESSAGE;
  457. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
  458. goto f_err;
  459. }
  460. goto again;
  461. }
  462. return (1);
  463. f_err:
  464. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  465. err:
  466. return (ret);
  467. }
  468. int ssl3_do_uncompress(SSL *ssl)
  469. {
  470. #ifndef OPENSSL_NO_COMP
  471. int i;
  472. SSL3_RECORD *rr;
  473. rr = RECORD_LAYER_get_rrec(&ssl->rlayer);
  474. i = COMP_expand_block(ssl->expand, rr->comp,
  475. SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
  476. (int)rr->length);
  477. if (i < 0)
  478. return (0);
  479. else
  480. rr->length = i;
  481. rr->data = rr->comp;
  482. #endif
  483. return (1);
  484. }
  485. int ssl3_do_compress(SSL *ssl)
  486. {
  487. #ifndef OPENSSL_NO_COMP
  488. int i;
  489. SSL3_RECORD *wr;
  490. wr = RECORD_LAYER_get_wrec(&ssl->rlayer);
  491. i = COMP_compress_block(ssl->compress, wr->data,
  492. SSL3_RT_MAX_COMPRESSED_LENGTH,
  493. wr->input, (int)wr->length);
  494. if (i < 0)
  495. return (0);
  496. else
  497. wr->length = i;
  498. wr->input = wr->data;
  499. #endif
  500. return (1);
  501. }
  502. /*-
  503. * ssl3_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
  504. *
  505. * Returns:
  506. * 0: (in non-constant time) if the record is publically invalid (i.e. too
  507. * short etc).
  508. * 1: if the record's padding is valid / the encryption was successful.
  509. * -1: if the record's padding is invalid or, if sending, an internal error
  510. * occurred.
  511. */
  512. int ssl3_enc(SSL *s, int send)
  513. {
  514. SSL3_RECORD *rec;
  515. EVP_CIPHER_CTX *ds;
  516. unsigned long l;
  517. int bs, i, mac_size = 0;
  518. const EVP_CIPHER *enc;
  519. if (send) {
  520. ds = s->enc_write_ctx;
  521. rec = RECORD_LAYER_get_wrec(&s->rlayer);
  522. if (s->enc_write_ctx == NULL)
  523. enc = NULL;
  524. else
  525. enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
  526. } else {
  527. ds = s->enc_read_ctx;
  528. rec = RECORD_LAYER_get_rrec(&s->rlayer);
  529. if (s->enc_read_ctx == NULL)
  530. enc = NULL;
  531. else
  532. enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
  533. }
  534. if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
  535. memmove(rec->data, rec->input, rec->length);
  536. rec->input = rec->data;
  537. } else {
  538. l = rec->length;
  539. bs = EVP_CIPHER_CTX_block_size(ds);
  540. /* COMPRESS */
  541. if ((bs != 1) && send) {
  542. i = bs - ((int)l % bs);
  543. /* we need to add 'i-1' padding bytes */
  544. l += i;
  545. /*
  546. * the last of these zero bytes will be overwritten with the
  547. * padding length.
  548. */
  549. memset(&rec->input[rec->length], 0, i);
  550. rec->length += i;
  551. rec->input[l - 1] = (i - 1);
  552. }
  553. if (!send) {
  554. if (l == 0 || l % bs != 0)
  555. return 0;
  556. /* otherwise, rec->length >= bs */
  557. }
  558. if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
  559. return -1;
  560. if (EVP_MD_CTX_md(s->read_hash) != NULL)
  561. mac_size = EVP_MD_CTX_size(s->read_hash);
  562. if ((bs != 1) && !send)
  563. return ssl3_cbc_remove_padding(s, rec, bs, mac_size);
  564. }
  565. return (1);
  566. }
  567. /*-
  568. * tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
  569. *
  570. * Returns:
  571. * 0: (in non-constant time) if the record is publically invalid (i.e. too
  572. * short etc).
  573. * 1: if the record's padding is valid / the encryption was successful.
  574. * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
  575. * an internal error occurred.
  576. */
  577. int tls1_enc(SSL *s, int send)
  578. {
  579. SSL3_RECORD *rec;
  580. EVP_CIPHER_CTX *ds;
  581. unsigned long l;
  582. int bs, i, j, k, pad = 0, ret, mac_size = 0;
  583. const EVP_CIPHER *enc;
  584. if (send) {
  585. if (EVP_MD_CTX_md(s->write_hash)) {
  586. int n = EVP_MD_CTX_size(s->write_hash);
  587. OPENSSL_assert(n >= 0);
  588. }
  589. ds = s->enc_write_ctx;
  590. rec = RECORD_LAYER_get_wrec(&s->rlayer);
  591. if (s->enc_write_ctx == NULL)
  592. enc = NULL;
  593. else {
  594. int ivlen;
  595. enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
  596. /* For TLSv1.1 and later explicit IV */
  597. if (SSL_USE_EXPLICIT_IV(s)
  598. && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
  599. ivlen = EVP_CIPHER_iv_length(enc);
  600. else
  601. ivlen = 0;
  602. if (ivlen > 1) {
  603. if (rec->data != rec->input)
  604. /*
  605. * we can't write into the input stream: Can this ever
  606. * happen?? (steve)
  607. */
  608. fprintf(stderr,
  609. "%s:%d: rec->data != rec->input\n",
  610. __FILE__, __LINE__);
  611. else if (RAND_bytes(rec->input, ivlen) <= 0)
  612. return -1;
  613. }
  614. }
  615. } else {
  616. if (EVP_MD_CTX_md(s->read_hash)) {
  617. int n = EVP_MD_CTX_size(s->read_hash);
  618. OPENSSL_assert(n >= 0);
  619. }
  620. ds = s->enc_read_ctx;
  621. rec = RECORD_LAYER_get_rrec(&s->rlayer);
  622. if (s->enc_read_ctx == NULL)
  623. enc = NULL;
  624. else
  625. enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
  626. }
  627. if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
  628. memmove(rec->data, rec->input, rec->length);
  629. rec->input = rec->data;
  630. ret = 1;
  631. } else {
  632. l = rec->length;
  633. bs = EVP_CIPHER_CTX_block_size(ds);
  634. if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
  635. unsigned char buf[EVP_AEAD_TLS1_AAD_LEN], *seq;
  636. seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
  637. : RECORD_LAYER_get_read_sequence(&s->rlayer);
  638. if (SSL_IS_DTLS(s)) {
  639. unsigned char dtlsseq[9], *p = dtlsseq;
  640. s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
  641. DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
  642. memcpy(p, &seq[2], 6);
  643. memcpy(buf, dtlsseq, 8);
  644. } else {
  645. memcpy(buf, seq, 8);
  646. for (i = 7; i >= 0; i--) { /* increment */
  647. ++seq[i];
  648. if (seq[i] != 0)
  649. break;
  650. }
  651. }
  652. buf[8] = rec->type;
  653. buf[9] = (unsigned char)(s->version >> 8);
  654. buf[10] = (unsigned char)(s->version);
  655. buf[11] = rec->length >> 8;
  656. buf[12] = rec->length & 0xff;
  657. pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  658. EVP_AEAD_TLS1_AAD_LEN, buf);
  659. if (pad <= 0)
  660. return -1;
  661. if (send) {
  662. l += pad;
  663. rec->length += pad;
  664. }
  665. } else if ((bs != 1) && send) {
  666. i = bs - ((int)l % bs);
  667. /* Add weird padding of upto 256 bytes */
  668. /* we need to add 'i' padding bytes of value j */
  669. j = i - 1;
  670. for (k = (int)l; k < (int)(l + i); k++)
  671. rec->input[k] = j;
  672. l += i;
  673. rec->length += i;
  674. }
  675. if (!send) {
  676. if (l == 0 || l % bs != 0)
  677. return 0;
  678. }
  679. i = EVP_Cipher(ds, rec->data, rec->input, l);
  680. if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds)) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
  681. ? (i < 0)
  682. : (i == 0))
  683. return -1; /* AEAD can fail to verify MAC */
  684. if (send == 0) {
  685. if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
  686. rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  687. rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  688. rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
  689. } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
  690. rec->data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
  691. rec->input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
  692. rec->length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
  693. }
  694. }
  695. ret = 1;
  696. if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
  697. mac_size = EVP_MD_CTX_size(s->read_hash);
  698. if ((bs != 1) && !send)
  699. ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
  700. if (pad && !send)
  701. rec->length -= pad;
  702. }
  703. return ret;
  704. }
  705. int n_ssl3_mac(SSL *ssl, unsigned char *md, int send)
  706. {
  707. SSL3_RECORD *rec;
  708. unsigned char *mac_sec, *seq;
  709. const EVP_MD_CTX *hash;
  710. unsigned char *p, rec_char;
  711. size_t md_size;
  712. int npad;
  713. int t;
  714. if (send) {
  715. rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
  716. mac_sec = &(ssl->s3->write_mac_secret[0]);
  717. seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
  718. hash = ssl->write_hash;
  719. } else {
  720. rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
  721. mac_sec = &(ssl->s3->read_mac_secret[0]);
  722. seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
  723. hash = ssl->read_hash;
  724. }
  725. t = EVP_MD_CTX_size(hash);
  726. if (t < 0)
  727. return -1;
  728. md_size = t;
  729. npad = (48 / md_size) * md_size;
  730. if (!send &&
  731. EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  732. ssl3_cbc_record_digest_supported(hash)) {
  733. /*
  734. * This is a CBC-encrypted record. We must avoid leaking any
  735. * timing-side channel information about how many blocks of data we
  736. * are hashing because that gives an attacker a timing-oracle.
  737. */
  738. /*-
  739. * npad is, at most, 48 bytes and that's with MD5:
  740. * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
  741. *
  742. * With SHA-1 (the largest hash speced for SSLv3) the hash size
  743. * goes up 4, but npad goes down by 8, resulting in a smaller
  744. * total size.
  745. */
  746. unsigned char header[75];
  747. unsigned j = 0;
  748. memcpy(header + j, mac_sec, md_size);
  749. j += md_size;
  750. memcpy(header + j, ssl3_pad_1, npad);
  751. j += npad;
  752. memcpy(header + j, seq, 8);
  753. j += 8;
  754. header[j++] = rec->type;
  755. header[j++] = rec->length >> 8;
  756. header[j++] = rec->length & 0xff;
  757. /* Final param == is SSLv3 */
  758. if (ssl3_cbc_digest_record(hash,
  759. md, &md_size,
  760. header, rec->input,
  761. rec->length + md_size, rec->orig_len,
  762. mac_sec, md_size, 1) <= 0)
  763. return -1;
  764. } else {
  765. unsigned int md_size_u;
  766. /* Chop the digest off the end :-) */
  767. EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
  768. if (md_ctx == NULL)
  769. return -1;
  770. rec_char = rec->type;
  771. p = md;
  772. s2n(rec->length, p);
  773. if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
  774. || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
  775. || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
  776. || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
  777. || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
  778. || EVP_DigestUpdate(md_ctx, md, 2) <= 0
  779. || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
  780. || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
  781. || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
  782. || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
  783. || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
  784. || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
  785. || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
  786. EVP_MD_CTX_reset(md_ctx);
  787. return -1;
  788. }
  789. md_size = md_size_u;
  790. EVP_MD_CTX_free(md_ctx);
  791. }
  792. ssl3_record_sequence_update(seq);
  793. return (md_size);
  794. }
  795. int tls1_mac(SSL *ssl, unsigned char *md, int send)
  796. {
  797. SSL3_RECORD *rec;
  798. unsigned char *seq;
  799. EVP_MD_CTX *hash;
  800. size_t md_size;
  801. int i;
  802. EVP_MD_CTX *hmac = NULL, *mac_ctx;
  803. unsigned char header[13];
  804. int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
  805. : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
  806. int t;
  807. if (send) {
  808. rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
  809. seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
  810. hash = ssl->write_hash;
  811. } else {
  812. rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
  813. seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
  814. hash = ssl->read_hash;
  815. }
  816. t = EVP_MD_CTX_size(hash);
  817. OPENSSL_assert(t >= 0);
  818. md_size = t;
  819. /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
  820. if (stream_mac) {
  821. mac_ctx = hash;
  822. } else {
  823. hmac = EVP_MD_CTX_new();
  824. if (hmac == NULL
  825. || !EVP_MD_CTX_copy(hmac, hash))
  826. return -1;
  827. mac_ctx = hmac;
  828. }
  829. if (SSL_IS_DTLS(ssl)) {
  830. unsigned char dtlsseq[8], *p = dtlsseq;
  831. s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
  832. DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
  833. memcpy(p, &seq[2], 6);
  834. memcpy(header, dtlsseq, 8);
  835. } else
  836. memcpy(header, seq, 8);
  837. header[8] = rec->type;
  838. header[9] = (unsigned char)(ssl->version >> 8);
  839. header[10] = (unsigned char)(ssl->version);
  840. header[11] = (rec->length) >> 8;
  841. header[12] = (rec->length) & 0xff;
  842. if (!send && !SSL_USE_ETM(ssl) &&
  843. EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  844. ssl3_cbc_record_digest_supported(mac_ctx)) {
  845. /*
  846. * This is a CBC-encrypted record. We must avoid leaking any
  847. * timing-side channel information about how many blocks of data we
  848. * are hashing because that gives an attacker a timing-oracle.
  849. */
  850. /* Final param == not SSLv3 */
  851. if (ssl3_cbc_digest_record(mac_ctx,
  852. md, &md_size,
  853. header, rec->input,
  854. rec->length + md_size, rec->orig_len,
  855. ssl->s3->read_mac_secret,
  856. ssl->s3->read_mac_secret_size, 0) <= 0) {
  857. EVP_MD_CTX_free(hmac);
  858. return -1;
  859. }
  860. } else {
  861. if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
  862. || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
  863. || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
  864. EVP_MD_CTX_free(hmac);
  865. return -1;
  866. }
  867. if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
  868. tls_fips_digest_extra(ssl->enc_read_ctx,
  869. mac_ctx, rec->input,
  870. rec->length, rec->orig_len);
  871. }
  872. EVP_MD_CTX_free(hmac);
  873. #ifdef TLS_DEBUG
  874. fprintf(stderr, "seq=");
  875. {
  876. int z;
  877. for (z = 0; z < 8; z++)
  878. fprintf(stderr, "%02X ", seq[z]);
  879. fprintf(stderr, "\n");
  880. }
  881. fprintf(stderr, "rec=");
  882. {
  883. unsigned int z;
  884. for (z = 0; z < rec->length; z++)
  885. fprintf(stderr, "%02X ", rec->data[z]);
  886. fprintf(stderr, "\n");
  887. }
  888. #endif
  889. if (!SSL_IS_DTLS(ssl)) {
  890. for (i = 7; i >= 0; i--) {
  891. ++seq[i];
  892. if (seq[i] != 0)
  893. break;
  894. }
  895. }
  896. #ifdef TLS_DEBUG
  897. {
  898. unsigned int z;
  899. for (z = 0; z < md_size; z++)
  900. fprintf(stderr, "%02X ", md[z]);
  901. fprintf(stderr, "\n");
  902. }
  903. #endif
  904. return (md_size);
  905. }
  906. /*-
  907. * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
  908. * record in |rec| by updating |rec->length| in constant time.
  909. *
  910. * block_size: the block size of the cipher used to encrypt the record.
  911. * returns:
  912. * 0: (in non-constant time) if the record is publicly invalid.
  913. * 1: if the padding was valid
  914. * -1: otherwise.
  915. */
  916. int ssl3_cbc_remove_padding(const SSL *s,
  917. SSL3_RECORD *rec,
  918. unsigned block_size, unsigned mac_size)
  919. {
  920. unsigned padding_length, good;
  921. const unsigned overhead = 1 /* padding length byte */ + mac_size;
  922. /*
  923. * These lengths are all public so we can test them in non-constant time.
  924. */
  925. if (overhead > rec->length)
  926. return 0;
  927. padding_length = rec->data[rec->length - 1];
  928. good = constant_time_ge(rec->length, padding_length + overhead);
  929. /* SSLv3 requires that the padding is minimal. */
  930. good &= constant_time_ge(block_size, padding_length + 1);
  931. rec->length -= good & (padding_length + 1);
  932. return constant_time_select_int(good, 1, -1);
  933. }
  934. /*-
  935. * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
  936. * record in |rec| in constant time and returns 1 if the padding is valid and
  937. * -1 otherwise. It also removes any explicit IV from the start of the record
  938. * without leaking any timing about whether there was enough space after the
  939. * padding was removed.
  940. *
  941. * block_size: the block size of the cipher used to encrypt the record.
  942. * returns:
  943. * 0: (in non-constant time) if the record is publicly invalid.
  944. * 1: if the padding was valid
  945. * -1: otherwise.
  946. */
  947. int tls1_cbc_remove_padding(const SSL *s,
  948. SSL3_RECORD *rec,
  949. unsigned block_size, unsigned mac_size)
  950. {
  951. unsigned padding_length, good, to_check, i;
  952. const unsigned overhead = 1 /* padding length byte */ + mac_size;
  953. /* Check if version requires explicit IV */
  954. if (SSL_USE_EXPLICIT_IV(s)) {
  955. /*
  956. * These lengths are all public so we can test them in non-constant
  957. * time.
  958. */
  959. if (overhead + block_size > rec->length)
  960. return 0;
  961. /* We can now safely skip explicit IV */
  962. rec->data += block_size;
  963. rec->input += block_size;
  964. rec->length -= block_size;
  965. rec->orig_len -= block_size;
  966. } else if (overhead > rec->length)
  967. return 0;
  968. padding_length = rec->data[rec->length - 1];
  969. if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
  970. /* padding is already verified */
  971. rec->length -= padding_length + 1;
  972. return 1;
  973. }
  974. good = constant_time_ge(rec->length, overhead + padding_length);
  975. /*
  976. * The padding consists of a length byte at the end of the record and
  977. * then that many bytes of padding, all with the same value as the length
  978. * byte. Thus, with the length byte included, there are i+1 bytes of
  979. * padding. We can't check just |padding_length+1| bytes because that
  980. * leaks decrypted information. Therefore we always have to check the
  981. * maximum amount of padding possible. (Again, the length of the record
  982. * is public information so we can use it.)
  983. */
  984. to_check = 255; /* maximum amount of padding. */
  985. if (to_check > rec->length - 1)
  986. to_check = rec->length - 1;
  987. for (i = 0; i < to_check; i++) {
  988. unsigned char mask = constant_time_ge_8(padding_length, i);
  989. unsigned char b = rec->data[rec->length - 1 - i];
  990. /*
  991. * The final |padding_length+1| bytes should all have the value
  992. * |padding_length|. Therefore the XOR should be zero.
  993. */
  994. good &= ~(mask & (padding_length ^ b));
  995. }
  996. /*
  997. * If any of the final |padding_length+1| bytes had the wrong value, one
  998. * or more of the lower eight bits of |good| will be cleared.
  999. */
  1000. good = constant_time_eq(0xff, good & 0xff);
  1001. rec->length -= good & (padding_length + 1);
  1002. return constant_time_select_int(good, 1, -1);
  1003. }
  1004. /*-
  1005. * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
  1006. * constant time (independent of the concrete value of rec->length, which may
  1007. * vary within a 256-byte window).
  1008. *
  1009. * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
  1010. * this function.
  1011. *
  1012. * On entry:
  1013. * rec->orig_len >= md_size
  1014. * md_size <= EVP_MAX_MD_SIZE
  1015. *
  1016. * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
  1017. * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
  1018. * a single or pair of cache-lines, then the variable memory accesses don't
  1019. * actually affect the timing. CPUs with smaller cache-lines [if any] are
  1020. * not multi-core and are not considered vulnerable to cache-timing attacks.
  1021. */
  1022. #define CBC_MAC_ROTATE_IN_PLACE
  1023. void ssl3_cbc_copy_mac(unsigned char *out,
  1024. const SSL3_RECORD *rec, unsigned md_size)
  1025. {
  1026. #if defined(CBC_MAC_ROTATE_IN_PLACE)
  1027. unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
  1028. unsigned char *rotated_mac;
  1029. #else
  1030. unsigned char rotated_mac[EVP_MAX_MD_SIZE];
  1031. #endif
  1032. /*
  1033. * mac_end is the index of |rec->data| just after the end of the MAC.
  1034. */
  1035. unsigned mac_end = rec->length;
  1036. unsigned mac_start = mac_end - md_size;
  1037. /*
  1038. * scan_start contains the number of bytes that we can ignore because the
  1039. * MAC's position can only vary by 255 bytes.
  1040. */
  1041. unsigned scan_start = 0;
  1042. unsigned i, j;
  1043. unsigned div_spoiler;
  1044. unsigned rotate_offset;
  1045. OPENSSL_assert(rec->orig_len >= md_size);
  1046. OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
  1047. #if defined(CBC_MAC_ROTATE_IN_PLACE)
  1048. rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
  1049. #endif
  1050. /* This information is public so it's safe to branch based on it. */
  1051. if (rec->orig_len > md_size + 255 + 1)
  1052. scan_start = rec->orig_len - (md_size + 255 + 1);
  1053. /*
  1054. * div_spoiler contains a multiple of md_size that is used to cause the
  1055. * modulo operation to be constant time. Without this, the time varies
  1056. * based on the amount of padding when running on Intel chips at least.
  1057. * The aim of right-shifting md_size is so that the compiler doesn't
  1058. * figure out that it can remove div_spoiler as that would require it to
  1059. * prove that md_size is always even, which I hope is beyond it.
  1060. */
  1061. div_spoiler = md_size >> 1;
  1062. div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
  1063. rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
  1064. memset(rotated_mac, 0, md_size);
  1065. for (i = scan_start, j = 0; i < rec->orig_len; i++) {
  1066. unsigned char mac_started = constant_time_ge_8(i, mac_start);
  1067. unsigned char mac_ended = constant_time_ge_8(i, mac_end);
  1068. unsigned char b = rec->data[i];
  1069. rotated_mac[j++] |= b & mac_started & ~mac_ended;
  1070. j &= constant_time_lt(j, md_size);
  1071. }
  1072. /* Now rotate the MAC */
  1073. #if defined(CBC_MAC_ROTATE_IN_PLACE)
  1074. j = 0;
  1075. for (i = 0; i < md_size; i++) {
  1076. /* in case cache-line is 32 bytes, touch second line */
  1077. ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
  1078. out[j++] = rotated_mac[rotate_offset++];
  1079. rotate_offset &= constant_time_lt(rotate_offset, md_size);
  1080. }
  1081. #else
  1082. memset(out, 0, md_size);
  1083. rotate_offset = md_size - rotate_offset;
  1084. rotate_offset &= constant_time_lt(rotate_offset, md_size);
  1085. for (i = 0; i < md_size; i++) {
  1086. for (j = 0; j < md_size; j++)
  1087. out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
  1088. rotate_offset++;
  1089. rotate_offset &= constant_time_lt(rotate_offset, md_size);
  1090. }
  1091. #endif
  1092. }
  1093. int dtls1_process_record(SSL *s)
  1094. {
  1095. int i, al;
  1096. int enc_err;
  1097. SSL_SESSION *sess;
  1098. SSL3_RECORD *rr;
  1099. unsigned int mac_size;
  1100. unsigned char md[EVP_MAX_MD_SIZE];
  1101. rr = RECORD_LAYER_get_rrec(&s->rlayer);
  1102. sess = s->session;
  1103. /*
  1104. * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  1105. * and we have that many bytes in s->packet
  1106. */
  1107. rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
  1108. /*
  1109. * ok, we can now read from 's->packet' data into 'rr' rr->input points
  1110. * at rr->length bytes, which need to be copied into rr->data by either
  1111. * the decryption or by the decompression When the data is 'copied' into
  1112. * the rr->data buffer, rr->input will be pointed at the new buffer
  1113. */
  1114. /*
  1115. * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
  1116. * bytes of encrypted compressed stuff.
  1117. */
  1118. /* check is not needed I believe */
  1119. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  1120. al = SSL_AD_RECORD_OVERFLOW;
  1121. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  1122. goto f_err;
  1123. }
  1124. /* decrypt in place in 'rr->input' */
  1125. rr->data = rr->input;
  1126. rr->orig_len = rr->length;
  1127. enc_err = s->method->ssl3_enc->enc(s, 0);
  1128. /*-
  1129. * enc_err is:
  1130. * 0: (in non-constant time) if the record is publically invalid.
  1131. * 1: if the padding is valid
  1132. * -1: if the padding is invalid
  1133. */
  1134. if (enc_err == 0) {
  1135. /* For DTLS we simply ignore bad packets. */
  1136. rr->length = 0;
  1137. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1138. goto err;
  1139. }
  1140. #ifdef TLS_DEBUG
  1141. printf("dec %d\n", rr->length);
  1142. {
  1143. unsigned int z;
  1144. for (z = 0; z < rr->length; z++)
  1145. printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
  1146. }
  1147. printf("\n");
  1148. #endif
  1149. /* r->length is now the compressed data plus mac */
  1150. if ((sess != NULL) &&
  1151. (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
  1152. /* s->read_hash != NULL => mac_size != -1 */
  1153. unsigned char *mac = NULL;
  1154. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  1155. mac_size = EVP_MD_CTX_size(s->read_hash);
  1156. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  1157. /*
  1158. * orig_len is the length of the record before any padding was
  1159. * removed. This is public information, as is the MAC in use,
  1160. * therefore we can safely process the record in a different amount
  1161. * of time if it's too short to possibly contain a MAC.
  1162. */
  1163. if (rr->orig_len < mac_size ||
  1164. /* CBC records must have a padding length byte too. */
  1165. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  1166. rr->orig_len < mac_size + 1)) {
  1167. al = SSL_AD_DECODE_ERROR;
  1168. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
  1169. goto f_err;
  1170. }
  1171. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
  1172. /*
  1173. * We update the length so that the TLS header bytes can be
  1174. * constructed correctly but we need to extract the MAC in
  1175. * constant time from within the record, without leaking the
  1176. * contents of the padding bytes.
  1177. */
  1178. mac = mac_tmp;
  1179. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
  1180. rr->length -= mac_size;
  1181. } else {
  1182. /*
  1183. * In this case there's no padding, so |rec->orig_len| equals
  1184. * |rec->length| and we checked that there's enough bytes for
  1185. * |mac_size| above.
  1186. */
  1187. rr->length -= mac_size;
  1188. mac = &rr->data[rr->length];
  1189. }
  1190. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  1191. if (i < 0 || mac == NULL
  1192. || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  1193. enc_err = -1;
  1194. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
  1195. enc_err = -1;
  1196. }
  1197. if (enc_err < 0) {
  1198. /* decryption failed, silently discard message */
  1199. rr->length = 0;
  1200. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1201. goto err;
  1202. }
  1203. /* r->length is now just compressed */
  1204. if (s->expand != NULL) {
  1205. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
  1206. al = SSL_AD_RECORD_OVERFLOW;
  1207. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
  1208. SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  1209. goto f_err;
  1210. }
  1211. if (!ssl3_do_uncompress(s)) {
  1212. al = SSL_AD_DECOMPRESSION_FAILURE;
  1213. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
  1214. goto f_err;
  1215. }
  1216. }
  1217. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
  1218. al = SSL_AD_RECORD_OVERFLOW;
  1219. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
  1220. goto f_err;
  1221. }
  1222. rr->off = 0;
  1223. /*-
  1224. * So at this point the following is true
  1225. * ssl->s3->rrec.type is the type of record
  1226. * ssl->s3->rrec.length == number of bytes in record
  1227. * ssl->s3->rrec.off == offset to first valid byte
  1228. * ssl->s3->rrec.data == where to take bytes from, increment
  1229. * after use :-).
  1230. */
  1231. /* we have pulled in a full packet so zero things */
  1232. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1233. return (1);
  1234. f_err:
  1235. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1236. err:
  1237. return (0);
  1238. }
  1239. /*
  1240. * retrieve a buffered record that belongs to the current epoch, ie,
  1241. * processed
  1242. */
  1243. #define dtls1_get_processed_record(s) \
  1244. dtls1_retrieve_buffered_record((s), \
  1245. &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
  1246. /*-
  1247. * Call this to get a new input record.
  1248. * It will return <= 0 if more data is needed, normally due to an error
  1249. * or non-blocking IO.
  1250. * When it finishes, one packet has been decoded and can be found in
  1251. * ssl->s3->rrec.type - is the type of record
  1252. * ssl->s3->rrec.data, - data
  1253. * ssl->s3->rrec.length, - number of bytes
  1254. */
  1255. /* used only by dtls1_read_bytes */
  1256. int dtls1_get_record(SSL *s)
  1257. {
  1258. int ssl_major, ssl_minor;
  1259. int i, n;
  1260. SSL3_RECORD *rr;
  1261. unsigned char *p = NULL;
  1262. unsigned short version;
  1263. DTLS1_BITMAP *bitmap;
  1264. unsigned int is_next_epoch;
  1265. rr = RECORD_LAYER_get_rrec(&s->rlayer);
  1266. /*
  1267. * The epoch may have changed. If so, process all the pending records.
  1268. * This is a non-blocking operation.
  1269. */
  1270. if (dtls1_process_buffered_records(s) < 0)
  1271. return -1;
  1272. /* if we're renegotiating, then there may be buffered records */
  1273. if (dtls1_get_processed_record(s))
  1274. return 1;
  1275. /* get something from the wire */
  1276. again:
  1277. /* check if we have the header */
  1278. if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
  1279. (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
  1280. n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
  1281. SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
  1282. /* read timeout is handled by dtls1_read_bytes */
  1283. if (n <= 0)
  1284. return (n); /* error or non-blocking */
  1285. /* this packet contained a partial record, dump it */
  1286. if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
  1287. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1288. goto again;
  1289. }
  1290. RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
  1291. p = RECORD_LAYER_get_packet(&s->rlayer);
  1292. if (s->msg_callback)
  1293. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
  1294. s, s->msg_callback_arg);
  1295. /* Pull apart the header into the DTLS1_RECORD */
  1296. rr->type = *(p++);
  1297. ssl_major = *(p++);
  1298. ssl_minor = *(p++);
  1299. version = (ssl_major << 8) | ssl_minor;
  1300. /* sequence number is 64 bits, with top 2 bytes = epoch */
  1301. n2s(p, rr->epoch);
  1302. memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
  1303. p += 6;
  1304. n2s(p, rr->length);
  1305. /* Lets check version */
  1306. if (!s->first_packet) {
  1307. if (version != s->version) {
  1308. /* unexpected version, silently discard */
  1309. rr->length = 0;
  1310. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1311. goto again;
  1312. }
  1313. }
  1314. if ((version & 0xff00) != (s->version & 0xff00)) {
  1315. /* wrong version, silently discard record */
  1316. rr->length = 0;
  1317. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1318. goto again;
  1319. }
  1320. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  1321. /* record too long, silently discard it */
  1322. rr->length = 0;
  1323. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1324. goto again;
  1325. }
  1326. /* now s->rlayer.rstate == SSL_ST_READ_BODY */
  1327. }
  1328. /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
  1329. if (rr->length >
  1330. RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
  1331. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  1332. i = rr->length;
  1333. n = ssl3_read_n(s, i, i, 1);
  1334. /* this packet contained a partial record, dump it */
  1335. if (n != i) {
  1336. rr->length = 0;
  1337. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1338. goto again;
  1339. }
  1340. /*
  1341. * now n == rr->length, and s->packet_length ==
  1342. * DTLS1_RT_HEADER_LENGTH + rr->length
  1343. */
  1344. }
  1345. /* set state for later operations */
  1346. RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
  1347. /* match epochs. NULL means the packet is dropped on the floor */
  1348. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  1349. if (bitmap == NULL) {
  1350. rr->length = 0;
  1351. RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
  1352. goto again; /* get another record */
  1353. }
  1354. #ifndef OPENSSL_NO_SCTP
  1355. /* Only do replay check if no SCTP bio */
  1356. if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  1357. #endif
  1358. /* Check whether this is a repeat, or aged record. */
  1359. if (!dtls1_record_replay_check(s, bitmap)) {
  1360. rr->length = 0;
  1361. RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
  1362. goto again; /* get another record */
  1363. }
  1364. #ifndef OPENSSL_NO_SCTP
  1365. }
  1366. #endif
  1367. /* just read a 0 length packet */
  1368. if (rr->length == 0)
  1369. goto again;
  1370. /*
  1371. * If this record is from the next epoch (either HM or ALERT), and a
  1372. * handshake is currently in progress, buffer it since it cannot be
  1373. * processed at this time.
  1374. */
  1375. if (is_next_epoch) {
  1376. if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
  1377. if (dtls1_buffer_record
  1378. (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
  1379. rr->seq_num) < 0)
  1380. return -1;
  1381. /* Mark receipt of record. */
  1382. dtls1_record_bitmap_update(s, bitmap);
  1383. }
  1384. rr->length = 0;
  1385. RECORD_LAYER_reset_packet_length(&s->rlayer);
  1386. goto again;
  1387. }
  1388. if (!dtls1_process_record(s)) {
  1389. rr->length = 0;
  1390. RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
  1391. goto again; /* get another record */
  1392. }
  1393. dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
  1394. return (1);
  1395. }