t1_enc.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. /* ssl/t1_enc.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-2007 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. /* ====================================================================
  112. * Copyright 2005 Nokia. All rights reserved.
  113. *
  114. * The portions of the attached software ("Contribution") is developed by
  115. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  116. * license.
  117. *
  118. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  119. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  120. * support (see RFC 4279) to OpenSSL.
  121. *
  122. * No patent licenses or other rights except those expressly stated in
  123. * the OpenSSL open source license shall be deemed granted or received
  124. * expressly, by implication, estoppel, or otherwise.
  125. *
  126. * No assurances are provided by Nokia that the Contribution does not
  127. * infringe the patent or other intellectual property rights of any third
  128. * party or that the license provides you with all the necessary rights
  129. * to make use of the Contribution.
  130. *
  131. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  132. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  133. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  134. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  135. * OTHERWISE.
  136. */
  137. #include <stdio.h>
  138. #include "ssl_locl.h"
  139. #ifndef OPENSSL_NO_COMP
  140. # include <openssl/comp.h>
  141. #endif
  142. #include <openssl/evp.h>
  143. #include <openssl/hmac.h>
  144. #include <openssl/md5.h>
  145. #include <openssl/rand.h>
  146. #ifdef KSSL_DEBUG
  147. # include <openssl/des.h>
  148. #endif
  149. /* seed1 through seed5 are virtually concatenated */
  150. static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
  151. int sec_len,
  152. const void *seed1, int seed1_len,
  153. const void *seed2, int seed2_len,
  154. const void *seed3, int seed3_len,
  155. const void *seed4, int seed4_len,
  156. const void *seed5, int seed5_len,
  157. unsigned char *out, int olen)
  158. {
  159. int chunk;
  160. size_t j;
  161. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  162. EVP_PKEY *mac_key;
  163. unsigned char A1[EVP_MAX_MD_SIZE];
  164. size_t A1_len;
  165. int ret = 0;
  166. chunk = EVP_MD_size(md);
  167. OPENSSL_assert(chunk >= 0);
  168. EVP_MD_CTX_init(&ctx);
  169. EVP_MD_CTX_init(&ctx_tmp);
  170. EVP_MD_CTX_init(&ctx_init);
  171. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  172. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
  173. if (!mac_key)
  174. goto err;
  175. if (!EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key))
  176. goto err;
  177. if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
  178. goto err;
  179. if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
  180. goto err;
  181. if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
  182. goto err;
  183. if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
  184. goto err;
  185. if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
  186. goto err;
  187. if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
  188. goto err;
  189. if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
  190. goto err;
  191. for (;;) {
  192. /* Reinit mac contexts */
  193. if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
  194. goto err;
  195. if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
  196. goto err;
  197. if (olen > chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx))
  198. goto err;
  199. if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
  200. goto err;
  201. if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
  202. goto err;
  203. if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
  204. goto err;
  205. if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
  206. goto err;
  207. if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
  208. goto err;
  209. if (olen > chunk) {
  210. if (!EVP_DigestSignFinal(&ctx, out, &j))
  211. goto err;
  212. out += j;
  213. olen -= j;
  214. /* calc the next A1 value */
  215. if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
  216. goto err;
  217. } else { /* last one */
  218. if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
  219. goto err;
  220. memcpy(out, A1, olen);
  221. break;
  222. }
  223. }
  224. ret = 1;
  225. err:
  226. EVP_PKEY_free(mac_key);
  227. EVP_MD_CTX_cleanup(&ctx);
  228. EVP_MD_CTX_cleanup(&ctx_tmp);
  229. EVP_MD_CTX_cleanup(&ctx_init);
  230. OPENSSL_cleanse(A1, sizeof(A1));
  231. return ret;
  232. }
  233. /* seed1 through seed5 are virtually concatenated */
  234. static int tls1_PRF(long digest_mask,
  235. const void *seed1, int seed1_len,
  236. const void *seed2, int seed2_len,
  237. const void *seed3, int seed3_len,
  238. const void *seed4, int seed4_len,
  239. const void *seed5, int seed5_len,
  240. const unsigned char *sec, int slen,
  241. unsigned char *out1, unsigned char *out2, int olen)
  242. {
  243. int len, i, idx, count;
  244. const unsigned char *S1;
  245. long m;
  246. const EVP_MD *md;
  247. int ret = 0;
  248. /* Count number of digests and partition sec evenly */
  249. count = 0;
  250. for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
  251. if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask)
  252. count++;
  253. }
  254. if (!count) {
  255. /* Should never happen */
  256. SSLerr(SSL_F_TLS1_PRF, ERR_R_INTERNAL_ERROR);
  257. goto err;
  258. }
  259. len = slen / count;
  260. if (count == 1)
  261. slen = 0;
  262. S1 = sec;
  263. memset(out1, 0, olen);
  264. for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
  265. if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask) {
  266. if (!md) {
  267. SSLerr(SSL_F_TLS1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
  268. goto err;
  269. }
  270. if (!tls1_P_hash(md, S1, len + (slen & 1),
  271. seed1, seed1_len, seed2, seed2_len, seed3,
  272. seed3_len, seed4, seed4_len, seed5, seed5_len,
  273. out2, olen))
  274. goto err;
  275. S1 += len;
  276. for (i = 0; i < olen; i++) {
  277. out1[i] ^= out2[i];
  278. }
  279. }
  280. }
  281. ret = 1;
  282. err:
  283. return ret;
  284. }
  285. static int tls1_generate_key_block(SSL *s, unsigned char *km,
  286. unsigned char *tmp, int num)
  287. {
  288. int ret;
  289. ret = tls1_PRF(ssl_get_algorithm2(s),
  290. TLS_MD_KEY_EXPANSION_CONST,
  291. TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3->server_random,
  292. SSL3_RANDOM_SIZE, s->s3->client_random, SSL3_RANDOM_SIZE,
  293. NULL, 0, NULL, 0, s->session->master_key,
  294. s->session->master_key_length, km, tmp, num);
  295. #ifdef KSSL_DEBUG
  296. fprintf(stderr, "tls1_generate_key_block() ==> %d byte master_key =\n\t",
  297. s->session->master_key_length);
  298. {
  299. int i;
  300. for (i = 0; i < s->session->master_key_length; i++) {
  301. fprintf(stderr, "%02X", s->session->master_key[i]);
  302. }
  303. fprintf(stderr, "\n");
  304. }
  305. #endif /* KSSL_DEBUG */
  306. return ret;
  307. }
  308. int tls1_change_cipher_state(SSL *s, int which)
  309. {
  310. static const unsigned char empty[] = "";
  311. unsigned char *p, *mac_secret;
  312. unsigned char *exp_label;
  313. unsigned char tmp1[EVP_MAX_KEY_LENGTH];
  314. unsigned char tmp2[EVP_MAX_KEY_LENGTH];
  315. unsigned char iv1[EVP_MAX_IV_LENGTH * 2];
  316. unsigned char iv2[EVP_MAX_IV_LENGTH * 2];
  317. unsigned char *ms, *key, *iv;
  318. int client_write;
  319. EVP_CIPHER_CTX *dd;
  320. const EVP_CIPHER *c;
  321. #ifndef OPENSSL_NO_COMP
  322. const SSL_COMP *comp;
  323. #endif
  324. const EVP_MD *m;
  325. int mac_type;
  326. int *mac_secret_size;
  327. EVP_MD_CTX *mac_ctx;
  328. EVP_PKEY *mac_key;
  329. int is_export, n, i, j, k, exp_label_len, cl;
  330. int reuse_dd = 0;
  331. is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
  332. c = s->s3->tmp.new_sym_enc;
  333. m = s->s3->tmp.new_hash;
  334. mac_type = s->s3->tmp.new_mac_pkey_type;
  335. #ifndef OPENSSL_NO_COMP
  336. comp = s->s3->tmp.new_compression;
  337. #endif
  338. #ifdef KSSL_DEBUG
  339. fprintf(stderr, "tls1_change_cipher_state(which= %d) w/\n", which);
  340. fprintf(stderr, "\talg= %ld/%ld, comp= %p\n",
  341. s->s3->tmp.new_cipher->algorithm_mkey,
  342. s->s3->tmp.new_cipher->algorithm_auth, comp);
  343. fprintf(stderr, "\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c);
  344. fprintf(stderr, "\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n",
  345. c->nid, c->block_size, c->key_len, c->iv_len);
  346. fprintf(stderr, "\tkey_block: len= %d, data= ",
  347. s->s3->tmp.key_block_length);
  348. {
  349. int i;
  350. for (i = 0; i < s->s3->tmp.key_block_length; i++)
  351. fprintf(stderr, "%02x", s->s3->tmp.key_block[i]);
  352. fprintf(stderr, "\n");
  353. }
  354. #endif /* KSSL_DEBUG */
  355. if (which & SSL3_CC_READ) {
  356. if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
  357. s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
  358. else
  359. s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
  360. if (s->enc_read_ctx != NULL)
  361. reuse_dd = 1;
  362. else if ((s->enc_read_ctx =
  363. OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
  364. goto err;
  365. else
  366. /*
  367. * make sure it's intialized in case we exit later with an error
  368. */
  369. EVP_CIPHER_CTX_init(s->enc_read_ctx);
  370. dd = s->enc_read_ctx;
  371. mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
  372. if (mac_ctx == NULL)
  373. goto err;
  374. #ifndef OPENSSL_NO_COMP
  375. if (s->expand != NULL) {
  376. COMP_CTX_free(s->expand);
  377. s->expand = NULL;
  378. }
  379. if (comp != NULL) {
  380. s->expand = COMP_CTX_new(comp->method);
  381. if (s->expand == NULL) {
  382. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
  383. SSL_R_COMPRESSION_LIBRARY_ERROR);
  384. goto err2;
  385. }
  386. if (s->s3->rrec.comp == NULL)
  387. s->s3->rrec.comp = (unsigned char *)
  388. OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
  389. if (s->s3->rrec.comp == NULL)
  390. goto err;
  391. }
  392. #endif
  393. /*
  394. * this is done by dtls1_reset_seq_numbers for DTLS
  395. */
  396. if (!SSL_IS_DTLS(s))
  397. memset(&(s->s3->read_sequence[0]), 0, 8);
  398. mac_secret = &(s->s3->read_mac_secret[0]);
  399. mac_secret_size = &(s->s3->read_mac_secret_size);
  400. } else {
  401. if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
  402. s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
  403. else
  404. s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
  405. if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
  406. reuse_dd = 1;
  407. else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
  408. goto err;
  409. dd = s->enc_write_ctx;
  410. if (SSL_IS_DTLS(s)) {
  411. mac_ctx = EVP_MD_CTX_create();
  412. if (mac_ctx == NULL)
  413. goto err;
  414. s->write_hash = mac_ctx;
  415. } else {
  416. mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
  417. if (mac_ctx == NULL)
  418. goto err;
  419. }
  420. #ifndef OPENSSL_NO_COMP
  421. if (s->compress != NULL) {
  422. COMP_CTX_free(s->compress);
  423. s->compress = NULL;
  424. }
  425. if (comp != NULL) {
  426. s->compress = COMP_CTX_new(comp->method);
  427. if (s->compress == NULL) {
  428. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
  429. SSL_R_COMPRESSION_LIBRARY_ERROR);
  430. goto err2;
  431. }
  432. }
  433. #endif
  434. /*
  435. * this is done by dtls1_reset_seq_numbers for DTLS
  436. */
  437. if (!SSL_IS_DTLS(s))
  438. memset(&(s->s3->write_sequence[0]), 0, 8);
  439. mac_secret = &(s->s3->write_mac_secret[0]);
  440. mac_secret_size = &(s->s3->write_mac_secret_size);
  441. }
  442. if (reuse_dd)
  443. EVP_CIPHER_CTX_cleanup(dd);
  444. p = s->s3->tmp.key_block;
  445. i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
  446. cl = EVP_CIPHER_key_length(c);
  447. j = is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
  448. cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
  449. /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
  450. /* If GCM mode only part of IV comes from PRF */
  451. if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
  452. k = EVP_GCM_TLS_FIXED_IV_LEN;
  453. else
  454. k = EVP_CIPHER_iv_length(c);
  455. if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
  456. (which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
  457. ms = &(p[0]);
  458. n = i + i;
  459. key = &(p[n]);
  460. n += j + j;
  461. iv = &(p[n]);
  462. n += k + k;
  463. exp_label = (unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST;
  464. exp_label_len = TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
  465. client_write = 1;
  466. } else {
  467. n = i;
  468. ms = &(p[n]);
  469. n += i + j;
  470. key = &(p[n]);
  471. n += j + k;
  472. iv = &(p[n]);
  473. n += k;
  474. exp_label = (unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST;
  475. exp_label_len = TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
  476. client_write = 0;
  477. }
  478. if (n > s->s3->tmp.key_block_length) {
  479. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
  480. goto err2;
  481. }
  482. memcpy(mac_secret, ms, i);
  483. if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
  484. mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
  485. mac_secret, *mac_secret_size);
  486. if (mac_key == NULL
  487. || EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
  488. EVP_PKEY_free(mac_key);
  489. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
  490. goto err2;
  491. }
  492. EVP_PKEY_free(mac_key);
  493. }
  494. #ifdef TLS_DEBUG
  495. printf("which = %04X\nmac key=", which);
  496. {
  497. int z;
  498. for (z = 0; z < i; z++)
  499. printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
  500. }
  501. #endif
  502. if (is_export) {
  503. /*
  504. * In here I set both the read and write key/iv to the same value
  505. * since only the correct one will be used :-).
  506. */
  507. if (!tls1_PRF(ssl_get_algorithm2(s),
  508. exp_label, exp_label_len,
  509. s->s3->client_random, SSL3_RANDOM_SIZE,
  510. s->s3->server_random, SSL3_RANDOM_SIZE,
  511. NULL, 0, NULL, 0,
  512. key, j, tmp1, tmp2, EVP_CIPHER_key_length(c)))
  513. goto err2;
  514. key = tmp1;
  515. if (k > 0) {
  516. if (!tls1_PRF(ssl_get_algorithm2(s),
  517. TLS_MD_IV_BLOCK_CONST, TLS_MD_IV_BLOCK_CONST_SIZE,
  518. s->s3->client_random, SSL3_RANDOM_SIZE,
  519. s->s3->server_random, SSL3_RANDOM_SIZE,
  520. NULL, 0, NULL, 0, empty, 0, iv1, iv2, k * 2))
  521. goto err2;
  522. if (client_write)
  523. iv = iv1;
  524. else
  525. iv = &(iv1[k]);
  526. }
  527. }
  528. s->session->key_arg_length = 0;
  529. #ifdef KSSL_DEBUG
  530. {
  531. int i;
  532. fprintf(stderr, "EVP_CipherInit_ex(dd,c,key=,iv=,which)\n");
  533. fprintf(stderr, "\tkey= ");
  534. for (i = 0; i < c->key_len; i++)
  535. fprintf(stderr, "%02x", key[i]);
  536. fprintf(stderr, "\n");
  537. fprintf(stderr, "\t iv= ");
  538. for (i = 0; i < c->iv_len; i++)
  539. fprintf(stderr, "%02x", iv[i]);
  540. fprintf(stderr, "\n");
  541. }
  542. #endif /* KSSL_DEBUG */
  543. if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
  544. if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
  545. || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
  546. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
  547. goto err2;
  548. }
  549. } else {
  550. if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
  551. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
  552. goto err2;
  553. }
  554. }
  555. /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
  556. if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
  557. && !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
  558. *mac_secret_size, mac_secret)) {
  559. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
  560. goto err2;
  561. }
  562. #ifdef OPENSSL_SSL_TRACE_CRYPTO
  563. if (s->msg_callback) {
  564. int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
  565. if (*mac_secret_size)
  566. s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
  567. mac_secret, *mac_secret_size,
  568. s, s->msg_callback_arg);
  569. if (c->key_len)
  570. s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
  571. key, c->key_len, s, s->msg_callback_arg);
  572. if (k) {
  573. if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
  574. wh |= TLS1_RT_CRYPTO_FIXED_IV;
  575. else
  576. wh |= TLS1_RT_CRYPTO_IV;
  577. s->msg_callback(2, s->version, wh, iv, k, s, s->msg_callback_arg);
  578. }
  579. }
  580. #endif
  581. #ifdef TLS_DEBUG
  582. printf("which = %04X\nkey=", which);
  583. {
  584. int z;
  585. for (z = 0; z < EVP_CIPHER_key_length(c); z++)
  586. printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
  587. }
  588. printf("\niv=");
  589. {
  590. int z;
  591. for (z = 0; z < k; z++)
  592. printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
  593. }
  594. printf("\n");
  595. #endif
  596. OPENSSL_cleanse(tmp1, sizeof(tmp1));
  597. OPENSSL_cleanse(tmp2, sizeof(tmp1));
  598. OPENSSL_cleanse(iv1, sizeof(iv1));
  599. OPENSSL_cleanse(iv2, sizeof(iv2));
  600. return (1);
  601. err:
  602. SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
  603. err2:
  604. return (0);
  605. }
  606. int tls1_setup_key_block(SSL *s)
  607. {
  608. unsigned char *p1, *p2 = NULL;
  609. const EVP_CIPHER *c;
  610. const EVP_MD *hash;
  611. int num;
  612. SSL_COMP *comp;
  613. int mac_type = NID_undef, mac_secret_size = 0;
  614. int ret = 0;
  615. #ifdef KSSL_DEBUG
  616. fprintf(stderr, "tls1_setup_key_block()\n");
  617. #endif /* KSSL_DEBUG */
  618. if (s->s3->tmp.key_block_length != 0)
  619. return (1);
  620. if (!ssl_cipher_get_evp
  621. (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp)) {
  622. SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
  623. return (0);
  624. }
  625. s->s3->tmp.new_sym_enc = c;
  626. s->s3->tmp.new_hash = hash;
  627. s->s3->tmp.new_mac_pkey_type = mac_type;
  628. s->s3->tmp.new_mac_secret_size = mac_secret_size;
  629. num =
  630. EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
  631. num *= 2;
  632. ssl3_cleanup_key_block(s);
  633. if ((p1 = (unsigned char *)OPENSSL_malloc(num)) == NULL) {
  634. SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
  635. goto err;
  636. }
  637. s->s3->tmp.key_block_length = num;
  638. s->s3->tmp.key_block = p1;
  639. if ((p2 = (unsigned char *)OPENSSL_malloc(num)) == NULL) {
  640. SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
  641. goto err;
  642. }
  643. #ifdef TLS_DEBUG
  644. printf("client random\n");
  645. {
  646. int z;
  647. for (z = 0; z < SSL3_RANDOM_SIZE; z++)
  648. printf("%02X%c", s->s3->client_random[z],
  649. ((z + 1) % 16) ? ' ' : '\n');
  650. }
  651. printf("server random\n");
  652. {
  653. int z;
  654. for (z = 0; z < SSL3_RANDOM_SIZE; z++)
  655. printf("%02X%c", s->s3->server_random[z],
  656. ((z + 1) % 16) ? ' ' : '\n');
  657. }
  658. printf("pre-master\n");
  659. {
  660. int z;
  661. for (z = 0; z < s->session->master_key_length; z++)
  662. printf("%02X%c", s->session->master_key[z],
  663. ((z + 1) % 16) ? ' ' : '\n');
  664. }
  665. #endif
  666. if (!tls1_generate_key_block(s, p1, p2, num))
  667. goto err;
  668. #ifdef TLS_DEBUG
  669. printf("\nkey block\n");
  670. {
  671. int z;
  672. for (z = 0; z < num; z++)
  673. printf("%02X%c", p1[z], ((z + 1) % 16) ? ' ' : '\n');
  674. }
  675. #endif
  676. if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
  677. && s->method->version <= TLS1_VERSION) {
  678. /*
  679. * enable vulnerability countermeasure for CBC ciphers with known-IV
  680. * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
  681. */
  682. s->s3->need_empty_fragments = 1;
  683. if (s->session->cipher != NULL) {
  684. if (s->session->cipher->algorithm_enc == SSL_eNULL)
  685. s->s3->need_empty_fragments = 0;
  686. #ifndef OPENSSL_NO_RC4
  687. if (s->session->cipher->algorithm_enc == SSL_RC4)
  688. s->s3->need_empty_fragments = 0;
  689. #endif
  690. }
  691. }
  692. ret = 1;
  693. err:
  694. if (p2) {
  695. OPENSSL_cleanse(p2, num);
  696. OPENSSL_free(p2);
  697. }
  698. return (ret);
  699. }
  700. /*-
  701. * tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
  702. *
  703. * Returns:
  704. * 0: (in non-constant time) if the record is publically invalid (i.e. too
  705. * short etc).
  706. * 1: if the record's padding is valid / the encryption was successful.
  707. * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
  708. * an internal error occured.
  709. */
  710. int tls1_enc(SSL *s, int send)
  711. {
  712. SSL3_RECORD *rec;
  713. EVP_CIPHER_CTX *ds;
  714. unsigned long l;
  715. int bs, i, j, k, pad = 0, ret, mac_size = 0;
  716. const EVP_CIPHER *enc;
  717. if (send) {
  718. if (EVP_MD_CTX_md(s->write_hash)) {
  719. int n = EVP_MD_CTX_size(s->write_hash);
  720. OPENSSL_assert(n >= 0);
  721. }
  722. ds = s->enc_write_ctx;
  723. rec = &(s->s3->wrec);
  724. if (s->enc_write_ctx == NULL)
  725. enc = NULL;
  726. else {
  727. int ivlen;
  728. enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
  729. /* For TLSv1.1 and later explicit IV */
  730. if (SSL_USE_EXPLICIT_IV(s)
  731. && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
  732. ivlen = EVP_CIPHER_iv_length(enc);
  733. else
  734. ivlen = 0;
  735. if (ivlen > 1) {
  736. if (rec->data != rec->input)
  737. /*
  738. * we can't write into the input stream: Can this ever
  739. * happen?? (steve)
  740. */
  741. fprintf(stderr,
  742. "%s:%d: rec->data != rec->input\n",
  743. __FILE__, __LINE__);
  744. else if (RAND_bytes(rec->input, ivlen) <= 0)
  745. return -1;
  746. }
  747. }
  748. } else {
  749. if (EVP_MD_CTX_md(s->read_hash)) {
  750. int n = EVP_MD_CTX_size(s->read_hash);
  751. OPENSSL_assert(n >= 0);
  752. }
  753. ds = s->enc_read_ctx;
  754. rec = &(s->s3->rrec);
  755. if (s->enc_read_ctx == NULL)
  756. enc = NULL;
  757. else
  758. enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
  759. }
  760. #ifdef KSSL_DEBUG
  761. fprintf(stderr, "tls1_enc(%d)\n", send);
  762. #endif /* KSSL_DEBUG */
  763. if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
  764. memmove(rec->data, rec->input, rec->length);
  765. rec->input = rec->data;
  766. ret = 1;
  767. } else {
  768. l = rec->length;
  769. bs = EVP_CIPHER_block_size(ds->cipher);
  770. if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
  771. unsigned char buf[EVP_AEAD_TLS1_AAD_LEN], *seq;
  772. seq = send ? s->s3->write_sequence : s->s3->read_sequence;
  773. if (SSL_IS_DTLS(s)) {
  774. unsigned char dtlsseq[9], *p = dtlsseq;
  775. s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
  776. memcpy(p, &seq[2], 6);
  777. memcpy(buf, dtlsseq, 8);
  778. } else {
  779. memcpy(buf, seq, 8);
  780. for (i = 7; i >= 0; i--) { /* increment */
  781. ++seq[i];
  782. if (seq[i] != 0)
  783. break;
  784. }
  785. }
  786. buf[8] = rec->type;
  787. buf[9] = (unsigned char)(s->version >> 8);
  788. buf[10] = (unsigned char)(s->version);
  789. buf[11] = rec->length >> 8;
  790. buf[12] = rec->length & 0xff;
  791. pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  792. EVP_AEAD_TLS1_AAD_LEN, buf);
  793. if (pad <= 0)
  794. return -1;
  795. if (send) {
  796. l += pad;
  797. rec->length += pad;
  798. }
  799. } else if ((bs != 1) && send) {
  800. i = bs - ((int)l % bs);
  801. /* Add weird padding of upto 256 bytes */
  802. /* we need to add 'i' padding bytes of value j */
  803. j = i - 1;
  804. if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
  805. if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
  806. j++;
  807. }
  808. for (k = (int)l; k < (int)(l + i); k++)
  809. rec->input[k] = j;
  810. l += i;
  811. rec->length += i;
  812. }
  813. #ifdef KSSL_DEBUG
  814. {
  815. unsigned long ui;
  816. fprintf(stderr,
  817. "EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
  818. ds, rec->data, rec->input, l);
  819. fprintf(stderr,
  820. "\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%lu %lu], %d iv_len\n",
  821. ds->buf_len, ds->cipher->key_len, DES_KEY_SZ,
  822. DES_SCHEDULE_SZ, ds->cipher->iv_len);
  823. fprintf(stderr, "\t\tIV: ");
  824. for (i = 0; i < ds->cipher->iv_len; i++)
  825. fprintf(stderr, "%02X", ds->iv[i]);
  826. fprintf(stderr, "\n");
  827. fprintf(stderr, "\trec->input=");
  828. for (ui = 0; ui < l; ui++)
  829. fprintf(stderr, " %02x", rec->input[ui]);
  830. fprintf(stderr, "\n");
  831. }
  832. #endif /* KSSL_DEBUG */
  833. if (!send) {
  834. if (l == 0 || l % bs != 0)
  835. return 0;
  836. }
  837. i = EVP_Cipher(ds, rec->data, rec->input, l);
  838. if ((EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
  839. ? (i < 0)
  840. : (i == 0))
  841. return -1; /* AEAD can fail to verify MAC */
  842. if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
  843. rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  844. rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  845. rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
  846. }
  847. #ifdef KSSL_DEBUG
  848. {
  849. unsigned long i;
  850. fprintf(stderr, "\trec->data=");
  851. for (i = 0; i < l; i++)
  852. fprintf(stderr, " %02x", rec->data[i]);
  853. fprintf(stderr, "\n");
  854. }
  855. #endif /* KSSL_DEBUG */
  856. ret = 1;
  857. if (EVP_MD_CTX_md(s->read_hash) != NULL)
  858. mac_size = EVP_MD_CTX_size(s->read_hash);
  859. if ((bs != 1) && !send)
  860. ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
  861. if (pad && !send)
  862. rec->length -= pad;
  863. }
  864. return ret;
  865. }
  866. int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
  867. {
  868. unsigned int ret;
  869. EVP_MD_CTX ctx, *d = NULL;
  870. int i;
  871. if (s->s3->handshake_buffer)
  872. if (!ssl3_digest_cached_records(s))
  873. return 0;
  874. for (i = 0; i < SSL_MAX_DIGEST; i++) {
  875. if (s->s3->handshake_dgst[i]
  876. && EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
  877. d = s->s3->handshake_dgst[i];
  878. break;
  879. }
  880. }
  881. if (!d) {
  882. SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC, SSL_R_NO_REQUIRED_DIGEST);
  883. return 0;
  884. }
  885. EVP_MD_CTX_init(&ctx);
  886. if (EVP_MD_CTX_copy_ex(&ctx, d) <=0
  887. || EVP_DigestFinal_ex(&ctx, out, &ret) <= 0)
  888. ret = 0;
  889. EVP_MD_CTX_cleanup(&ctx);
  890. return ((int)ret);
  891. }
  892. int tls1_final_finish_mac(SSL *s,
  893. const char *str, int slen, unsigned char *out)
  894. {
  895. unsigned int i;
  896. EVP_MD_CTX ctx;
  897. unsigned char buf[2 * EVP_MAX_MD_SIZE];
  898. unsigned char *q, buf2[12];
  899. int idx;
  900. long mask;
  901. int err = 0;
  902. const EVP_MD *md;
  903. q = buf;
  904. if (s->s3->handshake_buffer)
  905. if (!ssl3_digest_cached_records(s))
  906. return 0;
  907. EVP_MD_CTX_init(&ctx);
  908. for (idx = 0; ssl_get_handshake_digest(idx, &mask, &md); idx++) {
  909. if (mask & ssl_get_algorithm2(s)) {
  910. int hashsize = EVP_MD_size(md);
  911. EVP_MD_CTX *hdgst = s->s3->handshake_dgst[idx];
  912. if (!hdgst || hashsize < 0
  913. || hashsize > (int)(sizeof buf - (size_t)(q - buf))) {
  914. /*
  915. * internal error: 'buf' is too small for this cipersuite!
  916. */
  917. err = 1;
  918. } else {
  919. if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
  920. !EVP_DigestFinal_ex(&ctx, q, &i) ||
  921. (i != (unsigned int)hashsize))
  922. err = 1;
  923. q += hashsize;
  924. }
  925. }
  926. }
  927. if (!tls1_PRF(ssl_get_algorithm2(s),
  928. str, slen, buf, (int)(q - buf), NULL, 0, NULL, 0, NULL, 0,
  929. s->session->master_key, s->session->master_key_length,
  930. out, buf2, sizeof buf2))
  931. err = 1;
  932. EVP_MD_CTX_cleanup(&ctx);
  933. OPENSSL_cleanse(buf, (int)(q - buf));
  934. OPENSSL_cleanse(buf2, sizeof(buf2));
  935. if (err)
  936. return 0;
  937. else
  938. return sizeof buf2;
  939. }
  940. int tls1_mac(SSL *ssl, unsigned char *md, int send)
  941. {
  942. SSL3_RECORD *rec;
  943. unsigned char *seq;
  944. EVP_MD_CTX *hash;
  945. size_t md_size, orig_len;
  946. int i;
  947. EVP_MD_CTX hmac, *mac_ctx;
  948. unsigned char header[13];
  949. int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
  950. : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
  951. int t;
  952. if (send) {
  953. rec = &(ssl->s3->wrec);
  954. seq = &(ssl->s3->write_sequence[0]);
  955. hash = ssl->write_hash;
  956. } else {
  957. rec = &(ssl->s3->rrec);
  958. seq = &(ssl->s3->read_sequence[0]);
  959. hash = ssl->read_hash;
  960. }
  961. t = EVP_MD_CTX_size(hash);
  962. OPENSSL_assert(t >= 0);
  963. md_size = t;
  964. /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
  965. if (stream_mac) {
  966. mac_ctx = hash;
  967. } else {
  968. if (!EVP_MD_CTX_copy(&hmac, hash))
  969. return -1;
  970. mac_ctx = &hmac;
  971. }
  972. if (SSL_IS_DTLS(ssl)) {
  973. unsigned char dtlsseq[8], *p = dtlsseq;
  974. s2n(send ? ssl->d1->w_epoch : ssl->d1->r_epoch, p);
  975. memcpy(p, &seq[2], 6);
  976. memcpy(header, dtlsseq, 8);
  977. } else
  978. memcpy(header, seq, 8);
  979. /*
  980. * kludge: tls1_cbc_remove_padding passes padding length in rec->type
  981. */
  982. orig_len = rec->length + md_size + ((unsigned int)rec->type >> 8);
  983. rec->type &= 0xff;
  984. header[8] = rec->type;
  985. header[9] = (unsigned char)(ssl->version >> 8);
  986. header[10] = (unsigned char)(ssl->version);
  987. header[11] = (rec->length) >> 8;
  988. header[12] = (rec->length) & 0xff;
  989. if (!send &&
  990. EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  991. ssl3_cbc_record_digest_supported(mac_ctx)) {
  992. /*
  993. * This is a CBC-encrypted record. We must avoid leaking any
  994. * timing-side channel information about how many blocks of data we
  995. * are hashing because that gives an attacker a timing-oracle.
  996. */
  997. /* Final param == not SSLv3 */
  998. if (ssl3_cbc_digest_record(mac_ctx,
  999. md, &md_size,
  1000. header, rec->input,
  1001. rec->length + md_size, orig_len,
  1002. ssl->s3->read_mac_secret,
  1003. ssl->s3->read_mac_secret_size, 0) <= 0) {
  1004. if (!stream_mac)
  1005. EVP_MD_CTX_cleanup(&hmac);
  1006. return -1;
  1007. }
  1008. } else {
  1009. if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
  1010. || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
  1011. || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
  1012. if (!stream_mac)
  1013. EVP_MD_CTX_cleanup(&hmac);
  1014. return -1;
  1015. }
  1016. #ifdef OPENSSL_FIPS
  1017. if (!send && FIPS_mode())
  1018. tls_fips_digest_extra(ssl->enc_read_ctx,
  1019. mac_ctx, rec->input, rec->length, orig_len);
  1020. #endif
  1021. }
  1022. if (!stream_mac)
  1023. EVP_MD_CTX_cleanup(&hmac);
  1024. #ifdef TLS_DEBUG
  1025. fprintf(stderr, "seq=");
  1026. {
  1027. int z;
  1028. for (z = 0; z < 8; z++)
  1029. fprintf(stderr, "%02X ", seq[z]);
  1030. fprintf(stderr, "\n");
  1031. }
  1032. fprintf(stderr, "rec=");
  1033. {
  1034. unsigned int z;
  1035. for (z = 0; z < rec->length; z++)
  1036. fprintf(stderr, "%02X ", rec->data[z]);
  1037. fprintf(stderr, "\n");
  1038. }
  1039. #endif
  1040. if (!SSL_IS_DTLS(ssl)) {
  1041. for (i = 7; i >= 0; i--) {
  1042. ++seq[i];
  1043. if (seq[i] != 0)
  1044. break;
  1045. }
  1046. }
  1047. #ifdef TLS_DEBUG
  1048. {
  1049. unsigned int z;
  1050. for (z = 0; z < md_size; z++)
  1051. fprintf(stderr, "%02X ", md[z]);
  1052. fprintf(stderr, "\n");
  1053. }
  1054. #endif
  1055. return (md_size);
  1056. }
  1057. int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
  1058. int len)
  1059. {
  1060. unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
  1061. const void *co = NULL, *so = NULL;
  1062. int col = 0, sol = 0;
  1063. #ifdef KSSL_DEBUG
  1064. fprintf(stderr, "tls1_generate_master_secret(%p,%p, %p, %d)\n", s, out, p,
  1065. len);
  1066. #endif /* KSSL_DEBUG */
  1067. #ifdef TLSEXT_TYPE_opaque_prf_input
  1068. if (s->s3->client_opaque_prf_input != NULL
  1069. && s->s3->server_opaque_prf_input != NULL
  1070. && s->s3->client_opaque_prf_input_len > 0
  1071. && s->s3->client_opaque_prf_input_len ==
  1072. s->s3->server_opaque_prf_input_len) {
  1073. co = s->s3->client_opaque_prf_input;
  1074. col = s->s3->server_opaque_prf_input_len;
  1075. so = s->s3->server_opaque_prf_input;
  1076. /*
  1077. * must be same as col (see
  1078. * draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1)
  1079. */
  1080. sol = s->s3->client_opaque_prf_input_len;
  1081. }
  1082. #endif
  1083. tls1_PRF(ssl_get_algorithm2(s),
  1084. TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
  1085. s->s3->client_random, SSL3_RANDOM_SIZE,
  1086. co, col,
  1087. s->s3->server_random, SSL3_RANDOM_SIZE,
  1088. so, sol, p, len, s->session->master_key, buff, sizeof buff);
  1089. OPENSSL_cleanse(buff, sizeof buff);
  1090. #ifdef SSL_DEBUG
  1091. fprintf(stderr, "Premaster Secret:\n");
  1092. BIO_dump_fp(stderr, (char *)p, len);
  1093. fprintf(stderr, "Client Random:\n");
  1094. BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
  1095. fprintf(stderr, "Server Random:\n");
  1096. BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
  1097. fprintf(stderr, "Master Secret:\n");
  1098. BIO_dump_fp(stderr, (char *)s->session->master_key,
  1099. SSL3_MASTER_SECRET_SIZE);
  1100. #endif
  1101. #ifdef OPENSSL_SSL_TRACE_CRYPTO
  1102. if (s->msg_callback) {
  1103. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
  1104. p, len, s, s->msg_callback_arg);
  1105. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
  1106. s->s3->client_random, SSL3_RANDOM_SIZE,
  1107. s, s->msg_callback_arg);
  1108. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
  1109. s->s3->server_random, SSL3_RANDOM_SIZE,
  1110. s, s->msg_callback_arg);
  1111. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
  1112. s->session->master_key,
  1113. SSL3_MASTER_SECRET_SIZE, s, s->msg_callback_arg);
  1114. }
  1115. #endif
  1116. #ifdef KSSL_DEBUG
  1117. fprintf(stderr, "tls1_generate_master_secret() complete\n");
  1118. #endif /* KSSL_DEBUG */
  1119. return (SSL3_MASTER_SECRET_SIZE);
  1120. }
  1121. int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
  1122. const char *label, size_t llen,
  1123. const unsigned char *context,
  1124. size_t contextlen, int use_context)
  1125. {
  1126. unsigned char *buff;
  1127. unsigned char *val = NULL;
  1128. size_t vallen, currentvalpos;
  1129. int rv;
  1130. #ifdef KSSL_DEBUG
  1131. fprintf(stderr, "tls1_export_keying_material(%p,%p,%lu,%s,%lu,%p,%lu)\n",
  1132. s, out, olen, label, llen, context, contextlen);
  1133. #endif /* KSSL_DEBUG */
  1134. buff = OPENSSL_malloc(olen);
  1135. if (buff == NULL)
  1136. goto err2;
  1137. /*
  1138. * construct PRF arguments we construct the PRF argument ourself rather
  1139. * than passing separate values into the TLS PRF to ensure that the
  1140. * concatenation of values does not create a prohibited label.
  1141. */
  1142. vallen = llen + SSL3_RANDOM_SIZE * 2;
  1143. if (use_context) {
  1144. vallen += 2 + contextlen;
  1145. }
  1146. val = OPENSSL_malloc(vallen);
  1147. if (val == NULL)
  1148. goto err2;
  1149. currentvalpos = 0;
  1150. memcpy(val + currentvalpos, (unsigned char *)label, llen);
  1151. currentvalpos += llen;
  1152. memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
  1153. currentvalpos += SSL3_RANDOM_SIZE;
  1154. memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
  1155. currentvalpos += SSL3_RANDOM_SIZE;
  1156. if (use_context) {
  1157. val[currentvalpos] = (contextlen >> 8) & 0xff;
  1158. currentvalpos++;
  1159. val[currentvalpos] = contextlen & 0xff;
  1160. currentvalpos++;
  1161. if ((contextlen > 0) || (context != NULL)) {
  1162. memcpy(val + currentvalpos, context, contextlen);
  1163. }
  1164. }
  1165. /*
  1166. * disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
  1167. * label len) = 15, so size of val > max(prohibited label len) = 15 and
  1168. * the comparisons won't have buffer overflow
  1169. */
  1170. if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
  1171. TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
  1172. goto err1;
  1173. if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
  1174. TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
  1175. goto err1;
  1176. if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
  1177. TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
  1178. goto err1;
  1179. if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
  1180. TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
  1181. goto err1;
  1182. rv = tls1_PRF(ssl_get_algorithm2(s),
  1183. val, vallen,
  1184. NULL, 0,
  1185. NULL, 0,
  1186. NULL, 0,
  1187. NULL, 0,
  1188. s->session->master_key, s->session->master_key_length,
  1189. out, buff, olen);
  1190. OPENSSL_cleanse(val, vallen);
  1191. OPENSSL_cleanse(buff, olen);
  1192. #ifdef KSSL_DEBUG
  1193. fprintf(stderr, "tls1_export_keying_material() complete\n");
  1194. #endif /* KSSL_DEBUG */
  1195. goto ret;
  1196. err1:
  1197. SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL,
  1198. SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
  1199. rv = 0;
  1200. goto ret;
  1201. err2:
  1202. SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
  1203. rv = 0;
  1204. ret:
  1205. if (buff != NULL)
  1206. OPENSSL_free(buff);
  1207. if (val != NULL)
  1208. OPENSSL_free(val);
  1209. return (rv);
  1210. }
  1211. int tls1_alert_code(int code)
  1212. {
  1213. switch (code) {
  1214. case SSL_AD_CLOSE_NOTIFY:
  1215. return (SSL3_AD_CLOSE_NOTIFY);
  1216. case SSL_AD_UNEXPECTED_MESSAGE:
  1217. return (SSL3_AD_UNEXPECTED_MESSAGE);
  1218. case SSL_AD_BAD_RECORD_MAC:
  1219. return (SSL3_AD_BAD_RECORD_MAC);
  1220. case SSL_AD_DECRYPTION_FAILED:
  1221. return (TLS1_AD_DECRYPTION_FAILED);
  1222. case SSL_AD_RECORD_OVERFLOW:
  1223. return (TLS1_AD_RECORD_OVERFLOW);
  1224. case SSL_AD_DECOMPRESSION_FAILURE:
  1225. return (SSL3_AD_DECOMPRESSION_FAILURE);
  1226. case SSL_AD_HANDSHAKE_FAILURE:
  1227. return (SSL3_AD_HANDSHAKE_FAILURE);
  1228. case SSL_AD_NO_CERTIFICATE:
  1229. return (-1);
  1230. case SSL_AD_BAD_CERTIFICATE:
  1231. return (SSL3_AD_BAD_CERTIFICATE);
  1232. case SSL_AD_UNSUPPORTED_CERTIFICATE:
  1233. return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
  1234. case SSL_AD_CERTIFICATE_REVOKED:
  1235. return (SSL3_AD_CERTIFICATE_REVOKED);
  1236. case SSL_AD_CERTIFICATE_EXPIRED:
  1237. return (SSL3_AD_CERTIFICATE_EXPIRED);
  1238. case SSL_AD_CERTIFICATE_UNKNOWN:
  1239. return (SSL3_AD_CERTIFICATE_UNKNOWN);
  1240. case SSL_AD_ILLEGAL_PARAMETER:
  1241. return (SSL3_AD_ILLEGAL_PARAMETER);
  1242. case SSL_AD_UNKNOWN_CA:
  1243. return (TLS1_AD_UNKNOWN_CA);
  1244. case SSL_AD_ACCESS_DENIED:
  1245. return (TLS1_AD_ACCESS_DENIED);
  1246. case SSL_AD_DECODE_ERROR:
  1247. return (TLS1_AD_DECODE_ERROR);
  1248. case SSL_AD_DECRYPT_ERROR:
  1249. return (TLS1_AD_DECRYPT_ERROR);
  1250. case SSL_AD_EXPORT_RESTRICTION:
  1251. return (TLS1_AD_EXPORT_RESTRICTION);
  1252. case SSL_AD_PROTOCOL_VERSION:
  1253. return (TLS1_AD_PROTOCOL_VERSION);
  1254. case SSL_AD_INSUFFICIENT_SECURITY:
  1255. return (TLS1_AD_INSUFFICIENT_SECURITY);
  1256. case SSL_AD_INTERNAL_ERROR:
  1257. return (TLS1_AD_INTERNAL_ERROR);
  1258. case SSL_AD_USER_CANCELLED:
  1259. return (TLS1_AD_USER_CANCELLED);
  1260. case SSL_AD_NO_RENEGOTIATION:
  1261. return (TLS1_AD_NO_RENEGOTIATION);
  1262. case SSL_AD_UNSUPPORTED_EXTENSION:
  1263. return (TLS1_AD_UNSUPPORTED_EXTENSION);
  1264. case SSL_AD_CERTIFICATE_UNOBTAINABLE:
  1265. return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
  1266. case SSL_AD_UNRECOGNIZED_NAME:
  1267. return (TLS1_AD_UNRECOGNIZED_NAME);
  1268. case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
  1269. return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
  1270. case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
  1271. return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
  1272. case SSL_AD_UNKNOWN_PSK_IDENTITY:
  1273. return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
  1274. case SSL_AD_INAPPROPRIATE_FALLBACK:
  1275. return (TLS1_AD_INAPPROPRIATE_FALLBACK);
  1276. #if 0
  1277. /* not appropriate for TLS, not used for DTLS */
  1278. case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE:
  1279. return (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  1280. #endif
  1281. default:
  1282. return (-1);
  1283. }
  1284. }