t1_enc.c 45 KB

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