s3_srvr.c 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com).
  108. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  112. *
  113. * Portions of the attached software ("Contribution") are developed by
  114. * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
  115. *
  116. * The Contribution is licensed pursuant to the OpenSSL open source
  117. * license provided above.
  118. *
  119. * ECC cipher suite support in OpenSSL originally written by
  120. * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
  121. *
  122. */
  123. /* ====================================================================
  124. * Copyright 2005 Nokia. All rights reserved.
  125. *
  126. * The portions of the attached software ("Contribution") is developed by
  127. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  128. * license.
  129. *
  130. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  131. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  132. * support (see RFC 4279) to OpenSSL.
  133. *
  134. * No patent licenses or other rights except those expressly stated in
  135. * the OpenSSL open source license shall be deemed granted or received
  136. * expressly, by implication, estoppel, or otherwise.
  137. *
  138. * No assurances are provided by Nokia that the Contribution does not
  139. * infringe the patent or other intellectual property rights of any third
  140. * party or that the license provides you with all the necessary rights
  141. * to make use of the Contribution.
  142. *
  143. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  144. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  145. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  146. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  147. * OTHERWISE. */
  148. #include <openssl/ssl.h>
  149. #include <assert.h>
  150. #include <stdio.h>
  151. #include <string.h>
  152. #include <openssl/bn.h>
  153. #include <openssl/buf.h>
  154. #include <openssl/bytestring.h>
  155. #include <openssl/cipher.h>
  156. #include <openssl/dh.h>
  157. #include <openssl/ec.h>
  158. #include <openssl/ecdsa.h>
  159. #include <openssl/err.h>
  160. #include <openssl/evp.h>
  161. #include <openssl/hmac.h>
  162. #include <openssl/md5.h>
  163. #include <openssl/mem.h>
  164. #include <openssl/obj.h>
  165. #include <openssl/rand.h>
  166. #include <openssl/sha.h>
  167. #include <openssl/x509.h>
  168. #include "internal.h"
  169. #include "../crypto/internal.h"
  170. #include "../crypto/dh/internal.h"
  171. int ssl3_accept(SSL *ssl) {
  172. BUF_MEM *buf = NULL;
  173. uint32_t alg_a;
  174. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  175. int ret = -1;
  176. int new_state, state, skip = 0;
  177. assert(ssl->handshake_func == ssl3_accept);
  178. assert(ssl->server);
  179. assert(!SSL_IS_DTLS(ssl));
  180. ERR_clear_error();
  181. ERR_clear_system_error();
  182. if (ssl->info_callback != NULL) {
  183. cb = ssl->info_callback;
  184. } else if (ssl->ctx->info_callback != NULL) {
  185. cb = ssl->ctx->info_callback;
  186. }
  187. ssl->in_handshake++;
  188. if (ssl->cert == NULL) {
  189. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
  190. return -1;
  191. }
  192. for (;;) {
  193. state = ssl->state;
  194. switch (ssl->state) {
  195. case SSL_ST_ACCEPT:
  196. if (cb != NULL) {
  197. cb(ssl, SSL_CB_HANDSHAKE_START, 1);
  198. }
  199. if (ssl->init_buf == NULL) {
  200. buf = BUF_MEM_new();
  201. if (!buf || !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  202. ret = -1;
  203. goto end;
  204. }
  205. ssl->init_buf = buf;
  206. buf = NULL;
  207. }
  208. ssl->init_num = 0;
  209. /* Enable a write buffer. This groups handshake messages within a flight
  210. * into a single write. */
  211. if (!ssl_init_wbio_buffer(ssl, 1)) {
  212. ret = -1;
  213. goto end;
  214. }
  215. if (!ssl3_init_handshake_buffer(ssl)) {
  216. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  217. ret = -1;
  218. goto end;
  219. }
  220. if (!ssl->s3->have_version) {
  221. ssl->state = SSL3_ST_SR_INITIAL_BYTES;
  222. } else {
  223. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  224. }
  225. break;
  226. case SSL3_ST_SR_INITIAL_BYTES:
  227. ret = ssl3_get_initial_bytes(ssl);
  228. if (ret <= 0) {
  229. goto end;
  230. }
  231. /* ssl3_get_initial_bytes sets ssl->state to one of
  232. * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
  233. break;
  234. case SSL3_ST_SR_V2_CLIENT_HELLO:
  235. ret = ssl3_get_v2_client_hello(ssl);
  236. if (ret <= 0) {
  237. goto end;
  238. }
  239. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  240. break;
  241. case SSL3_ST_SR_CLNT_HELLO_A:
  242. case SSL3_ST_SR_CLNT_HELLO_B:
  243. case SSL3_ST_SR_CLNT_HELLO_C:
  244. case SSL3_ST_SR_CLNT_HELLO_D:
  245. ssl->shutdown = 0;
  246. ret = ssl3_get_client_hello(ssl);
  247. if (ret <= 0) {
  248. goto end;
  249. }
  250. ssl->state = SSL3_ST_SW_SRVR_HELLO_A;
  251. ssl->init_num = 0;
  252. break;
  253. case SSL3_ST_SW_SRVR_HELLO_A:
  254. case SSL3_ST_SW_SRVR_HELLO_B:
  255. ret = ssl3_send_server_hello(ssl);
  256. if (ret <= 0) {
  257. goto end;
  258. }
  259. if (ssl->hit) {
  260. if (ssl->tlsext_ticket_expected) {
  261. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  262. } else {
  263. ssl->state = SSL3_ST_SW_CHANGE_A;
  264. }
  265. } else {
  266. ssl->state = SSL3_ST_SW_CERT_A;
  267. }
  268. ssl->init_num = 0;
  269. break;
  270. case SSL3_ST_SW_CERT_A:
  271. case SSL3_ST_SW_CERT_B:
  272. if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
  273. ret = ssl3_send_server_certificate(ssl);
  274. if (ret <= 0) {
  275. goto end;
  276. }
  277. if (ssl->s3->tmp.certificate_status_expected) {
  278. ssl->state = SSL3_ST_SW_CERT_STATUS_A;
  279. } else {
  280. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  281. }
  282. } else {
  283. skip = 1;
  284. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  285. }
  286. ssl->init_num = 0;
  287. break;
  288. case SSL3_ST_SW_CERT_STATUS_A:
  289. case SSL3_ST_SW_CERT_STATUS_B:
  290. ret = ssl3_send_certificate_status(ssl);
  291. if (ret <= 0) {
  292. goto end;
  293. }
  294. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  295. ssl->init_num = 0;
  296. break;
  297. case SSL3_ST_SW_KEY_EXCH_A:
  298. case SSL3_ST_SW_KEY_EXCH_B:
  299. case SSL3_ST_SW_KEY_EXCH_C:
  300. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  301. /* Send a ServerKeyExchange message if:
  302. * - The key exchange is ephemeral or anonymous
  303. * Diffie-Hellman.
  304. * - There is a PSK identity hint.
  305. *
  306. * TODO(davidben): This logic is currently duplicated in d1_srvr.c. Fix
  307. * this. In the meantime, keep them in sync. */
  308. if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher) ||
  309. ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
  310. ret = ssl3_send_server_key_exchange(ssl);
  311. if (ret <= 0) {
  312. goto end;
  313. }
  314. } else {
  315. skip = 1;
  316. }
  317. ssl->state = SSL3_ST_SW_CERT_REQ_A;
  318. ssl->init_num = 0;
  319. break;
  320. case SSL3_ST_SW_CERT_REQ_A:
  321. case SSL3_ST_SW_CERT_REQ_B:
  322. if (ssl->s3->tmp.cert_request) {
  323. ret = ssl3_send_certificate_request(ssl);
  324. if (ret <= 0) {
  325. goto end;
  326. }
  327. } else {
  328. skip = 1;
  329. }
  330. ssl->state = SSL3_ST_SW_SRVR_DONE_A;
  331. ssl->init_num = 0;
  332. break;
  333. case SSL3_ST_SW_SRVR_DONE_A:
  334. case SSL3_ST_SW_SRVR_DONE_B:
  335. ret = ssl3_send_server_done(ssl);
  336. if (ret <= 0) {
  337. goto end;
  338. }
  339. ssl->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
  340. ssl->state = SSL3_ST_SW_FLUSH;
  341. ssl->init_num = 0;
  342. break;
  343. case SSL3_ST_SW_FLUSH:
  344. /* This code originally checked to see if any data was pending using
  345. * BIO_CTRL_INFO and then flushed. This caused problems as documented
  346. * in PR#1939. The proposed fix doesn't completely resolve this issue
  347. * as buggy implementations of BIO_CTRL_PENDING still exist. So instead
  348. * we just flush unconditionally. */
  349. ssl->rwstate = SSL_WRITING;
  350. if (BIO_flush(ssl->wbio) <= 0) {
  351. ret = -1;
  352. goto end;
  353. }
  354. ssl->rwstate = SSL_NOTHING;
  355. ssl->state = ssl->s3->tmp.next_state;
  356. break;
  357. case SSL3_ST_SR_CERT_A:
  358. case SSL3_ST_SR_CERT_B:
  359. if (ssl->s3->tmp.cert_request) {
  360. ret = ssl3_get_client_certificate(ssl);
  361. if (ret <= 0) {
  362. goto end;
  363. }
  364. }
  365. ssl->init_num = 0;
  366. ssl->state = SSL3_ST_SR_KEY_EXCH_A;
  367. break;
  368. case SSL3_ST_SR_KEY_EXCH_A:
  369. case SSL3_ST_SR_KEY_EXCH_B:
  370. case SSL3_ST_SR_KEY_EXCH_C:
  371. ret = ssl3_get_client_key_exchange(ssl);
  372. if (ret <= 0) {
  373. goto end;
  374. }
  375. ssl->state = SSL3_ST_SR_CERT_VRFY_A;
  376. ssl->init_num = 0;
  377. break;
  378. case SSL3_ST_SR_CERT_VRFY_A:
  379. case SSL3_ST_SR_CERT_VRFY_B:
  380. ret = ssl3_get_cert_verify(ssl);
  381. if (ret <= 0) {
  382. goto end;
  383. }
  384. ssl->state = SSL3_ST_SR_CHANGE;
  385. ssl->init_num = 0;
  386. break;
  387. case SSL3_ST_SR_CHANGE:
  388. ret = ssl->method->ssl_read_change_cipher_spec(ssl);
  389. if (ret <= 0) {
  390. goto end;
  391. }
  392. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_READ)) {
  393. ret = -1;
  394. goto end;
  395. }
  396. if (ssl->s3->next_proto_neg_seen) {
  397. ssl->state = SSL3_ST_SR_NEXT_PROTO_A;
  398. } else if (ssl->s3->tlsext_channel_id_valid) {
  399. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  400. } else {
  401. ssl->state = SSL3_ST_SR_FINISHED_A;
  402. }
  403. break;
  404. case SSL3_ST_SR_NEXT_PROTO_A:
  405. case SSL3_ST_SR_NEXT_PROTO_B:
  406. ret = ssl3_get_next_proto(ssl);
  407. if (ret <= 0) {
  408. goto end;
  409. }
  410. ssl->init_num = 0;
  411. if (ssl->s3->tlsext_channel_id_valid) {
  412. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  413. } else {
  414. ssl->state = SSL3_ST_SR_FINISHED_A;
  415. }
  416. break;
  417. case SSL3_ST_SR_CHANNEL_ID_A:
  418. case SSL3_ST_SR_CHANNEL_ID_B:
  419. ret = ssl3_get_channel_id(ssl);
  420. if (ret <= 0) {
  421. goto end;
  422. }
  423. ssl->init_num = 0;
  424. ssl->state = SSL3_ST_SR_FINISHED_A;
  425. break;
  426. case SSL3_ST_SR_FINISHED_A:
  427. case SSL3_ST_SR_FINISHED_B:
  428. ret = ssl3_get_finished(ssl, SSL3_ST_SR_FINISHED_A,
  429. SSL3_ST_SR_FINISHED_B);
  430. if (ret <= 0) {
  431. goto end;
  432. }
  433. if (ssl->hit) {
  434. ssl->state = SSL_ST_OK;
  435. } else if (ssl->tlsext_ticket_expected) {
  436. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  437. } else {
  438. ssl->state = SSL3_ST_SW_CHANGE_A;
  439. }
  440. /* If this is a full handshake with ChannelID then record the hashshake
  441. * hashes in |ssl->session| in case we need them to verify a ChannelID
  442. * signature on a resumption of this session in the future. */
  443. if (!ssl->hit && ssl->s3->tlsext_channel_id_valid) {
  444. ret = tls1_record_handshake_hashes_for_channel_id(ssl);
  445. if (ret <= 0) {
  446. goto end;
  447. }
  448. }
  449. ssl->init_num = 0;
  450. break;
  451. case SSL3_ST_SW_SESSION_TICKET_A:
  452. case SSL3_ST_SW_SESSION_TICKET_B:
  453. ret = ssl3_send_new_session_ticket(ssl);
  454. if (ret <= 0) {
  455. goto end;
  456. }
  457. ssl->state = SSL3_ST_SW_CHANGE_A;
  458. ssl->init_num = 0;
  459. break;
  460. case SSL3_ST_SW_CHANGE_A:
  461. case SSL3_ST_SW_CHANGE_B:
  462. ret = ssl3_send_change_cipher_spec(ssl, SSL3_ST_SW_CHANGE_A,
  463. SSL3_ST_SW_CHANGE_B);
  464. if (ret <= 0) {
  465. goto end;
  466. }
  467. ssl->state = SSL3_ST_SW_FINISHED_A;
  468. ssl->init_num = 0;
  469. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
  470. ret = -1;
  471. goto end;
  472. }
  473. break;
  474. case SSL3_ST_SW_FINISHED_A:
  475. case SSL3_ST_SW_FINISHED_B:
  476. ret = ssl3_send_finished(ssl, SSL3_ST_SW_FINISHED_A,
  477. SSL3_ST_SW_FINISHED_B);
  478. if (ret <= 0) {
  479. goto end;
  480. }
  481. ssl->state = SSL3_ST_SW_FLUSH;
  482. if (ssl->hit) {
  483. ssl->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
  484. } else {
  485. ssl->s3->tmp.next_state = SSL_ST_OK;
  486. }
  487. ssl->init_num = 0;
  488. break;
  489. case SSL_ST_OK:
  490. /* clean a few things up */
  491. ssl3_cleanup_key_block(ssl);
  492. BUF_MEM_free(ssl->init_buf);
  493. ssl->init_buf = NULL;
  494. /* remove buffering on output */
  495. ssl_free_wbio_buffer(ssl);
  496. ssl->init_num = 0;
  497. /* If we aren't retaining peer certificates then we can discard it
  498. * now. */
  499. if (ssl->ctx->retain_only_sha256_of_client_certs) {
  500. X509_free(ssl->session->peer);
  501. ssl->session->peer = NULL;
  502. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  503. ssl->session->cert_chain = NULL;
  504. }
  505. ssl->s3->initial_handshake_complete = 1;
  506. ssl_update_cache(ssl, SSL_SESS_CACHE_SERVER);
  507. if (cb != NULL) {
  508. cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  509. }
  510. ret = 1;
  511. goto end;
  512. default:
  513. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  514. ret = -1;
  515. goto end;
  516. }
  517. if (!ssl->s3->tmp.reuse_message && !skip && cb != NULL &&
  518. ssl->state != state) {
  519. new_state = ssl->state;
  520. ssl->state = state;
  521. cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
  522. ssl->state = new_state;
  523. }
  524. skip = 0;
  525. }
  526. end:
  527. ssl->in_handshake--;
  528. BUF_MEM_free(buf);
  529. if (cb != NULL) {
  530. cb(ssl, SSL_CB_ACCEPT_EXIT, ret);
  531. }
  532. return ret;
  533. }
  534. int ssl3_get_initial_bytes(SSL *ssl) {
  535. /* Read the first 5 bytes, the size of the TLS record header. This is
  536. * sufficient to detect a V2ClientHello and ensures that we never read beyond
  537. * the first record. */
  538. int ret = ssl_read_buffer_extend_to(ssl, SSL3_RT_HEADER_LENGTH);
  539. if (ret <= 0) {
  540. return ret;
  541. }
  542. assert(ssl_read_buffer_len(ssl) == SSL3_RT_HEADER_LENGTH);
  543. const uint8_t *p = ssl_read_buffer(ssl);
  544. /* Some dedicated error codes for protocol mixups should the application wish
  545. * to interpret them differently. (These do not overlap with ClientHello or
  546. * V2ClientHello.) */
  547. if (strncmp("GET ", (const char *)p, 4) == 0 ||
  548. strncmp("POST ", (const char *)p, 5) == 0 ||
  549. strncmp("HEAD ", (const char *)p, 5) == 0 ||
  550. strncmp("PUT ", (const char *)p, 4) == 0) {
  551. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTP_REQUEST);
  552. return -1;
  553. }
  554. if (strncmp("CONNE", (const char *)p, 5) == 0) {
  555. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTPS_PROXY_REQUEST);
  556. return -1;
  557. }
  558. /* Determine if this is a V2ClientHello. */
  559. if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
  560. p[3] >= SSL3_VERSION_MAJOR) {
  561. /* This is a V2ClientHello. */
  562. ssl->state = SSL3_ST_SR_V2_CLIENT_HELLO;
  563. return 1;
  564. }
  565. /* Fall through to the standard logic. */
  566. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  567. return 1;
  568. }
  569. int ssl3_get_v2_client_hello(SSL *ssl) {
  570. const uint8_t *p;
  571. int ret;
  572. CBS v2_client_hello, cipher_specs, session_id, challenge;
  573. size_t msg_length, rand_len, len;
  574. uint8_t msg_type;
  575. uint16_t version, cipher_spec_length, session_id_length, challenge_length;
  576. CBB client_hello, hello_body, cipher_suites;
  577. uint8_t random[SSL3_RANDOM_SIZE];
  578. /* Determine the length of the V2ClientHello. */
  579. assert(ssl_read_buffer_len(ssl) >= SSL3_RT_HEADER_LENGTH);
  580. p = ssl_read_buffer(ssl);
  581. msg_length = ((p[0] & 0x7f) << 8) | p[1];
  582. if (msg_length > (1024 * 4)) {
  583. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  584. return -1;
  585. }
  586. if (msg_length < SSL3_RT_HEADER_LENGTH - 2) {
  587. /* Reject lengths that are too short early. We have already read
  588. * |SSL3_RT_HEADER_LENGTH| bytes, so we should not attempt to process an
  589. * (invalid) V2ClientHello which would be shorter than that. */
  590. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_LENGTH_MISMATCH);
  591. return -1;
  592. }
  593. /* Read the remainder of the V2ClientHello. */
  594. ret = ssl_read_buffer_extend_to(ssl, 2 + msg_length);
  595. if (ret <= 0) {
  596. return ret;
  597. }
  598. assert(ssl_read_buffer_len(ssl) == msg_length + 2);
  599. CBS_init(&v2_client_hello, ssl_read_buffer(ssl) + 2, msg_length);
  600. /* The V2ClientHello without the length is incorporated into the handshake
  601. * hash. */
  602. if (!ssl3_update_handshake_hash(ssl, CBS_data(&v2_client_hello),
  603. CBS_len(&v2_client_hello))) {
  604. return -1;
  605. }
  606. if (ssl->msg_callback) {
  607. ssl->msg_callback(0, SSL2_VERSION, 0, CBS_data(&v2_client_hello),
  608. CBS_len(&v2_client_hello), ssl, ssl->msg_callback_arg);
  609. }
  610. if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
  611. !CBS_get_u16(&v2_client_hello, &version) ||
  612. !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
  613. !CBS_get_u16(&v2_client_hello, &session_id_length) ||
  614. !CBS_get_u16(&v2_client_hello, &challenge_length) ||
  615. !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
  616. !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
  617. !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
  618. CBS_len(&v2_client_hello) != 0) {
  619. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  620. return -1;
  621. }
  622. /* msg_type has already been checked. */
  623. assert(msg_type == SSL2_MT_CLIENT_HELLO);
  624. /* The client_random is the V2ClientHello challenge. Truncate or
  625. * left-pad with zeros as needed. */
  626. memset(random, 0, SSL3_RANDOM_SIZE);
  627. rand_len = CBS_len(&challenge);
  628. if (rand_len > SSL3_RANDOM_SIZE) {
  629. rand_len = SSL3_RANDOM_SIZE;
  630. }
  631. memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
  632. rand_len);
  633. /* Write out an equivalent SSLv3 ClientHello. */
  634. CBB_zero(&client_hello);
  635. if (!CBB_init_fixed(&client_hello, (uint8_t *)ssl->init_buf->data,
  636. ssl->init_buf->max) ||
  637. !CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
  638. !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
  639. !CBB_add_u16(&hello_body, version) ||
  640. !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
  641. /* No session id. */
  642. !CBB_add_u8(&hello_body, 0) ||
  643. !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
  644. CBB_cleanup(&client_hello);
  645. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  646. return -1;
  647. }
  648. /* Copy the cipher suites. */
  649. while (CBS_len(&cipher_specs) > 0) {
  650. uint32_t cipher_spec;
  651. if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
  652. CBB_cleanup(&client_hello);
  653. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  654. return -1;
  655. }
  656. /* Skip SSLv2 ciphers. */
  657. if ((cipher_spec & 0xff0000) != 0) {
  658. continue;
  659. }
  660. if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
  661. CBB_cleanup(&client_hello);
  662. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  663. return -1;
  664. }
  665. }
  666. /* Add the null compression scheme and finish. */
  667. if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
  668. !CBB_finish(&client_hello, NULL, &len)) {
  669. CBB_cleanup(&client_hello);
  670. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  671. return -1;
  672. }
  673. /* Mark the message for "re"-use by the version-specific method. */
  674. ssl->s3->tmp.reuse_message = 1;
  675. ssl->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
  676. /* The handshake message header is 4 bytes. */
  677. ssl->s3->tmp.message_size = len - 4;
  678. /* Consume and discard the V2ClientHello. */
  679. ssl_read_buffer_consume(ssl, 2 + msg_length);
  680. ssl_read_buffer_discard(ssl);
  681. return 1;
  682. }
  683. int ssl3_get_client_hello(SSL *ssl) {
  684. int ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
  685. long n;
  686. const SSL_CIPHER *c;
  687. STACK_OF(SSL_CIPHER) *ciphers = NULL;
  688. struct ssl_early_callback_ctx early_ctx;
  689. CBS client_hello;
  690. uint16_t client_version;
  691. CBS client_random, session_id, cipher_suites, compression_methods;
  692. SSL_SESSION *session = NULL;
  693. /* We do this so that we will respond with our native type. If we are TLSv1
  694. * and we get SSLv3, we will respond with TLSv1, This down switching should
  695. * be handled by a different method. If we are SSLv3, we will respond with
  696. * SSLv3, even if prompted with TLSv1. */
  697. switch (ssl->state) {
  698. case SSL3_ST_SR_CLNT_HELLO_A:
  699. case SSL3_ST_SR_CLNT_HELLO_B:
  700. n = ssl->method->ssl_get_message(
  701. ssl, SSL3_ST_SR_CLNT_HELLO_A, SSL3_ST_SR_CLNT_HELLO_B,
  702. SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH,
  703. ssl_hash_message, &ok);
  704. if (!ok) {
  705. return n;
  706. }
  707. ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
  708. /* fallthrough */
  709. case SSL3_ST_SR_CLNT_HELLO_C:
  710. case SSL3_ST_SR_CLNT_HELLO_D:
  711. /* We have previously parsed the ClientHello message, and can't call
  712. * ssl_get_message again without hashing the message into the Finished
  713. * digest again. */
  714. n = ssl->init_num;
  715. memset(&early_ctx, 0, sizeof(early_ctx));
  716. early_ctx.ssl = ssl;
  717. early_ctx.client_hello = ssl->init_msg;
  718. early_ctx.client_hello_len = n;
  719. if (!ssl_early_callback_init(&early_ctx)) {
  720. al = SSL_AD_DECODE_ERROR;
  721. OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
  722. goto f_err;
  723. }
  724. if (ssl->state == SSL3_ST_SR_CLNT_HELLO_C &&
  725. ssl->ctx->select_certificate_cb != NULL) {
  726. ssl->state = SSL3_ST_SR_CLNT_HELLO_D;
  727. switch (ssl->ctx->select_certificate_cb(&early_ctx)) {
  728. case 0:
  729. ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  730. goto err;
  731. case -1:
  732. /* Connection rejected. */
  733. al = SSL_AD_ACCESS_DENIED;
  734. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  735. goto f_err;
  736. default:
  737. /* fallthrough */;
  738. }
  739. }
  740. ssl->state = SSL3_ST_SR_CLNT_HELLO_D;
  741. break;
  742. default:
  743. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  744. return -1;
  745. }
  746. CBS_init(&client_hello, ssl->init_msg, n);
  747. if (!CBS_get_u16(&client_hello, &client_version) ||
  748. !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
  749. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  750. CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  751. al = SSL_AD_DECODE_ERROR;
  752. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  753. goto f_err;
  754. }
  755. /* use version from inside client hello, not from record header (may differ:
  756. * see RFC 2246, Appendix E, second paragraph) */
  757. ssl->client_version = client_version;
  758. /* Load the client random. */
  759. memcpy(ssl->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
  760. if (SSL_IS_DTLS(ssl)) {
  761. CBS cookie;
  762. if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
  763. CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
  764. al = SSL_AD_DECODE_ERROR;
  765. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  766. goto f_err;
  767. }
  768. }
  769. /* Note: This codepath may run twice if |ssl_get_prev_session| completes
  770. * asynchronously.
  771. *
  772. * TODO(davidben): Clean up the order of events around ClientHello
  773. * processing. */
  774. if (!ssl->s3->have_version) {
  775. /* Select version to use */
  776. uint16_t version = ssl3_get_mutual_version(ssl, client_version);
  777. if (version == 0) {
  778. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  779. ssl->version = ssl->client_version;
  780. al = SSL_AD_PROTOCOL_VERSION;
  781. goto f_err;
  782. }
  783. ssl->version = version;
  784. ssl->s3->enc_method = ssl3_get_enc_method(version);
  785. assert(ssl->s3->enc_method != NULL);
  786. /* At this point, the connection's version is known and |ssl->version| is
  787. * fixed. Begin enforcing the record-layer version. */
  788. ssl->s3->have_version = 1;
  789. } else if (SSL_IS_DTLS(ssl) ? (ssl->client_version > ssl->version)
  790. : (ssl->client_version < ssl->version)) {
  791. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
  792. al = SSL_AD_PROTOCOL_VERSION;
  793. goto f_err;
  794. }
  795. ssl->hit = 0;
  796. int send_new_ticket = 0;
  797. switch (ssl_get_prev_session(ssl, &session, &send_new_ticket, &early_ctx)) {
  798. case ssl_session_success:
  799. break;
  800. case ssl_session_error:
  801. goto err;
  802. case ssl_session_retry:
  803. ssl->rwstate = SSL_PENDING_SESSION;
  804. goto err;
  805. }
  806. ssl->tlsext_ticket_expected = send_new_ticket;
  807. /* The EMS state is needed when making the resumption decision, but
  808. * extensions are not normally parsed until later. This detects the EMS
  809. * extension for the resumption decision and it's checked against the result
  810. * of the normal parse later in this function. */
  811. const uint8_t *ems_data;
  812. size_t ems_len;
  813. int have_extended_master_secret =
  814. ssl->version != SSL3_VERSION &&
  815. SSL_early_callback_ctx_extension_get(&early_ctx,
  816. TLSEXT_TYPE_extended_master_secret,
  817. &ems_data, &ems_len) &&
  818. ems_len == 0;
  819. if (session != NULL) {
  820. if (session->extended_master_secret &&
  821. !have_extended_master_secret) {
  822. /* A ClientHello without EMS that attempts to resume a session with EMS
  823. * is fatal to the connection. */
  824. al = SSL_AD_HANDSHAKE_FAILURE;
  825. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  826. goto f_err;
  827. }
  828. ssl->hit =
  829. /* Only resume if the session's version matches the negotiated version:
  830. * most clients do not accept a mismatch. */
  831. ssl->version == session->ssl_version &&
  832. /* If the client offers the EMS extension, but the previous session
  833. * didn't use it, then negotiate a new session. */
  834. have_extended_master_secret == session->extended_master_secret;
  835. }
  836. if (ssl->hit) {
  837. /* Use the new session. */
  838. SSL_SESSION_free(ssl->session);
  839. ssl->session = session;
  840. session = NULL;
  841. ssl->verify_result = ssl->session->verify_result;
  842. } else {
  843. if (!ssl_get_new_session(ssl, 1 /* server */)) {
  844. goto err;
  845. }
  846. /* Clear the session ID if we want the session to be single-use. */
  847. if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
  848. ssl->session->session_id_length = 0;
  849. }
  850. }
  851. if (ssl->ctx->dos_protection_cb != NULL &&
  852. ssl->ctx->dos_protection_cb(&early_ctx) == 0) {
  853. /* Connection rejected for DOS reasons. */
  854. al = SSL_AD_ACCESS_DENIED;
  855. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  856. goto f_err;
  857. }
  858. if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
  859. CBS_len(&cipher_suites) == 0 ||
  860. CBS_len(&cipher_suites) % 2 != 0 ||
  861. !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
  862. CBS_len(&compression_methods) == 0) {
  863. al = SSL_AD_DECODE_ERROR;
  864. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  865. goto f_err;
  866. }
  867. ciphers = ssl_bytes_to_cipher_list(ssl, &cipher_suites);
  868. if (ciphers == NULL) {
  869. goto err;
  870. }
  871. /* If it is a hit, check that the cipher is in the list. */
  872. if (ssl->hit) {
  873. size_t j;
  874. int found_cipher = 0;
  875. uint32_t id = ssl->session->cipher->id;
  876. for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
  877. c = sk_SSL_CIPHER_value(ciphers, j);
  878. if (c->id == id) {
  879. found_cipher = 1;
  880. break;
  881. }
  882. }
  883. if (!found_cipher) {
  884. /* we need to have the cipher in the cipher list if we are asked to reuse
  885. * it */
  886. al = SSL_AD_ILLEGAL_PARAMETER;
  887. OPENSSL_PUT_ERROR(SSL, SSL_R_REQUIRED_CIPHER_MISSING);
  888. goto f_err;
  889. }
  890. }
  891. /* Only null compression is supported. */
  892. if (memchr(CBS_data(&compression_methods), 0,
  893. CBS_len(&compression_methods)) == NULL) {
  894. al = SSL_AD_ILLEGAL_PARAMETER;
  895. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMPRESSION_SPECIFIED);
  896. goto f_err;
  897. }
  898. /* TLS extensions. */
  899. if (ssl->version >= SSL3_VERSION &&
  900. !ssl_parse_clienthello_tlsext(ssl, &client_hello)) {
  901. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  902. goto err;
  903. }
  904. /* There should be nothing left over in the record. */
  905. if (CBS_len(&client_hello) != 0) {
  906. /* wrong packet length */
  907. al = SSL_AD_DECODE_ERROR;
  908. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  909. goto f_err;
  910. }
  911. if (have_extended_master_secret != ssl->s3->tmp.extended_master_secret) {
  912. al = SSL_AD_INTERNAL_ERROR;
  913. OPENSSL_PUT_ERROR(SSL, SSL_R_EMS_STATE_INCONSISTENT);
  914. goto f_err;
  915. }
  916. /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
  917. if (!ssl->hit) {
  918. if (ciphers == NULL) {
  919. al = SSL_AD_ILLEGAL_PARAMETER;
  920. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_PASSED);
  921. goto f_err;
  922. }
  923. /* Let cert callback update server certificates if required */
  924. if (ssl->cert->cert_cb) {
  925. int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
  926. if (rv == 0) {
  927. al = SSL_AD_INTERNAL_ERROR;
  928. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
  929. goto f_err;
  930. }
  931. if (rv < 0) {
  932. ssl->rwstate = SSL_X509_LOOKUP;
  933. goto err;
  934. }
  935. ssl->rwstate = SSL_NOTHING;
  936. }
  937. c = ssl3_choose_cipher(ssl, ciphers, ssl_get_cipher_preferences(ssl));
  938. if (c == NULL) {
  939. al = SSL_AD_HANDSHAKE_FAILURE;
  940. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
  941. goto f_err;
  942. }
  943. ssl->session->cipher = c;
  944. ssl->s3->tmp.new_cipher = c;
  945. /* Determine whether to request a client certificate. */
  946. ssl->s3->tmp.cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
  947. /* Only request a certificate if Channel ID isn't negotiated. */
  948. if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  949. ssl->s3->tlsext_channel_id_valid) {
  950. ssl->s3->tmp.cert_request = 0;
  951. }
  952. /* Plain PSK forbids Certificate and CertificateRequest. */
  953. if (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) {
  954. ssl->s3->tmp.cert_request = 0;
  955. }
  956. } else {
  957. /* Session-id reuse */
  958. ssl->s3->tmp.new_cipher = ssl->session->cipher;
  959. ssl->s3->tmp.cert_request = 0;
  960. }
  961. /* Now that the cipher is known, initialize the handshake hash. */
  962. if (!ssl3_init_handshake_hash(ssl)) {
  963. goto f_err;
  964. }
  965. /* In TLS 1.2, client authentication requires hashing the handshake transcript
  966. * under a different hash. Otherwise, release the handshake buffer. */
  967. if (!ssl->s3->tmp.cert_request ||
  968. ssl3_protocol_version(ssl) < TLS1_2_VERSION) {
  969. ssl3_free_handshake_buffer(ssl);
  970. }
  971. /* we now have the following setup;
  972. * client_random
  973. * cipher_list - our prefered list of ciphers
  974. * ciphers - the clients prefered list of ciphers
  975. * compression - basically ignored right now
  976. * ssl version is set - sslv3
  977. * ssl->session - The ssl session has been setup.
  978. * ssl->hit - session reuse flag
  979. * ssl->tmp.new_cipher - the new cipher to use. */
  980. ret = 1;
  981. if (0) {
  982. f_err:
  983. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  984. }
  985. err:
  986. sk_SSL_CIPHER_free(ciphers);
  987. SSL_SESSION_free(session);
  988. return ret;
  989. }
  990. int ssl3_send_server_hello(SSL *ssl) {
  991. if (ssl->state == SSL3_ST_SW_SRVR_HELLO_B) {
  992. return ssl_do_write(ssl);
  993. }
  994. assert(ssl->state == SSL3_ST_SW_SRVR_HELLO_A);
  995. /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
  996. * known attack while we fix ChannelID itself. */
  997. if (ssl->s3->tlsext_channel_id_valid &&
  998. (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
  999. ssl->s3->tlsext_channel_id_valid = 0;
  1000. }
  1001. /* If this is a resumption and the original handshake didn't support
  1002. * ChannelID then we didn't record the original handshake hashes in the
  1003. * session and so cannot resume with ChannelIDs. */
  1004. if (ssl->hit && ssl->session->original_handshake_hash_len == 0) {
  1005. ssl->s3->tlsext_channel_id_valid = 0;
  1006. }
  1007. if (!ssl_fill_hello_random(ssl->s3->server_random, SSL3_RANDOM_SIZE,
  1008. 1 /* server */)) {
  1009. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1010. return -1;
  1011. }
  1012. CBB cbb, session_id;
  1013. size_t length;
  1014. CBB_zero(&cbb);
  1015. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1016. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  1017. !CBB_add_u16(&cbb, ssl->version) ||
  1018. !CBB_add_bytes(&cbb, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
  1019. !CBB_add_u8_length_prefixed(&cbb, &session_id) ||
  1020. !CBB_add_bytes(&session_id, ssl->session->session_id,
  1021. ssl->session->session_id_length) ||
  1022. !CBB_add_u16(&cbb, ssl_cipher_get_value(ssl->s3->tmp.new_cipher)) ||
  1023. !CBB_add_u8(&cbb, 0 /* no compression */) ||
  1024. !ssl_add_serverhello_tlsext(ssl, &cbb) ||
  1025. !CBB_finish(&cbb, NULL, &length) ||
  1026. !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_HELLO, length)) {
  1027. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1028. CBB_cleanup(&cbb);
  1029. return -1;
  1030. }
  1031. ssl->state = SSL3_ST_SW_SRVR_HELLO_B;
  1032. return ssl_do_write(ssl);
  1033. }
  1034. int ssl3_send_certificate_status(SSL *ssl) {
  1035. if (ssl->state == SSL3_ST_SW_CERT_STATUS_A) {
  1036. CBB out, ocsp_response;
  1037. size_t length;
  1038. CBB_zero(&out);
  1039. if (!CBB_init_fixed(&out, ssl_handshake_start(ssl),
  1040. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  1041. !CBB_add_u8(&out, TLSEXT_STATUSTYPE_ocsp) ||
  1042. !CBB_add_u24_length_prefixed(&out, &ocsp_response) ||
  1043. !CBB_add_bytes(&ocsp_response, ssl->ctx->ocsp_response,
  1044. ssl->ctx->ocsp_response_length) ||
  1045. !CBB_finish(&out, NULL, &length) ||
  1046. !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_STATUS, length)) {
  1047. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1048. CBB_cleanup(&out);
  1049. return -1;
  1050. }
  1051. ssl->state = SSL3_ST_SW_CERT_STATUS_B;
  1052. }
  1053. /* SSL3_ST_SW_CERT_STATUS_B */
  1054. return ssl_do_write(ssl);
  1055. }
  1056. int ssl3_send_server_done(SSL *ssl) {
  1057. if (ssl->state == SSL3_ST_SW_SRVR_DONE_A) {
  1058. if (!ssl_set_handshake_header(ssl, SSL3_MT_SERVER_DONE, 0)) {
  1059. return -1;
  1060. }
  1061. ssl->state = SSL3_ST_SW_SRVR_DONE_B;
  1062. }
  1063. /* SSL3_ST_SW_SRVR_DONE_B */
  1064. return ssl_do_write(ssl);
  1065. }
  1066. int ssl3_send_server_key_exchange(SSL *ssl) {
  1067. if (ssl->state == SSL3_ST_SW_KEY_EXCH_C) {
  1068. return ssl_do_write(ssl);
  1069. }
  1070. CBB cbb, child;
  1071. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1072. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
  1073. goto err;
  1074. }
  1075. if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
  1076. /* This is the first iteration, so write parameters. */
  1077. uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1078. uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1079. /* PSK ciphers begin with an identity hint. */
  1080. if (alg_a & SSL_aPSK) {
  1081. size_t len =
  1082. (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
  1083. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1084. !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
  1085. len)) {
  1086. goto err;
  1087. }
  1088. }
  1089. if (alg_k & SSL_kDHE) {
  1090. /* Determine the group to use. */
  1091. DH *params = ssl->cert->dh_tmp;
  1092. if (params == NULL && ssl->cert->dh_tmp_cb != NULL) {
  1093. params = ssl->cert->dh_tmp_cb(ssl, 0, 1024);
  1094. }
  1095. if (params == NULL) {
  1096. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_DH_KEY);
  1097. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1098. goto err;
  1099. }
  1100. ssl->session->key_exchange_info = DH_num_bits(params);
  1101. /* Set up DH, generate a key, and emit the public half. */
  1102. DH *dh = DHparams_dup(params);
  1103. if (dh == NULL) {
  1104. goto err;
  1105. }
  1106. SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
  1107. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1108. !BN_bn2cbb_padded(&child, BN_num_bytes(params->p), params->p) ||
  1109. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1110. !BN_bn2cbb_padded(&child, BN_num_bytes(params->g), params->g) ||
  1111. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1112. !SSL_ECDH_CTX_generate_keypair(&ssl->s3->tmp.ecdh_ctx, &child)) {
  1113. goto err;
  1114. }
  1115. } else if (alg_k & SSL_kECDHE) {
  1116. /* Determine the curve to use. */
  1117. uint16_t curve_id;
  1118. if (!tls1_get_shared_curve(ssl, &curve_id)) {
  1119. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_ECDH_KEY);
  1120. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1121. goto err;
  1122. }
  1123. ssl->session->key_exchange_info = curve_id;
  1124. /* Set up ECDH, generate a key, and emit the public half. */
  1125. if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, curve_id) ||
  1126. !CBB_add_u8(&cbb, NAMED_CURVE_TYPE) ||
  1127. !CBB_add_u16(&cbb, curve_id) ||
  1128. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  1129. !SSL_ECDH_CTX_generate_keypair(&ssl->s3->tmp.ecdh_ctx, &child)) {
  1130. goto err;
  1131. }
  1132. } else {
  1133. assert(alg_k & SSL_kPSK);
  1134. }
  1135. /* Otherwise, restore |cbb| from the previous iteration.
  1136. * TODO(davidben): When |ssl->init_buf| is gone, come up with a simpler
  1137. * pattern. Probably keep the |CBB| around in the handshake state. */
  1138. } else if (!CBB_did_write(&cbb, ssl->init_num - SSL_HM_HEADER_LENGTH(ssl))) {
  1139. goto err;
  1140. }
  1141. /* Add a signature. */
  1142. if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
  1143. if (!ssl_has_private_key(ssl)) {
  1144. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1145. goto err;
  1146. }
  1147. const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
  1148. size_t sig_len;
  1149. enum ssl_private_key_result_t sign_result;
  1150. if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
  1151. /* This is the first iteration, so set up the signature. Sample the
  1152. * parameter length before adding a signature algorithm. */
  1153. if (!CBB_flush(&cbb)) {
  1154. goto err;
  1155. }
  1156. size_t params_len = CBB_len(&cbb);
  1157. /* Determine signature algorithm. */
  1158. const EVP_MD *md;
  1159. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1160. md = tls1_choose_signing_digest(ssl);
  1161. if (!tls12_add_sigandhash(ssl, &cbb, md)) {
  1162. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1163. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1164. goto err;
  1165. }
  1166. } else if (ssl_private_key_type(ssl) == EVP_PKEY_RSA) {
  1167. md = EVP_md5_sha1();
  1168. } else {
  1169. md = EVP_sha1();
  1170. }
  1171. /* Compute the digest and sign it. */
  1172. uint8_t digest[EVP_MAX_MD_SIZE];
  1173. unsigned digest_len = 0;
  1174. EVP_MD_CTX md_ctx;
  1175. EVP_MD_CTX_init(&md_ctx);
  1176. int digest_ret =
  1177. EVP_DigestInit_ex(&md_ctx, md, NULL) &&
  1178. EVP_DigestUpdate(&md_ctx, ssl->s3->client_random, SSL3_RANDOM_SIZE) &&
  1179. EVP_DigestUpdate(&md_ctx, ssl->s3->server_random, SSL3_RANDOM_SIZE) &&
  1180. EVP_DigestUpdate(&md_ctx, CBB_data(&cbb), params_len) &&
  1181. EVP_DigestFinal_ex(&md_ctx, digest, &digest_len);
  1182. EVP_MD_CTX_cleanup(&md_ctx);
  1183. uint8_t *ptr;
  1184. if (!digest_ret ||
  1185. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1186. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1187. goto err;
  1188. }
  1189. sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
  1190. digest, digest_len);
  1191. } else {
  1192. assert(ssl->state == SSL3_ST_SW_KEY_EXCH_B);
  1193. /* Retry the signature. */
  1194. uint8_t *ptr;
  1195. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1196. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1197. goto err;
  1198. }
  1199. sign_result =
  1200. ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
  1201. }
  1202. switch (sign_result) {
  1203. case ssl_private_key_success:
  1204. ssl->rwstate = SSL_NOTHING;
  1205. if (!CBB_did_write(&child, sig_len)) {
  1206. goto err;
  1207. }
  1208. break;
  1209. case ssl_private_key_failure:
  1210. ssl->rwstate = SSL_NOTHING;
  1211. goto err;
  1212. case ssl_private_key_retry:
  1213. /* Discard the unfinished signature and save the state of |cbb| for the
  1214. * next iteration. */
  1215. CBB_discard_child(&cbb);
  1216. ssl->init_num = SSL_HM_HEADER_LENGTH(ssl) + CBB_len(&cbb);
  1217. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1218. ssl->state = SSL3_ST_SW_KEY_EXCH_B;
  1219. goto err;
  1220. }
  1221. }
  1222. size_t length;
  1223. if (!CBB_finish(&cbb, NULL, &length) ||
  1224. !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_KEY_EXCHANGE, length)) {
  1225. goto err;
  1226. }
  1227. ssl->state = SSL3_ST_SW_KEY_EXCH_C;
  1228. return ssl_do_write(ssl);
  1229. err:
  1230. CBB_cleanup(&cbb);
  1231. return -1;
  1232. }
  1233. int ssl3_send_certificate_request(SSL *ssl) {
  1234. uint8_t *p, *d;
  1235. size_t i;
  1236. int j, nl, off, n;
  1237. STACK_OF(X509_NAME) *sk = NULL;
  1238. X509_NAME *name;
  1239. BUF_MEM *buf;
  1240. if (ssl->state == SSL3_ST_SW_CERT_REQ_A) {
  1241. buf = ssl->init_buf;
  1242. d = p = ssl_handshake_start(ssl);
  1243. /* get the list of acceptable cert types */
  1244. p++;
  1245. n = ssl3_get_req_cert_type(ssl, p);
  1246. d[0] = n;
  1247. p += n;
  1248. n++;
  1249. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1250. const uint8_t *psigs;
  1251. nl = tls12_get_psigalgs(ssl, &psigs);
  1252. s2n(nl, p);
  1253. memcpy(p, psigs, nl);
  1254. p += nl;
  1255. n += nl + 2;
  1256. }
  1257. off = n;
  1258. p += 2;
  1259. n += 2;
  1260. sk = SSL_get_client_CA_list(ssl);
  1261. nl = 0;
  1262. if (sk != NULL) {
  1263. for (i = 0; i < sk_X509_NAME_num(sk); i++) {
  1264. name = sk_X509_NAME_value(sk, i);
  1265. j = i2d_X509_NAME(name, NULL);
  1266. if (!BUF_MEM_grow_clean(buf, SSL_HM_HEADER_LENGTH(ssl) + n + j + 2)) {
  1267. OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
  1268. goto err;
  1269. }
  1270. p = ssl_handshake_start(ssl) + n;
  1271. s2n(j, p);
  1272. i2d_X509_NAME(name, &p);
  1273. n += 2 + j;
  1274. nl += 2 + j;
  1275. }
  1276. }
  1277. /* else no CA names */
  1278. p = ssl_handshake_start(ssl) + off;
  1279. s2n(nl, p);
  1280. if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_REQUEST, n)) {
  1281. goto err;
  1282. }
  1283. ssl->state = SSL3_ST_SW_CERT_REQ_B;
  1284. }
  1285. /* SSL3_ST_SW_CERT_REQ_B */
  1286. return ssl_do_write(ssl);
  1287. err:
  1288. return -1;
  1289. }
  1290. int ssl3_get_client_key_exchange(SSL *ssl) {
  1291. int al;
  1292. CBS client_key_exchange;
  1293. uint32_t alg_k;
  1294. uint32_t alg_a;
  1295. uint8_t *premaster_secret = NULL;
  1296. size_t premaster_secret_len = 0;
  1297. uint8_t *decrypt_buf = NULL;
  1298. unsigned psk_len = 0;
  1299. uint8_t psk[PSK_MAX_PSK_LEN];
  1300. if (ssl->state == SSL3_ST_SR_KEY_EXCH_A ||
  1301. ssl->state == SSL3_ST_SR_KEY_EXCH_B) {
  1302. int ok;
  1303. const long n = ssl->method->ssl_get_message(
  1304. ssl, SSL3_ST_SR_KEY_EXCH_A, SSL3_ST_SR_KEY_EXCH_B,
  1305. SSL3_MT_CLIENT_KEY_EXCHANGE, 2048 /* ??? */, ssl_hash_message, &ok);
  1306. if (!ok) {
  1307. return n;
  1308. }
  1309. }
  1310. CBS_init(&client_key_exchange, ssl->init_msg, ssl->init_num);
  1311. alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1312. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1313. /* If using a PSK key exchange, prepare the pre-shared key. */
  1314. if (alg_a & SSL_aPSK) {
  1315. CBS psk_identity;
  1316. /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
  1317. * then this is the only field in the message. */
  1318. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1319. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
  1320. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1321. al = SSL_AD_DECODE_ERROR;
  1322. goto f_err;
  1323. }
  1324. if (ssl->psk_server_callback == NULL) {
  1325. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_SERVER_CB);
  1326. al = SSL_AD_INTERNAL_ERROR;
  1327. goto f_err;
  1328. }
  1329. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1330. CBS_contains_zero_byte(&psk_identity)) {
  1331. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1332. al = SSL_AD_ILLEGAL_PARAMETER;
  1333. goto f_err;
  1334. }
  1335. if (!CBS_strdup(&psk_identity, &ssl->session->psk_identity)) {
  1336. al = SSL_AD_INTERNAL_ERROR;
  1337. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1338. goto f_err;
  1339. }
  1340. /* Look up the key for the identity. */
  1341. psk_len = ssl->psk_server_callback(ssl, ssl->session->psk_identity, psk,
  1342. sizeof(psk));
  1343. if (psk_len > PSK_MAX_PSK_LEN) {
  1344. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1345. al = SSL_AD_INTERNAL_ERROR;
  1346. goto f_err;
  1347. } else if (psk_len == 0) {
  1348. /* PSK related to the given identity not found */
  1349. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1350. al = SSL_AD_UNKNOWN_PSK_IDENTITY;
  1351. goto f_err;
  1352. }
  1353. }
  1354. /* Depending on the key exchange method, compute |premaster_secret| and
  1355. * |premaster_secret_len|. */
  1356. if (alg_k & SSL_kRSA) {
  1357. /* Allocate a buffer large enough for an RSA decryption. */
  1358. const size_t rsa_size = ssl_private_key_max_signature_len(ssl);
  1359. decrypt_buf = OPENSSL_malloc(rsa_size);
  1360. if (decrypt_buf == NULL) {
  1361. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1362. goto err;
  1363. }
  1364. enum ssl_private_key_result_t decrypt_result;
  1365. size_t decrypt_len;
  1366. if (ssl->state == SSL3_ST_SR_KEY_EXCH_B) {
  1367. if (!ssl_has_private_key(ssl) ||
  1368. ssl_private_key_type(ssl) != EVP_PKEY_RSA) {
  1369. al = SSL_AD_HANDSHAKE_FAILURE;
  1370. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_RSA_CERTIFICATE);
  1371. goto f_err;
  1372. }
  1373. CBS encrypted_premaster_secret;
  1374. if (ssl->version > SSL3_VERSION) {
  1375. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1376. &encrypted_premaster_secret) ||
  1377. CBS_len(&client_key_exchange) != 0) {
  1378. al = SSL_AD_DECODE_ERROR;
  1379. OPENSSL_PUT_ERROR(SSL,
  1380. SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
  1381. goto f_err;
  1382. }
  1383. } else {
  1384. encrypted_premaster_secret = client_key_exchange;
  1385. }
  1386. /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
  1387. * timing-sensitive code below. */
  1388. decrypt_result = ssl_private_key_decrypt(
  1389. ssl, decrypt_buf, &decrypt_len, rsa_size,
  1390. CBS_data(&encrypted_premaster_secret),
  1391. CBS_len(&encrypted_premaster_secret));
  1392. } else {
  1393. assert(ssl->state == SSL3_ST_SR_KEY_EXCH_C);
  1394. /* Complete async decrypt. */
  1395. decrypt_result = ssl_private_key_decrypt_complete(
  1396. ssl, decrypt_buf, &decrypt_len, rsa_size);
  1397. }
  1398. switch (decrypt_result) {
  1399. case ssl_private_key_success:
  1400. ssl->rwstate = SSL_NOTHING;
  1401. break;
  1402. case ssl_private_key_failure:
  1403. ssl->rwstate = SSL_NOTHING;
  1404. goto err;
  1405. case ssl_private_key_retry:
  1406. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1407. ssl->state = SSL3_ST_SR_KEY_EXCH_C;
  1408. goto err;
  1409. }
  1410. assert(decrypt_len == rsa_size);
  1411. /* Prepare a random premaster, to be used on invalid padding. See RFC 5246,
  1412. * section 7.4.7.1. */
  1413. premaster_secret_len = SSL_MAX_MASTER_KEY_LENGTH;
  1414. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1415. if (premaster_secret == NULL) {
  1416. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1417. goto err;
  1418. }
  1419. if (!RAND_bytes(premaster_secret, premaster_secret_len)) {
  1420. goto err;
  1421. }
  1422. /* The smallest padded premaster is 11 bytes of overhead. Small keys are
  1423. * publicly invalid. */
  1424. if (decrypt_len < 11 + premaster_secret_len) {
  1425. al = SSL_AD_DECRYPT_ERROR;
  1426. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1427. goto f_err;
  1428. }
  1429. /* Check the padding. See RFC 3447, section 7.2.2. */
  1430. size_t padding_len = decrypt_len - premaster_secret_len;
  1431. uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
  1432. constant_time_eq_int_8(decrypt_buf[1], 2);
  1433. size_t i;
  1434. for (i = 2; i < padding_len - 1; i++) {
  1435. good &= ~constant_time_is_zero_8(decrypt_buf[i]);
  1436. }
  1437. good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
  1438. /* The premaster secret must begin with |client_version|. This too must be
  1439. * checked in constant time (http://eprint.iacr.org/2003/052/). */
  1440. good &= constant_time_eq_8(decrypt_buf[padding_len],
  1441. (unsigned)(ssl->client_version >> 8));
  1442. good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
  1443. (unsigned)(ssl->client_version & 0xff));
  1444. /* Select, in constant time, either the decrypted premaster or the random
  1445. * premaster based on |good|. */
  1446. for (i = 0; i < premaster_secret_len; i++) {
  1447. premaster_secret[i] = constant_time_select_8(
  1448. good, decrypt_buf[padding_len + i], premaster_secret[i]);
  1449. }
  1450. OPENSSL_free(decrypt_buf);
  1451. decrypt_buf = NULL;
  1452. } else if (alg_k & (SSL_kECDHE|SSL_kDHE)) {
  1453. /* Parse the ClientKeyExchange. ECDHE uses a u8 length prefix while DHE uses
  1454. * u16. */
  1455. CBS peer_key;
  1456. int peer_key_ok;
  1457. if (alg_k & SSL_kECDHE) {
  1458. peer_key_ok = CBS_get_u8_length_prefixed(&client_key_exchange, &peer_key);
  1459. } else {
  1460. peer_key_ok =
  1461. CBS_get_u16_length_prefixed(&client_key_exchange, &peer_key);
  1462. }
  1463. if (!peer_key_ok || CBS_len(&client_key_exchange) != 0) {
  1464. al = SSL_AD_DECODE_ERROR;
  1465. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1466. goto f_err;
  1467. }
  1468. /* Compute the premaster. */
  1469. uint8_t alert;
  1470. if (!SSL_ECDH_CTX_compute_secret(&ssl->s3->tmp.ecdh_ctx, &premaster_secret,
  1471. &premaster_secret_len, &alert,
  1472. CBS_data(&peer_key), CBS_len(&peer_key))) {
  1473. al = alert;
  1474. goto f_err;
  1475. }
  1476. /* The key exchange state may now be discarded. */
  1477. SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
  1478. } else if (alg_k & SSL_kPSK) {
  1479. /* For plain PSK, other_secret is a block of 0s with the same length as the
  1480. * pre-shared key. */
  1481. premaster_secret_len = psk_len;
  1482. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1483. if (premaster_secret == NULL) {
  1484. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1485. goto err;
  1486. }
  1487. memset(premaster_secret, 0, premaster_secret_len);
  1488. } else {
  1489. al = SSL_AD_HANDSHAKE_FAILURE;
  1490. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_TYPE);
  1491. goto f_err;
  1492. }
  1493. /* For a PSK cipher suite, the actual pre-master secret is combined with the
  1494. * pre-shared key. */
  1495. if (alg_a & SSL_aPSK) {
  1496. CBB new_premaster, child;
  1497. uint8_t *new_data;
  1498. size_t new_len;
  1499. CBB_zero(&new_premaster);
  1500. if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len) ||
  1501. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1502. !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
  1503. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1504. !CBB_add_bytes(&child, psk, psk_len) ||
  1505. !CBB_finish(&new_premaster, &new_data, &new_len)) {
  1506. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1507. CBB_cleanup(&new_premaster);
  1508. goto err;
  1509. }
  1510. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1511. OPENSSL_free(premaster_secret);
  1512. premaster_secret = new_data;
  1513. premaster_secret_len = new_len;
  1514. }
  1515. /* Compute the master secret */
  1516. ssl->session->master_key_length = tls1_generate_master_secret(
  1517. ssl, ssl->session->master_key, premaster_secret, premaster_secret_len);
  1518. if (ssl->session->master_key_length == 0) {
  1519. goto err;
  1520. }
  1521. ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
  1522. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1523. OPENSSL_free(premaster_secret);
  1524. return 1;
  1525. f_err:
  1526. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1527. err:
  1528. if (premaster_secret != NULL) {
  1529. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1530. OPENSSL_free(premaster_secret);
  1531. }
  1532. OPENSSL_free(decrypt_buf);
  1533. return -1;
  1534. }
  1535. int ssl3_get_cert_verify(SSL *ssl) {
  1536. int al, ok, ret = 0;
  1537. long n;
  1538. CBS certificate_verify, signature;
  1539. X509 *peer = ssl->session->peer;
  1540. EVP_PKEY *pkey = NULL;
  1541. const EVP_MD *md = NULL;
  1542. uint8_t digest[EVP_MAX_MD_SIZE];
  1543. size_t digest_length;
  1544. EVP_PKEY_CTX *pctx = NULL;
  1545. /* Only RSA and ECDSA client certificates are supported, so a
  1546. * CertificateVerify is required if and only if there's a client certificate.
  1547. * */
  1548. if (peer == NULL) {
  1549. ssl3_free_handshake_buffer(ssl);
  1550. return 1;
  1551. }
  1552. n = ssl->method->ssl_get_message(
  1553. ssl, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B,
  1554. SSL3_MT_CERTIFICATE_VERIFY, SSL3_RT_MAX_PLAIN_LENGTH,
  1555. ssl_dont_hash_message, &ok);
  1556. if (!ok) {
  1557. return n;
  1558. }
  1559. /* Filter out unsupported certificate types. */
  1560. pkey = X509_get_pubkey(peer);
  1561. if (pkey == NULL) {
  1562. goto err;
  1563. }
  1564. if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
  1565. (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC)) {
  1566. al = SSL_AD_UNSUPPORTED_CERTIFICATE;
  1567. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  1568. goto f_err;
  1569. }
  1570. CBS_init(&certificate_verify, ssl->init_msg, n);
  1571. /* Determine the digest type if needbe. */
  1572. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1573. uint8_t hash, signature_type;
  1574. if (!CBS_get_u8(&certificate_verify, &hash) ||
  1575. !CBS_get_u8(&certificate_verify, &signature_type)) {
  1576. al = SSL_AD_DECODE_ERROR;
  1577. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1578. goto f_err;
  1579. }
  1580. if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature_type, pkey)) {
  1581. goto f_err;
  1582. }
  1583. }
  1584. /* Compute the digest. */
  1585. if (!ssl3_cert_verify_hash(ssl, digest, &digest_length, &md, pkey->type)) {
  1586. goto err;
  1587. }
  1588. /* The handshake buffer is no longer necessary, and we may hash the current
  1589. * message.*/
  1590. ssl3_free_handshake_buffer(ssl);
  1591. if (!ssl3_hash_current_message(ssl)) {
  1592. goto err;
  1593. }
  1594. /* Parse and verify the signature. */
  1595. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  1596. CBS_len(&certificate_verify) != 0) {
  1597. al = SSL_AD_DECODE_ERROR;
  1598. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1599. goto f_err;
  1600. }
  1601. pctx = EVP_PKEY_CTX_new(pkey, NULL);
  1602. if (pctx == NULL) {
  1603. goto err;
  1604. }
  1605. if (!EVP_PKEY_verify_init(pctx) ||
  1606. !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
  1607. !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature), digest,
  1608. digest_length)) {
  1609. al = SSL_AD_DECRYPT_ERROR;
  1610. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1611. goto f_err;
  1612. }
  1613. ret = 1;
  1614. if (0) {
  1615. f_err:
  1616. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1617. }
  1618. err:
  1619. EVP_PKEY_CTX_free(pctx);
  1620. EVP_PKEY_free(pkey);
  1621. return ret;
  1622. }
  1623. int ssl3_get_client_certificate(SSL *ssl) {
  1624. int i, ok, al, ret = -1;
  1625. X509 *x = NULL;
  1626. unsigned long n;
  1627. STACK_OF(X509) *sk = NULL;
  1628. SHA256_CTX sha256;
  1629. CBS certificate_msg, certificate_list;
  1630. int is_first_certificate = 1;
  1631. n = ssl->method->ssl_get_message(ssl, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
  1632. -1, (long)ssl->max_cert_list,
  1633. ssl_hash_message, &ok);
  1634. if (!ok) {
  1635. return n;
  1636. }
  1637. if (ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
  1638. if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1639. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1640. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1641. al = SSL_AD_HANDSHAKE_FAILURE;
  1642. goto f_err;
  1643. }
  1644. /* If tls asked for a client cert, the client must return a 0 list */
  1645. if (ssl->version > SSL3_VERSION && ssl->s3->tmp.cert_request) {
  1646. OPENSSL_PUT_ERROR(SSL,
  1647. SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
  1648. al = SSL_AD_UNEXPECTED_MESSAGE;
  1649. goto f_err;
  1650. }
  1651. ssl->s3->tmp.reuse_message = 1;
  1652. return 1;
  1653. }
  1654. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
  1655. al = SSL_AD_UNEXPECTED_MESSAGE;
  1656. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_MESSAGE_TYPE);
  1657. goto f_err;
  1658. }
  1659. CBS_init(&certificate_msg, ssl->init_msg, n);
  1660. sk = sk_X509_new_null();
  1661. if (sk == NULL) {
  1662. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1663. goto err;
  1664. }
  1665. if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
  1666. CBS_len(&certificate_msg) != 0) {
  1667. al = SSL_AD_DECODE_ERROR;
  1668. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1669. goto f_err;
  1670. }
  1671. while (CBS_len(&certificate_list) > 0) {
  1672. CBS certificate;
  1673. const uint8_t *data;
  1674. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  1675. al = SSL_AD_DECODE_ERROR;
  1676. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1677. goto f_err;
  1678. }
  1679. if (is_first_certificate && ssl->ctx->retain_only_sha256_of_client_certs) {
  1680. /* If this is the first certificate, and we don't want to keep peer
  1681. * certificates in memory, then we hash it right away. */
  1682. SHA256_Init(&sha256);
  1683. SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
  1684. SHA256_Final(ssl->session->peer_sha256, &sha256);
  1685. ssl->session->peer_sha256_valid = 1;
  1686. }
  1687. is_first_certificate = 0;
  1688. /* A u24 length cannot overflow a long. */
  1689. data = CBS_data(&certificate);
  1690. x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
  1691. if (x == NULL) {
  1692. al = SSL_AD_BAD_CERTIFICATE;
  1693. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  1694. goto f_err;
  1695. }
  1696. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  1697. al = SSL_AD_DECODE_ERROR;
  1698. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  1699. goto f_err;
  1700. }
  1701. if (!sk_X509_push(sk, x)) {
  1702. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1703. goto err;
  1704. }
  1705. x = NULL;
  1706. }
  1707. if (sk_X509_num(sk) <= 0) {
  1708. /* No client certificate so the handshake buffer may be discarded. */
  1709. ssl3_free_handshake_buffer(ssl);
  1710. /* TLS does not mind 0 certs returned */
  1711. if (ssl->version == SSL3_VERSION) {
  1712. al = SSL_AD_HANDSHAKE_FAILURE;
  1713. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
  1714. goto f_err;
  1715. } else if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1716. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1717. /* Fail for TLS only if we required a certificate */
  1718. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1719. al = SSL_AD_HANDSHAKE_FAILURE;
  1720. goto f_err;
  1721. }
  1722. } else {
  1723. i = ssl_verify_cert_chain(ssl, sk);
  1724. if (i <= 0) {
  1725. al = ssl_verify_alarm_type(ssl->verify_result);
  1726. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  1727. goto f_err;
  1728. }
  1729. }
  1730. X509_free(ssl->session->peer);
  1731. ssl->session->peer = sk_X509_shift(sk);
  1732. ssl->session->verify_result = ssl->verify_result;
  1733. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  1734. ssl->session->cert_chain = sk;
  1735. /* Inconsistency alert: cert_chain does *not* include the peer's own
  1736. * certificate, while we do include it in s3_clnt.c */
  1737. sk = NULL;
  1738. ret = 1;
  1739. if (0) {
  1740. f_err:
  1741. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1742. }
  1743. err:
  1744. X509_free(x);
  1745. sk_X509_pop_free(sk, X509_free);
  1746. return ret;
  1747. }
  1748. int ssl3_send_server_certificate(SSL *ssl) {
  1749. if (ssl->state == SSL3_ST_SW_CERT_A) {
  1750. if (!ssl3_output_cert_chain(ssl)) {
  1751. return 0;
  1752. }
  1753. ssl->state = SSL3_ST_SW_CERT_B;
  1754. }
  1755. /* SSL3_ST_SW_CERT_B */
  1756. return ssl_do_write(ssl);
  1757. }
  1758. /* send a new session ticket (not necessarily for a new session) */
  1759. int ssl3_send_new_session_ticket(SSL *ssl) {
  1760. int ret = -1;
  1761. uint8_t *session = NULL;
  1762. size_t session_len;
  1763. EVP_CIPHER_CTX ctx;
  1764. HMAC_CTX hctx;
  1765. EVP_CIPHER_CTX_init(&ctx);
  1766. HMAC_CTX_init(&hctx);
  1767. if (ssl->state == SSL3_ST_SW_SESSION_TICKET_A) {
  1768. uint8_t *p, *macstart;
  1769. int len;
  1770. unsigned int hlen;
  1771. SSL_CTX *tctx = ssl->initial_ctx;
  1772. uint8_t iv[EVP_MAX_IV_LENGTH];
  1773. uint8_t key_name[16];
  1774. /* The maximum overhead of encrypting the session is 16 (key name) + IV +
  1775. * one block of encryption overhead + HMAC. */
  1776. const size_t max_ticket_overhead =
  1777. 16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
  1778. /* Serialize the SSL_SESSION to be encoded into the ticket. */
  1779. if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &session,
  1780. &session_len)) {
  1781. goto err;
  1782. }
  1783. /* If the session is too long, emit a dummy value rather than abort the
  1784. * connection. */
  1785. if (session_len > 0xFFFF - max_ticket_overhead) {
  1786. static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
  1787. const size_t placeholder_len = strlen(kTicketPlaceholder);
  1788. OPENSSL_free(session);
  1789. session = NULL;
  1790. p = ssl_handshake_start(ssl);
  1791. /* Emit ticket_lifetime_hint. */
  1792. l2n(0, p);
  1793. /* Emit ticket. */
  1794. s2n(placeholder_len, p);
  1795. memcpy(p, kTicketPlaceholder, placeholder_len);
  1796. p += placeholder_len;
  1797. len = p - ssl_handshake_start(ssl);
  1798. if (!ssl_set_handshake_header(ssl, SSL3_MT_NEWSESSION_TICKET, len)) {
  1799. goto err;
  1800. }
  1801. ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
  1802. return ssl_do_write(ssl);
  1803. }
  1804. /* Grow buffer if need be: the length calculation is as follows:
  1805. * handshake_header_length + 4 (ticket lifetime hint) + 2 (ticket length) +
  1806. * max_ticket_overhead + * session_length */
  1807. if (!BUF_MEM_grow(ssl->init_buf, SSL_HM_HEADER_LENGTH(ssl) + 6 +
  1808. max_ticket_overhead + session_len)) {
  1809. goto err;
  1810. }
  1811. p = ssl_handshake_start(ssl);
  1812. /* Initialize HMAC and cipher contexts. If callback present it does all the
  1813. * work otherwise use generated values from parent ctx. */
  1814. if (tctx->tlsext_ticket_key_cb) {
  1815. if (tctx->tlsext_ticket_key_cb(ssl, key_name, iv, &ctx, &hctx,
  1816. 1 /* encrypt */) < 0) {
  1817. goto err;
  1818. }
  1819. } else {
  1820. if (!RAND_bytes(iv, 16) ||
  1821. !EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
  1822. tctx->tlsext_tick_aes_key, iv) ||
  1823. !HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(),
  1824. NULL)) {
  1825. goto err;
  1826. }
  1827. memcpy(key_name, tctx->tlsext_tick_key_name, 16);
  1828. }
  1829. /* Ticket lifetime hint (advisory only): We leave this unspecified for
  1830. * resumed session (for simplicity), and guess that tickets for new
  1831. * sessions will live as long as their sessions. */
  1832. l2n(ssl->hit ? 0 : ssl->session->timeout, p);
  1833. /* Skip ticket length for now */
  1834. p += 2;
  1835. /* Output key name */
  1836. macstart = p;
  1837. memcpy(p, key_name, 16);
  1838. p += 16;
  1839. /* output IV */
  1840. memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
  1841. p += EVP_CIPHER_CTX_iv_length(&ctx);
  1842. /* Encrypt session data */
  1843. if (!EVP_EncryptUpdate(&ctx, p, &len, session, session_len)) {
  1844. goto err;
  1845. }
  1846. p += len;
  1847. if (!EVP_EncryptFinal_ex(&ctx, p, &len)) {
  1848. goto err;
  1849. }
  1850. p += len;
  1851. if (!HMAC_Update(&hctx, macstart, p - macstart) ||
  1852. !HMAC_Final(&hctx, p, &hlen)) {
  1853. goto err;
  1854. }
  1855. p += hlen;
  1856. /* Now write out lengths: p points to end of data written */
  1857. /* Total length */
  1858. len = p - ssl_handshake_start(ssl);
  1859. /* Skip ticket lifetime hint */
  1860. p = ssl_handshake_start(ssl) + 4;
  1861. s2n(len - 6, p);
  1862. if (!ssl_set_handshake_header(ssl, SSL3_MT_NEWSESSION_TICKET, len)) {
  1863. goto err;
  1864. }
  1865. ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
  1866. }
  1867. /* SSL3_ST_SW_SESSION_TICKET_B */
  1868. ret = ssl_do_write(ssl);
  1869. err:
  1870. OPENSSL_free(session);
  1871. EVP_CIPHER_CTX_cleanup(&ctx);
  1872. HMAC_CTX_cleanup(&hctx);
  1873. return ret;
  1874. }
  1875. /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
  1876. * sets the next_proto member in s if found */
  1877. int ssl3_get_next_proto(SSL *ssl) {
  1878. int ok;
  1879. long n;
  1880. CBS next_protocol, selected_protocol, padding;
  1881. /* Clients cannot send a NextProtocol message if we didn't see the extension
  1882. * in their ClientHello */
  1883. if (!ssl->s3->next_proto_neg_seen) {
  1884. OPENSSL_PUT_ERROR(SSL, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
  1885. return -1;
  1886. }
  1887. n = ssl->method->ssl_get_message(ssl, SSL3_ST_SR_NEXT_PROTO_A,
  1888. SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO,
  1889. 514, /* See the payload format below */
  1890. ssl_hash_message, &ok);
  1891. if (!ok) {
  1892. return n;
  1893. }
  1894. CBS_init(&next_protocol, ssl->init_msg, n);
  1895. /* The payload looks like:
  1896. * uint8 proto_len;
  1897. * uint8 proto[proto_len];
  1898. * uint8 padding_len;
  1899. * uint8 padding[padding_len]; */
  1900. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  1901. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  1902. CBS_len(&next_protocol) != 0 ||
  1903. !CBS_stow(&selected_protocol, &ssl->s3->next_proto_negotiated,
  1904. &ssl->s3->next_proto_negotiated_len)) {
  1905. return 0;
  1906. }
  1907. return 1;
  1908. }
  1909. /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
  1910. int ssl3_get_channel_id(SSL *ssl) {
  1911. int ret = -1, ok;
  1912. long n;
  1913. uint8_t channel_id_hash[EVP_MAX_MD_SIZE];
  1914. size_t channel_id_hash_len;
  1915. const uint8_t *p;
  1916. uint16_t extension_type;
  1917. EC_GROUP *p256 = NULL;
  1918. EC_KEY *key = NULL;
  1919. EC_POINT *point = NULL;
  1920. ECDSA_SIG sig;
  1921. BIGNUM x, y;
  1922. CBS encrypted_extensions, extension;
  1923. n = ssl->method->ssl_get_message(
  1924. ssl, SSL3_ST_SR_CHANNEL_ID_A, SSL3_ST_SR_CHANNEL_ID_B,
  1925. SSL3_MT_ENCRYPTED_EXTENSIONS, 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
  1926. ssl_dont_hash_message, &ok);
  1927. if (!ok) {
  1928. return n;
  1929. }
  1930. /* Before incorporating the EncryptedExtensions message to the handshake
  1931. * hash, compute the hash that should have been signed. */
  1932. if (!tls1_channel_id_hash(ssl, channel_id_hash, &channel_id_hash_len)) {
  1933. return -1;
  1934. }
  1935. assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
  1936. if (!ssl3_hash_current_message(ssl)) {
  1937. return -1;
  1938. }
  1939. CBS_init(&encrypted_extensions, ssl->init_msg, n);
  1940. /* EncryptedExtensions could include multiple extensions, but the only
  1941. * extension that could be negotiated is ChannelID, so there can only be one
  1942. * entry.
  1943. *
  1944. * The payload looks like:
  1945. * uint16 extension_type
  1946. * uint16 extension_len;
  1947. * uint8 x[32];
  1948. * uint8 y[32];
  1949. * uint8 r[32];
  1950. * uint8 s[32]; */
  1951. if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
  1952. !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
  1953. CBS_len(&encrypted_extensions) != 0 ||
  1954. extension_type != TLSEXT_TYPE_channel_id ||
  1955. CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
  1956. OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_MESSAGE);
  1957. return -1;
  1958. }
  1959. p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
  1960. if (!p256) {
  1961. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
  1962. return -1;
  1963. }
  1964. BN_init(&x);
  1965. BN_init(&y);
  1966. sig.r = BN_new();
  1967. sig.s = BN_new();
  1968. if (sig.r == NULL || sig.s == NULL) {
  1969. goto err;
  1970. }
  1971. p = CBS_data(&extension);
  1972. if (BN_bin2bn(p + 0, 32, &x) == NULL ||
  1973. BN_bin2bn(p + 32, 32, &y) == NULL ||
  1974. BN_bin2bn(p + 64, 32, sig.r) == NULL ||
  1975. BN_bin2bn(p + 96, 32, sig.s) == NULL) {
  1976. goto err;
  1977. }
  1978. point = EC_POINT_new(p256);
  1979. if (!point ||
  1980. !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL)) {
  1981. goto err;
  1982. }
  1983. key = EC_KEY_new();
  1984. if (!key || !EC_KEY_set_group(key, p256) ||
  1985. !EC_KEY_set_public_key(key, point)) {
  1986. goto err;
  1987. }
  1988. /* We stored the handshake hash in |tlsext_channel_id| the first time that we
  1989. * were called. */
  1990. if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key)) {
  1991. OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
  1992. ssl->s3->tlsext_channel_id_valid = 0;
  1993. goto err;
  1994. }
  1995. memcpy(ssl->s3->tlsext_channel_id, p, 64);
  1996. ret = 1;
  1997. err:
  1998. BN_free(&x);
  1999. BN_free(&y);
  2000. BN_free(sig.r);
  2001. BN_free(sig.s);
  2002. EC_KEY_free(key);
  2003. EC_POINT_free(point);
  2004. EC_GROUP_free(p256);
  2005. return ret;
  2006. }