t1_enc.c 37 KB

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