Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com).
  108. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2005 Nokia. All rights reserved.
  112. *
  113. * The portions of the attached software ("Contribution") is developed by
  114. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  115. * license.
  116. *
  117. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  118. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  119. * support (see RFC 4279) to OpenSSL.
  120. *
  121. * No patent licenses or other rights except those expressly stated in
  122. * the OpenSSL open source license shall be deemed granted or received
  123. * expressly, by implication, estoppel, or otherwise.
  124. *
  125. * No assurances are provided by Nokia that the Contribution does not
  126. * infringe the patent or other intellectual property rights of any third
  127. * party or that the license provides you with all the necessary rights
  128. * to make use of the Contribution.
  129. *
  130. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  131. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  132. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  133. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  134. * OTHERWISE. */
  135. #include <stdio.h>
  136. #include <assert.h>
  137. #include <openssl/err.h>
  138. #include <openssl/evp.h>
  139. #include <openssl/hmac.h>
  140. #include <openssl/md5.h>
  141. #include <openssl/mem.h>
  142. #include <openssl/obj.h>
  143. #include <openssl/rand.h>
  144. #include "ssl_locl.h"
  145. /* seed1 through seed5 are virtually concatenated */
  146. static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
  147. int sec_len,
  148. const void *seed1, int seed1_len,
  149. const void *seed2, int seed2_len,
  150. const void *seed3, int seed3_len,
  151. unsigned char *out, int olen)
  152. {
  153. int chunk;
  154. size_t j;
  155. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  156. EVP_PKEY *mac_key;
  157. unsigned char A1[EVP_MAX_MD_SIZE];
  158. size_t A1_len;
  159. int ret = 0;
  160. chunk=EVP_MD_size(md);
  161. EVP_MD_CTX_init(&ctx);
  162. EVP_MD_CTX_init(&ctx_tmp);
  163. EVP_MD_CTX_init(&ctx_init);
  164. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
  165. if (!mac_key)
  166. goto err;
  167. if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
  168. goto err;
  169. if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
  170. goto err;
  171. if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
  172. goto err;
  173. if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
  174. goto err;
  175. if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
  176. goto err;
  177. A1_len = EVP_MAX_MD_SIZE;
  178. if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
  179. goto err;
  180. for (;;)
  181. {
  182. /* Reinit mac contexts */
  183. if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
  184. goto err;
  185. if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
  186. goto err;
  187. if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
  188. goto err;
  189. if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
  190. goto err;
  191. if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
  192. goto err;
  193. if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
  194. goto err;
  195. if (olen > chunk)
  196. {
  197. j = olen;
  198. if (!EVP_DigestSignFinal(&ctx,out,&j))
  199. goto err;
  200. out+=j;
  201. olen-=j;
  202. /* calc the next A1 value */
  203. A1_len = EVP_MAX_MD_SIZE;
  204. if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
  205. goto err;
  206. }
  207. else /* last one */
  208. {
  209. A1_len = EVP_MAX_MD_SIZE;
  210. if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
  211. goto err;
  212. memcpy(out,A1,olen);
  213. break;
  214. }
  215. }
  216. ret = 1;
  217. err:
  218. EVP_PKEY_free(mac_key);
  219. EVP_MD_CTX_cleanup(&ctx);
  220. EVP_MD_CTX_cleanup(&ctx_tmp);
  221. EVP_MD_CTX_cleanup(&ctx_init);
  222. OPENSSL_cleanse(A1,sizeof(A1));
  223. return ret;
  224. }
  225. /* seed1 through seed5 are virtually concatenated */
  226. static int tls1_PRF(long digest_mask,
  227. const void *seed1, int seed1_len,
  228. const void *seed2, int seed2_len,
  229. const void *seed3, int seed3_len,
  230. const unsigned char *sec, int slen,
  231. unsigned char *out1,
  232. unsigned char *out2, int olen)
  233. {
  234. int len,i,idx,count;
  235. const unsigned char *S1;
  236. long m;
  237. const EVP_MD *md;
  238. int ret = 0;
  239. /* Count number of digests and partition sec evenly */
  240. count=0;
  241. for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
  242. if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
  243. }
  244. len=slen/count;
  245. if (count == 1)
  246. slen = 0;
  247. S1=sec;
  248. memset(out1,0,olen);
  249. for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
  250. if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
  251. if (!md) {
  252. OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
  253. goto err;
  254. }
  255. if (!tls1_P_hash(md ,S1,len+(slen&1),
  256. seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,
  257. out2,olen))
  258. goto err;
  259. S1+=len;
  260. for (i=0; i<olen; i++)
  261. {
  262. out1[i]^=out2[i];
  263. }
  264. }
  265. }
  266. ret = 1;
  267. err:
  268. return ret;
  269. }
  270. static int tls1_generate_key_block(SSL *s, unsigned char *km,
  271. unsigned char *tmp, int num)
  272. {
  273. int ret;
  274. ret = tls1_PRF(ssl_get_algorithm2(s),
  275. TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
  276. s->s3->server_random,SSL3_RANDOM_SIZE,
  277. s->s3->client_random,SSL3_RANDOM_SIZE,
  278. s->session->master_key,s->session->master_key_length,
  279. km,tmp,num);
  280. return ret;
  281. }
  282. /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
  283. * returns 0 on malloc error. */
  284. static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
  285. {
  286. if (*aead_ctx != NULL)
  287. EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
  288. else
  289. {
  290. *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
  291. if (*aead_ctx == NULL)
  292. {
  293. OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
  294. return 0;
  295. }
  296. }
  297. return 1;
  298. }
  299. static void tls1_cleanup_enc_ctx(EVP_CIPHER_CTX **ctx)
  300. {
  301. if (*ctx != NULL)
  302. EVP_CIPHER_CTX_free(*ctx);
  303. *ctx = NULL;
  304. }
  305. static void tls1_cleanup_hash_ctx(EVP_MD_CTX **ctx)
  306. {
  307. if (*ctx != NULL)
  308. EVP_MD_CTX_destroy(*ctx);
  309. *ctx = NULL;
  310. }
  311. static int tls1_change_cipher_state_aead(SSL *s, char is_read,
  312. const unsigned char *key, unsigned key_len,
  313. const unsigned char *iv, unsigned iv_len,
  314. const unsigned char *mac_secret, unsigned mac_secret_len)
  315. {
  316. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  317. SSL_AEAD_CTX *aead_ctx;
  318. /* mac_key_and_key is used to merge the MAC and cipher keys for an AEAD
  319. * which simulates pre-AEAD cipher suites. It needs to be large enough
  320. * to cope with the largest pair of keys. */
  321. uint8_t mac_key_and_key[32 /* HMAC(SHA256) */ + 32 /* AES-256 */];
  322. if (is_read)
  323. {
  324. tls1_cleanup_enc_ctx(&s->enc_read_ctx);
  325. tls1_cleanup_hash_ctx(&s->read_hash);
  326. }
  327. else
  328. {
  329. tls1_cleanup_enc_ctx(&s->enc_write_ctx);
  330. tls1_cleanup_hash_ctx(&s->write_hash);
  331. }
  332. if (mac_secret_len > 0)
  333. {
  334. /* This is a "stateful" AEAD (for compatibility with pre-AEAD
  335. * cipher suites). */
  336. if (mac_secret_len + key_len > sizeof(mac_key_and_key))
  337. {
  338. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  339. return 0;
  340. }
  341. memcpy(mac_key_and_key, mac_secret, mac_secret_len);
  342. memcpy(mac_key_and_key + mac_secret_len, key, key_len);
  343. key = mac_key_and_key;
  344. key_len += mac_secret_len;
  345. }
  346. if (is_read)
  347. {
  348. if (!tls1_aead_ctx_init(&s->aead_read_ctx))
  349. return 0;
  350. aead_ctx = s->aead_read_ctx;
  351. }
  352. else
  353. {
  354. if (!tls1_aead_ctx_init(&s->aead_write_ctx))
  355. return 0;
  356. aead_ctx = s->aead_write_ctx;
  357. }
  358. if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
  359. EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
  360. {
  361. OPENSSL_free(aead_ctx);
  362. if (is_read)
  363. s->aead_read_ctx = NULL;
  364. else
  365. s->aead_write_ctx = NULL;
  366. return 0;
  367. }
  368. if (iv_len > sizeof(aead_ctx->fixed_nonce))
  369. {
  370. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  371. return 0;
  372. }
  373. memcpy(aead_ctx->fixed_nonce, iv, iv_len);
  374. aead_ctx->fixed_nonce_len = iv_len;
  375. aead_ctx->variable_nonce_len = 8; /* correct for all true AEADs so far. */
  376. if (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)
  377. aead_ctx->variable_nonce_len = 0;
  378. aead_ctx->variable_nonce_included_in_record =
  379. (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
  380. if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead))
  381. {
  382. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  383. return 0;
  384. }
  385. aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
  386. return 1;
  387. }
  388. static void tls1_cleanup_aead_ctx(SSL_AEAD_CTX **ctx)
  389. {
  390. if (*ctx != NULL)
  391. {
  392. EVP_AEAD_CTX_cleanup(&(*ctx)->ctx);
  393. OPENSSL_free(*ctx);
  394. }
  395. *ctx = NULL;
  396. }
  397. /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
  398. * states when using EVP_CIPHER. The argument |is_read| is true iff this
  399. * function is being called due to reading, as opposed to writing, a
  400. * ChangeCipherSpec message. In order to support export ciphersuites,
  401. * use_client_keys indicates whether the key material provided is in the
  402. * "client write" direction. */
  403. static int tls1_change_cipher_state_cipher(
  404. SSL *s, char is_read, char use_client_keys,
  405. const unsigned char *mac_secret, unsigned mac_secret_len,
  406. const unsigned char *key, unsigned key_len,
  407. const unsigned char *iv, unsigned iv_len)
  408. {
  409. const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
  410. EVP_CIPHER_CTX *cipher_ctx;
  411. EVP_MD_CTX *mac_ctx;
  412. if (is_read)
  413. tls1_cleanup_aead_ctx(&s->aead_read_ctx);
  414. else
  415. tls1_cleanup_aead_ctx(&s->aead_write_ctx);
  416. if (is_read)
  417. {
  418. if (s->enc_read_ctx != NULL && !SSL_IS_DTLS(s))
  419. EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
  420. else if ((s->enc_read_ctx=EVP_CIPHER_CTX_new()) == NULL)
  421. goto err;
  422. cipher_ctx = s->enc_read_ctx;
  423. mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
  424. memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
  425. s->s3->read_mac_secret_size = mac_secret_len;
  426. }
  427. else
  428. {
  429. /* When updating the write contexts for DTLS, we do not wish to
  430. * free the old ones because DTLS stores pointers to them in
  431. * order to implement retransmission. */
  432. if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
  433. EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
  434. else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
  435. goto err;
  436. else
  437. /* make sure it's intialized in case we exit later with an error */
  438. EVP_CIPHER_CTX_init(s->enc_write_ctx);
  439. cipher_ctx = s->enc_write_ctx;
  440. if (SSL_IS_DTLS(s))
  441. {
  442. /* This is the same as ssl_replace_hash, but doesn't
  443. * free the old |s->write_hash|. */
  444. mac_ctx = EVP_MD_CTX_create();
  445. if (!mac_ctx)
  446. goto err;
  447. s->write_hash = mac_ctx;
  448. }
  449. else
  450. mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
  451. memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
  452. s->s3->write_mac_secret_size = mac_secret_len;
  453. }
  454. EVP_PKEY *mac_key =
  455. EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
  456. NULL, mac_secret, mac_secret_len);
  457. if (!mac_key)
  458. return 0;
  459. EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
  460. EVP_PKEY_free(mac_key);
  461. EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
  462. return 1;
  463. err:
  464. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_cipher, ERR_R_MALLOC_FAILURE);
  465. return 0;
  466. }
  467. int tls1_change_cipher_state(SSL *s, int which)
  468. {
  469. /* is_read is true if we have just read a ChangeCipherSpec message -
  470. * i.e. we need to update the read cipherspec. Otherwise we have just
  471. * written one. */
  472. const char is_read = (which & SSL3_CC_READ) != 0;
  473. /* use_client_keys is true if we wish to use the keys for the "client
  474. * write" direction. This is the case if we're a client sending a
  475. * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
  476. const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
  477. which == SSL3_CHANGE_CIPHER_SERVER_READ;
  478. const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
  479. const unsigned char *client_write_key, *server_write_key, *key;
  480. const unsigned char *client_write_iv, *server_write_iv, *iv;
  481. const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
  482. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  483. unsigned key_len, iv_len, mac_secret_len;
  484. const unsigned char *key_data;
  485. /* Reset sequence number to zero. */
  486. if (!SSL_IS_DTLS(s))
  487. memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
  488. mac_secret_len = s->s3->tmp.new_mac_secret_size;
  489. if (aead != NULL)
  490. {
  491. key_len = EVP_AEAD_key_length(aead);
  492. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
  493. * cipher suites) the key length reported by
  494. * |EVP_AEAD_key_length| will include the MAC key bytes. */
  495. if (key_len < mac_secret_len)
  496. {
  497. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  498. return 0;
  499. }
  500. key_len -= mac_secret_len;
  501. iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
  502. }
  503. else
  504. {
  505. key_len = EVP_CIPHER_key_length(cipher);
  506. iv_len = EVP_CIPHER_iv_length(cipher);
  507. }
  508. key_data = s->s3->tmp.key_block;
  509. client_write_mac_secret = key_data; key_data += mac_secret_len;
  510. server_write_mac_secret = key_data; key_data += mac_secret_len;
  511. client_write_key = key_data; key_data += key_len;
  512. server_write_key = key_data; key_data += key_len;
  513. client_write_iv = key_data; key_data += iv_len;
  514. server_write_iv = key_data; key_data += iv_len;
  515. if (use_client_keys)
  516. {
  517. mac_secret = client_write_mac_secret;
  518. key = client_write_key;
  519. iv = client_write_iv;
  520. }
  521. else
  522. {
  523. mac_secret = server_write_mac_secret;
  524. key = server_write_key;
  525. iv = server_write_iv;
  526. }
  527. if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
  528. {
  529. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  530. return 0;
  531. }
  532. if (aead != NULL)
  533. {
  534. if (!tls1_change_cipher_state_aead(s, is_read,
  535. key, key_len, iv, iv_len,
  536. mac_secret, mac_secret_len))
  537. return 0;
  538. }
  539. else
  540. {
  541. if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
  542. mac_secret, mac_secret_len,
  543. key, key_len,
  544. iv, iv_len))
  545. return 0;
  546. }
  547. return 1;
  548. }
  549. int tls1_setup_key_block(SSL *s)
  550. {
  551. unsigned char *p1,*p2=NULL;
  552. const EVP_CIPHER *c = NULL;
  553. const EVP_MD *hash = NULL;
  554. const EVP_AEAD *aead = NULL;
  555. int num;
  556. int mac_type= NID_undef,mac_secret_size=0;
  557. int ret=0;
  558. unsigned key_len, iv_len;
  559. if (s->s3->tmp.key_block_length != 0)
  560. return(1);
  561. if (s->session->cipher &&
  562. ((s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD) ||
  563. (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)))
  564. {
  565. if (!ssl_cipher_get_evp_aead(s->session, &aead))
  566. goto cipher_unavailable_err;
  567. key_len = EVP_AEAD_key_length(aead);
  568. iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
  569. if ((s->session->cipher->algorithm2 &
  570. SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD) &&
  571. !ssl_cipher_get_mac(s->session, &hash, &mac_type, &mac_secret_size))
  572. goto cipher_unavailable_err;
  573. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
  574. * cipher suites) the key length reported by
  575. * |EVP_AEAD_key_length| will include the MAC key bytes. */
  576. if (key_len < (size_t)mac_secret_size)
  577. {
  578. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  579. return 0;
  580. }
  581. key_len -= mac_secret_size;
  582. }
  583. else
  584. {
  585. if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size))
  586. goto cipher_unavailable_err;
  587. key_len = EVP_CIPHER_key_length(c);
  588. iv_len = EVP_CIPHER_iv_length(c);
  589. }
  590. s->s3->tmp.new_aead=aead;
  591. s->s3->tmp.new_sym_enc=c;
  592. s->s3->tmp.new_hash=hash;
  593. s->s3->tmp.new_mac_pkey_type = mac_type;
  594. s->s3->tmp.new_mac_secret_size = mac_secret_size;
  595. num=key_len+mac_secret_size+iv_len;
  596. num*=2;
  597. ssl3_cleanup_key_block(s);
  598. if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
  599. {
  600. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  601. goto err;
  602. }
  603. s->s3->tmp.key_block_length=num;
  604. s->s3->tmp.key_block=p1;
  605. if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
  606. {
  607. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  608. goto err;
  609. }
  610. #ifdef TLS_DEBUG
  611. printf("client random\n");
  612. { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
  613. printf("server random\n");
  614. { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
  615. printf("pre-master\n");
  616. { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
  617. #endif
  618. if (!tls1_generate_key_block(s,p1,p2,num))
  619. goto err;
  620. #ifdef TLS_DEBUG
  621. printf("\nkey block\n");
  622. { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
  623. #endif
  624. if (s->method->version <= TLS1_VERSION &&
  625. (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0)
  626. {
  627. /* enable vulnerability countermeasure for CBC ciphers with
  628. * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
  629. */
  630. s->s3->need_record_splitting = 1;
  631. if (s->session->cipher != NULL)
  632. {
  633. if (s->session->cipher->algorithm_enc == SSL_RC4)
  634. s->s3->need_record_splitting = 0;
  635. }
  636. }
  637. ret = 1;
  638. err:
  639. if (p2)
  640. {
  641. OPENSSL_cleanse(p2,num);
  642. OPENSSL_free(p2);
  643. }
  644. return(ret);
  645. cipher_unavailable_err:
  646. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
  647. return 0;
  648. }
  649. /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
  650. *
  651. * Returns:
  652. * 0: (in non-constant time) if the record is publically invalid (i.e. too
  653. * short etc).
  654. * 1: if the record's padding is valid / the encryption was successful.
  655. * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
  656. * an internal error occured.
  657. */
  658. int tls1_enc(SSL *s, int send)
  659. {
  660. SSL3_RECORD *rec;
  661. EVP_CIPHER_CTX *ds;
  662. unsigned long l;
  663. int bs,i,j,k,pad=0,ret,mac_size=0;
  664. const EVP_CIPHER *enc;
  665. const SSL_AEAD_CTX *aead;
  666. if (send)
  667. rec = &s->s3->wrec;
  668. else
  669. rec = &s->s3->rrec;
  670. if (send)
  671. aead = s->aead_write_ctx;
  672. else
  673. aead = s->aead_read_ctx;
  674. if (aead)
  675. {
  676. unsigned char ad[13], *seq, *in, *out, nonce[16];
  677. unsigned nonce_used;
  678. size_t n;
  679. seq = send ? s->s3->write_sequence : s->s3->read_sequence;
  680. if (SSL_IS_DTLS(s))
  681. {
  682. unsigned char dtlsseq[9], *p = dtlsseq;
  683. s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
  684. memcpy(p, &seq[2], 6);
  685. memcpy(ad, dtlsseq, 8);
  686. }
  687. else
  688. {
  689. memcpy(ad, seq, 8);
  690. for (i=7; i>=0; i--) /* increment */
  691. {
  692. ++seq[i];
  693. if (seq[i] != 0)
  694. break;
  695. }
  696. }
  697. ad[8] = rec->type;
  698. ad[9] = (unsigned char)(s->version>>8);
  699. ad[10] = (unsigned char)(s->version);
  700. if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce) ||
  701. aead->variable_nonce_len > 8)
  702. return -1; /* internal error - should never happen. */
  703. memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
  704. nonce_used = aead->fixed_nonce_len;
  705. if (send)
  706. {
  707. size_t len = rec->length;
  708. size_t eivlen = 0;
  709. in = rec->input;
  710. out = rec->data;
  711. /* When sending we use the sequence number as the
  712. * variable part of the nonce. */
  713. if (aead->variable_nonce_len > 8)
  714. return -1;
  715. memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
  716. nonce_used += aead->variable_nonce_len;
  717. /* in do_ssl3_write, rec->input is moved forward by
  718. * variable_nonce_len in order to leave space for the
  719. * variable nonce. Thus we can copy the sequence number
  720. * bytes into place without overwriting any of the
  721. * plaintext. */
  722. if (aead->variable_nonce_included_in_record)
  723. {
  724. memcpy(out, ad, aead->variable_nonce_len);
  725. len -= aead->variable_nonce_len;
  726. eivlen = aead->variable_nonce_len;
  727. }
  728. ad[11] = len >> 8;
  729. ad[12] = len & 0xff;
  730. if (!EVP_AEAD_CTX_seal(
  731. &aead->ctx,
  732. out + eivlen, &n, len + aead->tag_len,
  733. nonce, nonce_used,
  734. in + eivlen, len,
  735. ad, sizeof(ad)))
  736. {
  737. return -1;
  738. }
  739. if (aead->variable_nonce_included_in_record)
  740. n += aead->variable_nonce_len;
  741. }
  742. else
  743. {
  744. /* receive */
  745. size_t len = rec->length;
  746. if (rec->data != rec->input)
  747. return -1; /* internal error - should never happen. */
  748. out = in = rec->input;
  749. if (len < aead->variable_nonce_len)
  750. return 0;
  751. memcpy(nonce + nonce_used,
  752. aead->variable_nonce_included_in_record ? in : ad,
  753. aead->variable_nonce_len);
  754. nonce_used += aead->variable_nonce_len;
  755. if (aead->variable_nonce_included_in_record)
  756. {
  757. in += aead->variable_nonce_len;
  758. len -= aead->variable_nonce_len;
  759. out += aead->variable_nonce_len;
  760. }
  761. if (len < aead->tag_len)
  762. return 0;
  763. len -= aead->tag_len;
  764. ad[11] = len >> 8;
  765. ad[12] = len & 0xff;
  766. if (!EVP_AEAD_CTX_open(
  767. &aead->ctx,
  768. out, &n, len,
  769. nonce, nonce_used,
  770. in, len + aead->tag_len,
  771. ad, sizeof(ad)))
  772. {
  773. return -1;
  774. }
  775. rec->data = rec->input = out;
  776. }
  777. rec->length = n;
  778. return 1;
  779. }
  780. if (send)
  781. {
  782. ds=s->enc_write_ctx;
  783. rec= &(s->s3->wrec);
  784. if (s->enc_write_ctx == NULL)
  785. enc=NULL;
  786. else
  787. {
  788. int ivlen;
  789. enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
  790. /* For TLSv1.1 and later explicit IV */
  791. if (SSL_USE_EXPLICIT_IV(s)
  792. && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
  793. ivlen = EVP_CIPHER_iv_length(enc);
  794. else
  795. ivlen = 0;
  796. if (ivlen > 1)
  797. {
  798. if ( rec->data != rec->input)
  799. /* we can't write into the input stream:
  800. * Can this ever happen?? (steve)
  801. */
  802. fprintf(stderr,
  803. "%s:%d: rec->data != rec->input\n",
  804. __FILE__, __LINE__);
  805. else if (RAND_bytes(rec->input, ivlen) <= 0)
  806. return -1;
  807. }
  808. }
  809. }
  810. else
  811. {
  812. ds=s->enc_read_ctx;
  813. rec= &(s->s3->rrec);
  814. if (s->enc_read_ctx == NULL)
  815. enc=NULL;
  816. else
  817. enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
  818. }
  819. if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
  820. {
  821. memmove(rec->data,rec->input,rec->length);
  822. rec->input=rec->data;
  823. ret = 1;
  824. }
  825. else
  826. {
  827. l=rec->length;
  828. bs=EVP_CIPHER_block_size(ds->cipher);
  829. if ((bs != 1) && send)
  830. {
  831. i=bs-((int)l%bs);
  832. /* Add weird padding of upto 256 bytes */
  833. /* we need to add 'i' padding bytes of value j */
  834. j=i-1;
  835. for (k=(int)l; k<(int)(l+i); k++)
  836. rec->input[k]=j;
  837. l+=i;
  838. rec->length+=i;
  839. }
  840. if (!send)
  841. {
  842. if (l == 0 || l%bs != 0)
  843. return 0;
  844. }
  845. i = EVP_Cipher(ds,rec->data,rec->input,l);
  846. if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
  847. ?(i<0)
  848. :(i==0))
  849. return -1; /* AEAD can fail to verify MAC */
  850. ret = 1;
  851. if (EVP_MD_CTX_md(s->read_hash) != NULL)
  852. mac_size = EVP_MD_CTX_size(s->read_hash);
  853. if ((bs != 1) && !send)
  854. ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
  855. if (pad && !send)
  856. rec->length -= pad;
  857. }
  858. return ret;
  859. }
  860. int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
  861. {
  862. unsigned int ret;
  863. EVP_MD_CTX ctx, *d=NULL;
  864. int i;
  865. if (s->s3->handshake_buffer)
  866. if (!ssl3_digest_cached_records(s, free_handshake_buffer))
  867. return 0;
  868. for (i=0;i<SSL_MAX_DIGEST;i++)
  869. {
  870. if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
  871. {
  872. d=s->s3->handshake_dgst[i];
  873. break;
  874. }
  875. }
  876. if (!d) {
  877. OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
  878. return 0;
  879. }
  880. EVP_MD_CTX_init(&ctx);
  881. EVP_MD_CTX_copy_ex(&ctx,d);
  882. EVP_DigestFinal_ex(&ctx,out,&ret);
  883. EVP_MD_CTX_cleanup(&ctx);
  884. return((int)ret);
  885. }
  886. /* tls1_handshake_digest calculates the current handshake hash and writes it to
  887. * |out|, which has space for |out_len| bytes. It returns the number of bytes
  888. * written or -1 in the event of an error. This function works on a copy of the
  889. * underlying digests so can be called multiple times and prior to the final
  890. * update etc. */
  891. int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
  892. {
  893. const EVP_MD *md;
  894. EVP_MD_CTX ctx;
  895. int i, err = 0, len = 0;
  896. long mask;
  897. EVP_MD_CTX_init(&ctx);
  898. for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
  899. {
  900. int hash_size;
  901. unsigned int digest_len;
  902. EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
  903. if ((mask & ssl_get_algorithm2(s)) == 0)
  904. continue;
  905. hash_size = EVP_MD_size(md);
  906. if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
  907. {
  908. err = 1;
  909. break;
  910. }
  911. if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
  912. !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
  913. digest_len != (unsigned int)hash_size) /* internal error */
  914. {
  915. err = 1;
  916. break;
  917. }
  918. out += digest_len;
  919. out_len -= digest_len;
  920. len += digest_len;
  921. }
  922. EVP_MD_CTX_cleanup(&ctx);
  923. if (err != 0)
  924. return -1;
  925. return len;
  926. }
  927. int tls1_final_finish_mac(SSL *s,
  928. const char *str, int slen, unsigned char *out)
  929. {
  930. unsigned char buf[2*EVP_MAX_MD_SIZE];
  931. unsigned char buf2[12];
  932. int err=0;
  933. int digests_len;
  934. if (s->s3->handshake_buffer)
  935. if (!ssl3_digest_cached_records(s, free_handshake_buffer))
  936. return 0;
  937. digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
  938. if (digests_len < 0)
  939. {
  940. err = 1;
  941. digests_len = 0;
  942. }
  943. if (!tls1_PRF(ssl_get_algorithm2(s),
  944. str,slen, buf, digests_len, NULL,0,
  945. s->session->master_key,s->session->master_key_length,
  946. out,buf2,sizeof buf2))
  947. err = 1;
  948. if (err)
  949. return 0;
  950. else
  951. return sizeof buf2;
  952. }
  953. int tls1_mac(SSL *ssl, unsigned char *md, int send)
  954. {
  955. SSL3_RECORD *rec;
  956. unsigned char *seq;
  957. EVP_MD_CTX *hash;
  958. size_t md_size, orig_len;
  959. int i;
  960. EVP_MD_CTX hmac, *mac_ctx;
  961. unsigned char header[13];
  962. int t;
  963. if (send)
  964. {
  965. rec= &(ssl->s3->wrec);
  966. seq= &(ssl->s3->write_sequence[0]);
  967. hash=ssl->write_hash;
  968. }
  969. else
  970. {
  971. rec= &(ssl->s3->rrec);
  972. seq= &(ssl->s3->read_sequence[0]);
  973. hash=ssl->read_hash;
  974. }
  975. t=EVP_MD_CTX_size(hash);
  976. assert(t >= 0);
  977. md_size=t;
  978. if (!EVP_MD_CTX_copy(&hmac,hash))
  979. return -1;
  980. mac_ctx = &hmac;
  981. if (SSL_IS_DTLS(ssl))
  982. {
  983. unsigned char dtlsseq[8],*p=dtlsseq;
  984. s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
  985. memcpy (p,&seq[2],6);
  986. memcpy(header, dtlsseq, 8);
  987. }
  988. else
  989. memcpy(header, seq, 8);
  990. /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
  991. orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
  992. rec->type &= 0xff;
  993. header[8]=rec->type;
  994. header[9]=(unsigned char)(ssl->version>>8);
  995. header[10]=(unsigned char)(ssl->version);
  996. header[11]=(rec->length)>>8;
  997. header[12]=(rec->length)&0xff;
  998. if (!send &&
  999. EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  1000. ssl3_cbc_record_digest_supported(mac_ctx))
  1001. {
  1002. /* This is a CBC-encrypted record. We must avoid leaking any
  1003. * timing-side channel information about how many blocks of
  1004. * data we are hashing because that gives an attacker a
  1005. * timing-oracle. */
  1006. ssl3_cbc_digest_record(
  1007. mac_ctx,
  1008. md, &md_size,
  1009. header, rec->input,
  1010. rec->length + md_size, orig_len,
  1011. ssl->s3->read_mac_secret,
  1012. ssl->s3->read_mac_secret_size,
  1013. 0 /* not SSLv3 */);
  1014. }
  1015. else
  1016. {
  1017. EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
  1018. EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
  1019. t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
  1020. assert(t > 0);
  1021. }
  1022. EVP_MD_CTX_cleanup(&hmac);
  1023. if (!SSL_IS_DTLS(ssl))
  1024. {
  1025. for (i=7; i>=0; i--)
  1026. {
  1027. ++seq[i];
  1028. if (seq[i] != 0) break;
  1029. }
  1030. }
  1031. return(md_size);
  1032. }
  1033. int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
  1034. int len)
  1035. {
  1036. unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
  1037. if (s->s3->tmp.extended_master_secret)
  1038. {
  1039. uint8_t digests[2*EVP_MAX_MD_SIZE];
  1040. int digests_len;
  1041. if (s->s3->handshake_buffer)
  1042. {
  1043. /* The master secret is based on the handshake hash
  1044. * just after sending the ClientKeyExchange. However,
  1045. * we might have a client certificate to send, in which
  1046. * case we might need different hashes for the
  1047. * verification and thus still need the handshake
  1048. * buffer around. Keeping both a handshake buffer *and*
  1049. * running hashes isn't yet supported so, when it comes
  1050. * to calculating the Finished hash, we'll have to hash
  1051. * the handshake buffer again. */
  1052. if (!ssl3_digest_cached_records(s, dont_free_handshake_buffer))
  1053. return 0;
  1054. }
  1055. digests_len = tls1_handshake_digest(s, digests, sizeof(digests));
  1056. if (digests_len == -1)
  1057. {
  1058. return 0;
  1059. }
  1060. tls1_PRF(ssl_get_algorithm2(s),
  1061. TLS_MD_EXTENDED_MASTER_SECRET_CONST,
  1062. TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
  1063. digests, digests_len,
  1064. NULL, 0,
  1065. p, len,
  1066. s->session->master_key,
  1067. buff, sizeof(buff));
  1068. }
  1069. else
  1070. {
  1071. tls1_PRF(ssl_get_algorithm2(s),
  1072. TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
  1073. s->s3->client_random,SSL3_RANDOM_SIZE,
  1074. s->s3->server_random,SSL3_RANDOM_SIZE,
  1075. p, len,
  1076. s->session->master_key,buff,sizeof buff);
  1077. }
  1078. #ifdef SSL_DEBUG
  1079. fprintf(stderr, "Premaster Secret:\n");
  1080. BIO_dump_fp(stderr, (char *)p, len);
  1081. fprintf(stderr, "Client Random:\n");
  1082. BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
  1083. fprintf(stderr, "Server Random:\n");
  1084. BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
  1085. fprintf(stderr, "Master Secret:\n");
  1086. BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
  1087. #endif
  1088. #ifdef OPENSSL_SSL_TRACE_CRYPTO
  1089. if (s->msg_callback)
  1090. {
  1091. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
  1092. p, len, s, s->msg_callback_arg);
  1093. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
  1094. s->s3->client_random, SSL3_RANDOM_SIZE,
  1095. s, s->msg_callback_arg);
  1096. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
  1097. s->s3->server_random, SSL3_RANDOM_SIZE,
  1098. s, s->msg_callback_arg);
  1099. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
  1100. s->session->master_key,
  1101. SSL3_MASTER_SECRET_SIZE,
  1102. s, s->msg_callback_arg);
  1103. }
  1104. #endif
  1105. return(SSL3_MASTER_SECRET_SIZE);
  1106. }
  1107. int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
  1108. const char *label, size_t llen, const unsigned char *context,
  1109. size_t contextlen, int use_context)
  1110. {
  1111. unsigned char *buff;
  1112. unsigned char *val = NULL;
  1113. size_t vallen, currentvalpos;
  1114. int rv;
  1115. buff = OPENSSL_malloc(olen);
  1116. if (buff == NULL) goto err2;
  1117. /* construct PRF arguments
  1118. * we construct the PRF argument ourself rather than passing separate
  1119. * values into the TLS PRF to ensure that the concatenation of values
  1120. * does not create a prohibited label.
  1121. */
  1122. vallen = llen + SSL3_RANDOM_SIZE * 2;
  1123. if (use_context)
  1124. {
  1125. vallen += 2 + contextlen;
  1126. }
  1127. val = OPENSSL_malloc(vallen);
  1128. if (val == NULL) goto err2;
  1129. currentvalpos = 0;
  1130. memcpy(val + currentvalpos, (unsigned char *) label, llen);
  1131. currentvalpos += llen;
  1132. memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
  1133. currentvalpos += SSL3_RANDOM_SIZE;
  1134. memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
  1135. currentvalpos += SSL3_RANDOM_SIZE;
  1136. if (use_context)
  1137. {
  1138. val[currentvalpos] = (contextlen >> 8) & 0xff;
  1139. currentvalpos++;
  1140. val[currentvalpos] = contextlen & 0xff;
  1141. currentvalpos++;
  1142. if ((contextlen > 0) || (context != NULL))
  1143. {
  1144. memcpy(val + currentvalpos, context, contextlen);
  1145. }
  1146. }
  1147. /* disallow prohibited labels
  1148. * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
  1149. * 15, so size of val > max(prohibited label len) = 15 and the
  1150. * comparisons won't have buffer overflow
  1151. */
  1152. if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
  1153. TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
  1154. if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
  1155. TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
  1156. if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
  1157. TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
  1158. if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
  1159. TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
  1160. rv = tls1_PRF(ssl_get_algorithm2(s),
  1161. val, vallen,
  1162. NULL, 0,
  1163. NULL, 0,
  1164. s->session->master_key,s->session->master_key_length,
  1165. out,buff,olen);
  1166. goto ret;
  1167. err1:
  1168. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
  1169. rv = 0;
  1170. goto ret;
  1171. err2:
  1172. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
  1173. rv = 0;
  1174. ret:
  1175. if (buff != NULL) OPENSSL_free(buff);
  1176. if (val != NULL) OPENSSL_free(val);
  1177. return(rv);
  1178. }
  1179. int tls1_alert_code(int code)
  1180. {
  1181. switch (code)
  1182. {
  1183. case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
  1184. case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
  1185. case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
  1186. case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
  1187. case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
  1188. case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
  1189. case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
  1190. case SSL_AD_NO_CERTIFICATE: return(-1);
  1191. case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
  1192. case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
  1193. case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
  1194. case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
  1195. case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
  1196. case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
  1197. case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
  1198. case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
  1199. case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
  1200. case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
  1201. case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
  1202. case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
  1203. case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
  1204. case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
  1205. case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
  1206. case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
  1207. case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
  1208. case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
  1209. case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
  1210. case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
  1211. case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
  1212. case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
  1213. case SSL_AD_INAPPROPRIATE_FALLBACK:return(SSL3_AD_INAPPROPRIATE_FALLBACK);
  1214. default: return(-1);
  1215. }
  1216. }