handshake_server.cc 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  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 <string.h>
  151. #include <openssl/bn.h>
  152. #include <openssl/buf.h>
  153. #include <openssl/bytestring.h>
  154. #include <openssl/cipher.h>
  155. #include <openssl/ec.h>
  156. #include <openssl/ecdsa.h>
  157. #include <openssl/err.h>
  158. #include <openssl/evp.h>
  159. #include <openssl/hmac.h>
  160. #include <openssl/md5.h>
  161. #include <openssl/mem.h>
  162. #include <openssl/nid.h>
  163. #include <openssl/rand.h>
  164. #include <openssl/x509.h>
  165. #include "internal.h"
  166. #include "../crypto/internal.h"
  167. BSSL_NAMESPACE_BEGIN
  168. bool ssl_client_cipher_list_contains_cipher(
  169. const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
  170. CBS cipher_suites;
  171. CBS_init(&cipher_suites, client_hello->cipher_suites,
  172. client_hello->cipher_suites_len);
  173. while (CBS_len(&cipher_suites) > 0) {
  174. uint16_t got_id;
  175. if (!CBS_get_u16(&cipher_suites, &got_id)) {
  176. return false;
  177. }
  178. if (got_id == id) {
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
  185. const SSL_CLIENT_HELLO *client_hello) {
  186. SSL *const ssl = hs->ssl;
  187. assert(!ssl->s3->have_version);
  188. CBS supported_versions, versions;
  189. if (ssl_client_hello_get_extension(client_hello, &supported_versions,
  190. TLSEXT_TYPE_supported_versions)) {
  191. if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
  192. CBS_len(&supported_versions) != 0 ||
  193. CBS_len(&versions) == 0) {
  194. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  195. *out_alert = SSL_AD_DECODE_ERROR;
  196. return false;
  197. }
  198. } else {
  199. // Convert the ClientHello version to an equivalent supported_versions
  200. // extension.
  201. static const uint8_t kTLSVersions[] = {
  202. 0x03, 0x03, // TLS 1.2
  203. 0x03, 0x02, // TLS 1.1
  204. 0x03, 0x01, // TLS 1
  205. };
  206. static const uint8_t kDTLSVersions[] = {
  207. 0xfe, 0xfd, // DTLS 1.2
  208. 0xfe, 0xff, // DTLS 1.0
  209. };
  210. size_t versions_len = 0;
  211. if (SSL_is_dtls(ssl)) {
  212. if (client_hello->version <= DTLS1_2_VERSION) {
  213. versions_len = 4;
  214. } else if (client_hello->version <= DTLS1_VERSION) {
  215. versions_len = 2;
  216. }
  217. CBS_init(&versions, kDTLSVersions + sizeof(kDTLSVersions) - versions_len,
  218. versions_len);
  219. } else {
  220. if (client_hello->version >= TLS1_2_VERSION) {
  221. versions_len = 6;
  222. } else if (client_hello->version >= TLS1_1_VERSION) {
  223. versions_len = 4;
  224. } else if (client_hello->version >= TLS1_VERSION) {
  225. versions_len = 2;
  226. }
  227. CBS_init(&versions, kTLSVersions + sizeof(kTLSVersions) - versions_len,
  228. versions_len);
  229. }
  230. }
  231. if (!ssl_negotiate_version(hs, out_alert, &ssl->version, &versions)) {
  232. return false;
  233. }
  234. // At this point, the connection's version is known and |ssl->version| is
  235. // fixed. Begin enforcing the record-layer version.
  236. ssl->s3->have_version = true;
  237. ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
  238. // Handle FALLBACK_SCSV.
  239. if (ssl_client_cipher_list_contains_cipher(client_hello,
  240. SSL3_CK_FALLBACK_SCSV & 0xffff) &&
  241. ssl_protocol_version(ssl) < hs->max_version) {
  242. OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
  243. *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
  244. return false;
  245. }
  246. return true;
  247. }
  248. static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
  249. const SSL_CLIENT_HELLO *client_hello) {
  250. CBS cipher_suites;
  251. CBS_init(&cipher_suites, client_hello->cipher_suites,
  252. client_hello->cipher_suites_len);
  253. UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
  254. if (!sk) {
  255. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  256. return nullptr;
  257. }
  258. while (CBS_len(&cipher_suites) > 0) {
  259. uint16_t cipher_suite;
  260. if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
  261. OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
  262. return nullptr;
  263. }
  264. const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
  265. if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
  266. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  267. return nullptr;
  268. }
  269. }
  270. return sk;
  271. }
  272. // ssl_get_compatible_server_ciphers determines the key exchange and
  273. // authentication cipher suite masks compatible with the server configuration
  274. // and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
  275. // exchange mask and |*out_mask_a| to the authentication mask.
  276. static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
  277. uint32_t *out_mask_k,
  278. uint32_t *out_mask_a) {
  279. uint32_t mask_k = 0;
  280. uint32_t mask_a = 0;
  281. if (ssl_has_certificate(hs)) {
  282. mask_a |= ssl_cipher_auth_mask_for_key(hs->local_pubkey.get());
  283. if (EVP_PKEY_id(hs->local_pubkey.get()) == EVP_PKEY_RSA) {
  284. mask_k |= SSL_kRSA;
  285. }
  286. }
  287. // Check for a shared group to consider ECDHE ciphers.
  288. uint16_t unused;
  289. if (tls1_get_shared_group(hs, &unused)) {
  290. mask_k |= SSL_kECDHE;
  291. }
  292. // PSK requires a server callback.
  293. if (hs->config->psk_server_callback != NULL) {
  294. mask_k |= SSL_kPSK;
  295. mask_a |= SSL_aPSK;
  296. }
  297. *out_mask_k = mask_k;
  298. *out_mask_a = mask_a;
  299. }
  300. static const SSL_CIPHER *ssl3_choose_cipher(
  301. SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
  302. const SSLCipherPreferenceList *server_pref) {
  303. SSL *const ssl = hs->ssl;
  304. const STACK_OF(SSL_CIPHER) *prio, *allow;
  305. // in_group_flags will either be NULL, or will point to an array of bytes
  306. // which indicate equal-preference groups in the |prio| stack. See the
  307. // comment about |in_group_flags| in the |SSLCipherPreferenceList|
  308. // struct.
  309. const bool *in_group_flags;
  310. // group_min contains the minimal index so far found in a group, or -1 if no
  311. // such value exists yet.
  312. int group_min = -1;
  313. UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
  314. ssl_parse_client_cipher_list(client_hello);
  315. if (!client_pref) {
  316. return nullptr;
  317. }
  318. if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
  319. prio = server_pref->ciphers.get();
  320. in_group_flags = server_pref->in_group_flags;
  321. allow = client_pref.get();
  322. } else {
  323. prio = client_pref.get();
  324. in_group_flags = NULL;
  325. allow = server_pref->ciphers.get();
  326. }
  327. uint32_t mask_k, mask_a;
  328. ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
  329. for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
  330. const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
  331. size_t cipher_index;
  332. if (// Check if the cipher is supported for the current version.
  333. SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) &&
  334. ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) &&
  335. // Check the cipher is supported for the server configuration.
  336. (c->algorithm_mkey & mask_k) &&
  337. (c->algorithm_auth & mask_a) &&
  338. // Check the cipher is in the |allow| list.
  339. sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
  340. if (in_group_flags != NULL && in_group_flags[i]) {
  341. // This element of |prio| is in a group. Update the minimum index found
  342. // so far and continue looking.
  343. if (group_min == -1 || (size_t)group_min > cipher_index) {
  344. group_min = cipher_index;
  345. }
  346. } else {
  347. if (group_min != -1 && (size_t)group_min < cipher_index) {
  348. cipher_index = group_min;
  349. }
  350. return sk_SSL_CIPHER_value(allow, cipher_index);
  351. }
  352. }
  353. if (in_group_flags != NULL && !in_group_flags[i] && group_min != -1) {
  354. // We are about to leave a group, but we found a match in it, so that's
  355. // our answer.
  356. return sk_SSL_CIPHER_value(allow, group_min);
  357. }
  358. }
  359. return nullptr;
  360. }
  361. static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
  362. ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
  363. hs->state = state12_read_client_hello;
  364. return ssl_hs_ok;
  365. }
  366. // is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent
  367. // from a JDK 11 client with both TLS 1.3 and a prior version enabled.
  368. static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) {
  369. // JDK 11 ClientHellos contain a number of unusual properties which should
  370. // limit false positives.
  371. // JDK 11 does not support ChaCha20-Poly1305. This is unusual: many modern
  372. // clients implement ChaCha20-Poly1305.
  373. if (ssl_client_cipher_list_contains_cipher(
  374. client_hello, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
  375. return false;
  376. }
  377. // JDK 11 always sends extensions in a particular order.
  378. constexpr uint16_t kMaxFragmentLength = 0x0001;
  379. constexpr uint16_t kStatusRequestV2 = 0x0011;
  380. static CONSTEXPR_ARRAY struct {
  381. uint16_t id;
  382. bool required;
  383. } kJavaExtensions[] = {
  384. {TLSEXT_TYPE_server_name, false},
  385. {kMaxFragmentLength, false},
  386. {TLSEXT_TYPE_status_request, false},
  387. {TLSEXT_TYPE_supported_groups, true},
  388. {TLSEXT_TYPE_ec_point_formats, false},
  389. {TLSEXT_TYPE_signature_algorithms, true},
  390. // Java always sends signature_algorithms_cert.
  391. {TLSEXT_TYPE_signature_algorithms_cert, true},
  392. {TLSEXT_TYPE_application_layer_protocol_negotiation, false},
  393. {kStatusRequestV2, false},
  394. {TLSEXT_TYPE_extended_master_secret, false},
  395. {TLSEXT_TYPE_supported_versions, true},
  396. {TLSEXT_TYPE_cookie, false},
  397. {TLSEXT_TYPE_psk_key_exchange_modes, true},
  398. {TLSEXT_TYPE_key_share, true},
  399. {TLSEXT_TYPE_renegotiate, false},
  400. {TLSEXT_TYPE_pre_shared_key, false},
  401. };
  402. Span<const uint8_t> sigalgs, sigalgs_cert;
  403. bool has_status_request = false, has_status_request_v2 = false;
  404. CBS extensions, supported_groups;
  405. CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
  406. for (const auto &java_extension : kJavaExtensions) {
  407. CBS copy = extensions;
  408. uint16_t id;
  409. if (CBS_get_u16(&copy, &id) && id == java_extension.id) {
  410. // The next extension is the one we expected.
  411. extensions = copy;
  412. CBS body;
  413. if (!CBS_get_u16_length_prefixed(&extensions, &body)) {
  414. return false;
  415. }
  416. switch (id) {
  417. case TLSEXT_TYPE_status_request:
  418. has_status_request = true;
  419. break;
  420. case kStatusRequestV2:
  421. has_status_request_v2 = true;
  422. break;
  423. case TLSEXT_TYPE_signature_algorithms:
  424. sigalgs = body;
  425. break;
  426. case TLSEXT_TYPE_signature_algorithms_cert:
  427. sigalgs_cert = body;
  428. break;
  429. case TLSEXT_TYPE_supported_groups:
  430. supported_groups = body;
  431. break;
  432. }
  433. } else if (java_extension.required) {
  434. return false;
  435. }
  436. }
  437. if (CBS_len(&extensions) != 0) {
  438. return false;
  439. }
  440. // JDK 11 never advertises X25519. It is not offered by default, and
  441. // -Djdk.tls.namedGroups=x25519 does not work. This is unusual: many modern
  442. // clients implement X25519.
  443. while (CBS_len(&supported_groups) > 0) {
  444. uint16_t group;
  445. if (!CBS_get_u16(&supported_groups, &group) ||
  446. group == SSL_CURVE_X25519) {
  447. return false;
  448. }
  449. }
  450. if (// JDK 11 always sends the same contents in signature_algorithms and
  451. // signature_algorithms_cert. This is unusual: signature_algorithms_cert,
  452. // if omitted, is treated as if it were signature_algorithms.
  453. sigalgs != sigalgs_cert ||
  454. // When TLS 1.2 or below is enabled, JDK 11 sends status_request_v2 iff it
  455. // sends status_request. This is unusual: status_request_v2 is not widely
  456. // implemented.
  457. has_status_request != has_status_request_v2) {
  458. return false;
  459. }
  460. return true;
  461. }
  462. static bool extract_sni(SSL_HANDSHAKE *hs, uint8_t *out_alert,
  463. const SSL_CLIENT_HELLO *client_hello) {
  464. SSL *const ssl = hs->ssl;
  465. CBS sni;
  466. if (!ssl_client_hello_get_extension(client_hello, &sni,
  467. TLSEXT_TYPE_server_name)) {
  468. // No SNI extension to parse.
  469. return true;
  470. }
  471. CBS server_name_list, host_name;
  472. uint8_t name_type;
  473. if (!CBS_get_u16_length_prefixed(&sni, &server_name_list) ||
  474. !CBS_get_u8(&server_name_list, &name_type) ||
  475. // Although the server_name extension was intended to be extensible to
  476. // new name types and multiple names, OpenSSL 1.0.x had a bug which meant
  477. // different name types will cause an error. Further, RFC 4366 originally
  478. // defined syntax inextensibly. RFC 6066 corrected this mistake, but
  479. // adding new name types is no longer feasible.
  480. //
  481. // Act as if the extensibility does not exist to simplify parsing.
  482. !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
  483. CBS_len(&server_name_list) != 0 ||
  484. CBS_len(&sni) != 0) {
  485. *out_alert = SSL_AD_DECODE_ERROR;
  486. return false;
  487. }
  488. if (name_type != TLSEXT_NAMETYPE_host_name ||
  489. CBS_len(&host_name) == 0 ||
  490. CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
  491. CBS_contains_zero_byte(&host_name)) {
  492. *out_alert = SSL_AD_UNRECOGNIZED_NAME;
  493. return false;
  494. }
  495. // Copy the hostname as a string.
  496. char *raw = nullptr;
  497. if (!CBS_strdup(&host_name, &raw)) {
  498. *out_alert = SSL_AD_INTERNAL_ERROR;
  499. return false;
  500. }
  501. ssl->s3->hostname.reset(raw);
  502. hs->should_ack_sni = true;
  503. return true;
  504. }
  505. static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
  506. SSL *const ssl = hs->ssl;
  507. SSLMessage msg;
  508. if (!ssl->method->get_message(ssl, &msg)) {
  509. return ssl_hs_read_message;
  510. }
  511. if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
  512. return ssl_hs_error;
  513. }
  514. SSL_CLIENT_HELLO client_hello;
  515. if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
  516. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  517. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  518. return ssl_hs_error;
  519. }
  520. if (hs->config->handoff) {
  521. return ssl_hs_handoff;
  522. }
  523. uint8_t alert = SSL_AD_DECODE_ERROR;
  524. if (!extract_sni(hs, &alert, &client_hello)) {
  525. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  526. return ssl_hs_error;
  527. }
  528. // Run the early callback.
  529. if (ssl->ctx->select_certificate_cb != NULL) {
  530. switch (ssl->ctx->select_certificate_cb(&client_hello)) {
  531. case ssl_select_cert_retry:
  532. return ssl_hs_certificate_selection_pending;
  533. case ssl_select_cert_error:
  534. // Connection rejected.
  535. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  536. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  537. return ssl_hs_error;
  538. default:
  539. /* fallthrough */;
  540. }
  541. }
  542. // Freeze the version range after the early callback.
  543. if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
  544. return ssl_hs_error;
  545. }
  546. if (hs->config->jdk11_workaround &&
  547. is_probably_jdk11_with_tls13(&client_hello)) {
  548. hs->apply_jdk11_workaround = true;
  549. }
  550. if (!negotiate_version(hs, &alert, &client_hello)) {
  551. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  552. return ssl_hs_error;
  553. }
  554. hs->client_version = client_hello.version;
  555. if (client_hello.random_len != SSL3_RANDOM_SIZE) {
  556. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  557. return ssl_hs_error;
  558. }
  559. OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
  560. client_hello.random_len);
  561. // Only null compression is supported. TLS 1.3 further requires the peer
  562. // advertise no other compression.
  563. if (OPENSSL_memchr(client_hello.compression_methods, 0,
  564. client_hello.compression_methods_len) == NULL ||
  565. (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
  566. client_hello.compression_methods_len != 1)) {
  567. OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
  568. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  569. return ssl_hs_error;
  570. }
  571. // TLS extensions.
  572. if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
  573. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  574. return ssl_hs_error;
  575. }
  576. hs->state = state12_select_certificate;
  577. return ssl_hs_ok;
  578. }
  579. static enum ssl_hs_wait_t do_select_certificate(SSL_HANDSHAKE *hs) {
  580. SSL *const ssl = hs->ssl;
  581. SSLMessage msg;
  582. if (!ssl->method->get_message(ssl, &msg)) {
  583. return ssl_hs_read_message;
  584. }
  585. // Call |cert_cb| to update server certificates if required.
  586. if (hs->config->cert->cert_cb != NULL) {
  587. int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
  588. if (rv == 0) {
  589. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
  590. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  591. return ssl_hs_error;
  592. }
  593. if (rv < 0) {
  594. return ssl_hs_x509_lookup;
  595. }
  596. }
  597. if (!ssl_on_certificate_selected(hs)) {
  598. return ssl_hs_error;
  599. }
  600. if (hs->ocsp_stapling_requested &&
  601. ssl->ctx->legacy_ocsp_callback != nullptr) {
  602. switch (ssl->ctx->legacy_ocsp_callback(
  603. ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
  604. case SSL_TLSEXT_ERR_OK:
  605. break;
  606. case SSL_TLSEXT_ERR_NOACK:
  607. hs->ocsp_stapling_requested = false;
  608. break;
  609. default:
  610. OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
  611. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  612. return ssl_hs_error;
  613. }
  614. }
  615. if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
  616. // Jump to the TLS 1.3 state machine.
  617. hs->state = state12_tls13;
  618. return ssl_hs_ok;
  619. }
  620. ssl->s3->early_data_reason = ssl_early_data_protocol_version;
  621. SSL_CLIENT_HELLO client_hello;
  622. if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
  623. return ssl_hs_error;
  624. }
  625. // Negotiate the cipher suite. This must be done after |cert_cb| so the
  626. // certificate is finalized.
  627. SSLCipherPreferenceList *prefs = hs->config->cipher_list
  628. ? hs->config->cipher_list.get()
  629. : ssl->ctx->cipher_list.get();
  630. hs->new_cipher = ssl3_choose_cipher(hs, &client_hello, prefs);
  631. if (hs->new_cipher == NULL) {
  632. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
  633. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  634. return ssl_hs_error;
  635. }
  636. hs->state = state12_select_parameters;
  637. return ssl_hs_ok;
  638. }
  639. static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
  640. enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
  641. if (wait == ssl_hs_ok) {
  642. hs->state = state12_finish_server_handshake;
  643. return ssl_hs_ok;
  644. }
  645. return wait;
  646. }
  647. static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
  648. SSL *const ssl = hs->ssl;
  649. SSLMessage msg;
  650. if (!ssl->method->get_message(ssl, &msg)) {
  651. return ssl_hs_read_message;
  652. }
  653. SSL_CLIENT_HELLO client_hello;
  654. if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
  655. return ssl_hs_error;
  656. }
  657. // Determine whether we are doing session resumption.
  658. UniquePtr<SSL_SESSION> session;
  659. bool tickets_supported = false, renew_ticket = false;
  660. enum ssl_hs_wait_t wait = ssl_get_prev_session(
  661. hs, &session, &tickets_supported, &renew_ticket, &client_hello);
  662. if (wait != ssl_hs_ok) {
  663. return wait;
  664. }
  665. if (session) {
  666. if (session->extended_master_secret && !hs->extended_master_secret) {
  667. // A ClientHello without EMS that attempts to resume a session with EMS
  668. // is fatal to the connection.
  669. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  670. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  671. return ssl_hs_error;
  672. }
  673. if (!ssl_session_is_resumable(hs, session.get()) ||
  674. // If the client offers the EMS extension, but the previous session
  675. // didn't use it, then negotiate a new session.
  676. hs->extended_master_secret != session->extended_master_secret) {
  677. session.reset();
  678. }
  679. }
  680. if (session) {
  681. // Use the old session.
  682. hs->ticket_expected = renew_ticket;
  683. ssl->session = std::move(session);
  684. ssl->s3->session_reused = true;
  685. } else {
  686. hs->ticket_expected = tickets_supported;
  687. ssl_set_session(ssl, NULL);
  688. if (!ssl_get_new_session(hs, 1 /* server */)) {
  689. return ssl_hs_error;
  690. }
  691. // Clear the session ID if we want the session to be single-use.
  692. if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
  693. hs->new_session->session_id_length = 0;
  694. }
  695. }
  696. if (ssl->ctx->dos_protection_cb != NULL &&
  697. ssl->ctx->dos_protection_cb(&client_hello) == 0) {
  698. // Connection rejected for DOS reasons.
  699. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  700. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  701. return ssl_hs_error;
  702. }
  703. if (ssl->session == NULL) {
  704. hs->new_session->cipher = hs->new_cipher;
  705. // Determine whether to request a client certificate.
  706. hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
  707. // Only request a certificate if Channel ID isn't negotiated.
  708. if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  709. ssl->s3->channel_id_valid) {
  710. hs->cert_request = false;
  711. }
  712. // CertificateRequest may only be sent in certificate-based ciphers.
  713. if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
  714. hs->cert_request = false;
  715. }
  716. if (!hs->cert_request) {
  717. // OpenSSL returns X509_V_OK when no certificates are requested. This is
  718. // classed by them as a bug, but it's assumed by at least NGINX.
  719. hs->new_session->verify_result = X509_V_OK;
  720. }
  721. }
  722. // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
  723. // deferred. Complete it now.
  724. uint8_t alert = SSL_AD_DECODE_ERROR;
  725. if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
  726. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  727. return ssl_hs_error;
  728. }
  729. // Now that all parameters are known, initialize the handshake hash and hash
  730. // the ClientHello.
  731. if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
  732. !ssl_hash_message(hs, msg)) {
  733. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  734. return ssl_hs_error;
  735. }
  736. // Handback includes the whole handshake transcript, so we cannot free the
  737. // transcript buffer in the handback case.
  738. if (!hs->cert_request && !hs->handback) {
  739. hs->transcript.FreeBuffer();
  740. }
  741. ssl->method->next_message(ssl);
  742. hs->state = state12_send_server_hello;
  743. return ssl_hs_ok;
  744. }
  745. static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
  746. out = out.subspan(out.size() - in.size());
  747. assert(out.size() == in.size());
  748. OPENSSL_memcpy(out.data(), in.data(), in.size());
  749. }
  750. static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
  751. SSL *const ssl = hs->ssl;
  752. // We only accept ChannelIDs on connections with ECDHE in order to avoid a
  753. // known attack while we fix ChannelID itself.
  754. if (ssl->s3->channel_id_valid &&
  755. (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
  756. ssl->s3->channel_id_valid = false;
  757. }
  758. // If this is a resumption and the original handshake didn't support
  759. // ChannelID then we didn't record the original handshake hashes in the
  760. // session and so cannot resume with ChannelIDs.
  761. if (ssl->session != NULL &&
  762. ssl->session->original_handshake_hash_len == 0) {
  763. ssl->s3->channel_id_valid = false;
  764. }
  765. struct OPENSSL_timeval now;
  766. ssl_get_current_time(ssl, &now);
  767. ssl->s3->server_random[0] = now.tv_sec >> 24;
  768. ssl->s3->server_random[1] = now.tv_sec >> 16;
  769. ssl->s3->server_random[2] = now.tv_sec >> 8;
  770. ssl->s3->server_random[3] = now.tv_sec;
  771. if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
  772. return ssl_hs_error;
  773. }
  774. // Implement the TLS 1.3 anti-downgrade feature.
  775. if (ssl_supports_version(hs, TLS1_3_VERSION)) {
  776. if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
  777. if (hs->apply_jdk11_workaround) {
  778. // JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
  779. // here. However, the signal is only effective if all TLS 1.2
  780. // ServerHellos produced by the server are marked. Thus we send a
  781. // different non-standard signal for the time being, until JDK 11.0.2 is
  782. // released and clients have updated.
  783. copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
  784. } else {
  785. copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
  786. }
  787. } else {
  788. copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
  789. }
  790. }
  791. const SSL_SESSION *session = hs->new_session.get();
  792. if (ssl->session != nullptr) {
  793. session = ssl->session.get();
  794. }
  795. ScopedCBB cbb;
  796. CBB body, session_id;
  797. if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
  798. !CBB_add_u16(&body, ssl->version) ||
  799. !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
  800. !CBB_add_u8_length_prefixed(&body, &session_id) ||
  801. !CBB_add_bytes(&session_id, session->session_id,
  802. session->session_id_length) ||
  803. !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
  804. !CBB_add_u8(&body, 0 /* no compression */) ||
  805. !ssl_add_serverhello_tlsext(hs, &body) ||
  806. !ssl_add_message_cbb(ssl, cbb.get())) {
  807. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  808. return ssl_hs_error;
  809. }
  810. if (ssl->session != NULL) {
  811. hs->state = state12_send_server_finished;
  812. } else {
  813. hs->state = state12_send_server_certificate;
  814. }
  815. return ssl_hs_ok;
  816. }
  817. static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
  818. SSL *const ssl = hs->ssl;
  819. ScopedCBB cbb;
  820. if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
  821. if (!ssl_has_certificate(hs)) {
  822. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
  823. return ssl_hs_error;
  824. }
  825. if (!ssl_output_cert_chain(hs)) {
  826. return ssl_hs_error;
  827. }
  828. if (hs->certificate_status_expected) {
  829. CBB body, ocsp_response;
  830. if (!ssl->method->init_message(ssl, cbb.get(), &body,
  831. SSL3_MT_CERTIFICATE_STATUS) ||
  832. !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
  833. !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
  834. !CBB_add_bytes(
  835. &ocsp_response,
  836. CRYPTO_BUFFER_data(hs->config->cert->ocsp_response.get()),
  837. CRYPTO_BUFFER_len(hs->config->cert->ocsp_response.get())) ||
  838. !ssl_add_message_cbb(ssl, cbb.get())) {
  839. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  840. return ssl_hs_error;
  841. }
  842. }
  843. }
  844. // Assemble ServerKeyExchange parameters if needed.
  845. uint32_t alg_k = hs->new_cipher->algorithm_mkey;
  846. uint32_t alg_a = hs->new_cipher->algorithm_auth;
  847. if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
  848. ((alg_a & SSL_aPSK) && hs->config->psk_identity_hint)) {
  849. // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
  850. // the client and server randoms for the signing transcript.
  851. CBB child;
  852. if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
  853. !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
  854. !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
  855. return ssl_hs_error;
  856. }
  857. // PSK ciphers begin with an identity hint.
  858. if (alg_a & SSL_aPSK) {
  859. size_t len = hs->config->psk_identity_hint == nullptr
  860. ? 0
  861. : strlen(hs->config->psk_identity_hint.get());
  862. if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
  863. !CBB_add_bytes(&child,
  864. (const uint8_t *)hs->config->psk_identity_hint.get(),
  865. len)) {
  866. return ssl_hs_error;
  867. }
  868. }
  869. if (alg_k & SSL_kECDHE) {
  870. // Determine the group to use.
  871. uint16_t group_id;
  872. if (!tls1_get_shared_group(hs, &group_id)) {
  873. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  874. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  875. return ssl_hs_error;
  876. }
  877. hs->new_session->group_id = group_id;
  878. // Set up ECDH, generate a key, and emit the public half.
  879. hs->key_shares[0] = SSLKeyShare::Create(group_id);
  880. if (!hs->key_shares[0] ||
  881. !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||
  882. !CBB_add_u16(cbb.get(), group_id) ||
  883. !CBB_add_u8_length_prefixed(cbb.get(), &child) ||
  884. !hs->key_shares[0]->Offer(&child)) {
  885. return ssl_hs_error;
  886. }
  887. } else {
  888. assert(alg_k & SSL_kPSK);
  889. }
  890. if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
  891. return ssl_hs_error;
  892. }
  893. }
  894. hs->state = state12_send_server_key_exchange;
  895. return ssl_hs_ok;
  896. }
  897. static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
  898. SSL *const ssl = hs->ssl;
  899. if (hs->server_params.size() == 0) {
  900. hs->state = state12_send_server_hello_done;
  901. return ssl_hs_ok;
  902. }
  903. ScopedCBB cbb;
  904. CBB body, child;
  905. if (!ssl->method->init_message(ssl, cbb.get(), &body,
  906. SSL3_MT_SERVER_KEY_EXCHANGE) ||
  907. // |hs->server_params| contains a prefix for signing.
  908. hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
  909. !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
  910. hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
  911. return ssl_hs_error;
  912. }
  913. // Add a signature.
  914. if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
  915. if (!ssl_has_private_key(hs)) {
  916. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  917. return ssl_hs_error;
  918. }
  919. // Determine the signature algorithm.
  920. uint16_t signature_algorithm;
  921. if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
  922. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  923. return ssl_hs_error;
  924. }
  925. if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
  926. if (!CBB_add_u16(&body, signature_algorithm)) {
  927. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  928. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  929. return ssl_hs_error;
  930. }
  931. }
  932. // Add space for the signature.
  933. const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
  934. uint8_t *ptr;
  935. if (!CBB_add_u16_length_prefixed(&body, &child) ||
  936. !CBB_reserve(&child, &ptr, max_sig_len)) {
  937. return ssl_hs_error;
  938. }
  939. size_t sig_len;
  940. switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
  941. signature_algorithm, hs->server_params)) {
  942. case ssl_private_key_success:
  943. if (!CBB_did_write(&child, sig_len)) {
  944. return ssl_hs_error;
  945. }
  946. break;
  947. case ssl_private_key_failure:
  948. return ssl_hs_error;
  949. case ssl_private_key_retry:
  950. return ssl_hs_private_key_operation;
  951. }
  952. }
  953. if (!ssl_add_message_cbb(ssl, cbb.get())) {
  954. return ssl_hs_error;
  955. }
  956. hs->server_params.Reset();
  957. hs->state = state12_send_server_hello_done;
  958. return ssl_hs_ok;
  959. }
  960. static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
  961. SSL *const ssl = hs->ssl;
  962. ScopedCBB cbb;
  963. CBB body;
  964. if (hs->cert_request) {
  965. CBB cert_types, sigalgs_cbb;
  966. if (!ssl->method->init_message(ssl, cbb.get(), &body,
  967. SSL3_MT_CERTIFICATE_REQUEST) ||
  968. !CBB_add_u8_length_prefixed(&body, &cert_types) ||
  969. !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
  970. !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN) ||
  971. // TLS 1.2 has no way to specify different signature algorithms for
  972. // certificates and the online signature, so emit the more restrictive
  973. // certificate list.
  974. (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
  975. (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
  976. !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb, true /* certs */))) ||
  977. !ssl_add_client_CA_list(hs, &body) ||
  978. !ssl_add_message_cbb(ssl, cbb.get())) {
  979. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  980. return ssl_hs_error;
  981. }
  982. }
  983. if (!ssl->method->init_message(ssl, cbb.get(), &body,
  984. SSL3_MT_SERVER_HELLO_DONE) ||
  985. !ssl_add_message_cbb(ssl, cbb.get())) {
  986. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  987. return ssl_hs_error;
  988. }
  989. hs->state = state12_read_client_certificate;
  990. return ssl_hs_flush;
  991. }
  992. static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
  993. SSL *const ssl = hs->ssl;
  994. if (hs->handback && hs->new_cipher->algorithm_mkey == SSL_kECDHE) {
  995. return ssl_hs_handback;
  996. }
  997. if (!hs->cert_request) {
  998. hs->state = state12_verify_client_certificate;
  999. return ssl_hs_ok;
  1000. }
  1001. SSLMessage msg;
  1002. if (!ssl->method->get_message(ssl, &msg)) {
  1003. return ssl_hs_read_message;
  1004. }
  1005. if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
  1006. return ssl_hs_error;
  1007. }
  1008. if (!ssl_hash_message(hs, msg)) {
  1009. return ssl_hs_error;
  1010. }
  1011. CBS certificate_msg = msg.body;
  1012. uint8_t alert = SSL_AD_DECODE_ERROR;
  1013. if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
  1014. hs->config->retain_only_sha256_of_client_certs
  1015. ? hs->new_session->peer_sha256
  1016. : nullptr,
  1017. &certificate_msg, ssl->ctx->pool)) {
  1018. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  1019. return ssl_hs_error;
  1020. }
  1021. if (CBS_len(&certificate_msg) != 0 ||
  1022. !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
  1023. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1024. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1025. return ssl_hs_error;
  1026. }
  1027. if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
  1028. // No client certificate so the handshake buffer may be discarded.
  1029. hs->transcript.FreeBuffer();
  1030. if (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
  1031. // Fail for TLS only if we required a certificate
  1032. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1033. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1034. return ssl_hs_error;
  1035. }
  1036. // OpenSSL returns X509_V_OK when no certificates are received. This is
  1037. // classed by them as a bug, but it's assumed by at least NGINX.
  1038. hs->new_session->verify_result = X509_V_OK;
  1039. } else if (hs->config->retain_only_sha256_of_client_certs) {
  1040. // The hash will have been filled in.
  1041. hs->new_session->peer_sha256_valid = 1;
  1042. }
  1043. ssl->method->next_message(ssl);
  1044. hs->state = state12_verify_client_certificate;
  1045. return ssl_hs_ok;
  1046. }
  1047. static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
  1048. if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) > 0) {
  1049. switch (ssl_verify_peer_cert(hs)) {
  1050. case ssl_verify_ok:
  1051. break;
  1052. case ssl_verify_invalid:
  1053. return ssl_hs_error;
  1054. case ssl_verify_retry:
  1055. return ssl_hs_certificate_verify;
  1056. }
  1057. }
  1058. hs->state = state12_read_client_key_exchange;
  1059. return ssl_hs_ok;
  1060. }
  1061. static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
  1062. SSL *const ssl = hs->ssl;
  1063. SSLMessage msg;
  1064. if (!ssl->method->get_message(ssl, &msg)) {
  1065. return ssl_hs_read_message;
  1066. }
  1067. if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
  1068. return ssl_hs_error;
  1069. }
  1070. CBS client_key_exchange = msg.body;
  1071. uint32_t alg_k = hs->new_cipher->algorithm_mkey;
  1072. uint32_t alg_a = hs->new_cipher->algorithm_auth;
  1073. // If using a PSK key exchange, parse the PSK identity.
  1074. if (alg_a & SSL_aPSK) {
  1075. CBS psk_identity;
  1076. // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
  1077. // then this is the only field in the message.
  1078. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1079. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
  1080. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1081. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1082. return ssl_hs_error;
  1083. }
  1084. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1085. CBS_contains_zero_byte(&psk_identity)) {
  1086. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1087. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  1088. return ssl_hs_error;
  1089. }
  1090. char *raw = nullptr;
  1091. if (!CBS_strdup(&psk_identity, &raw)) {
  1092. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1093. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1094. return ssl_hs_error;
  1095. }
  1096. hs->new_session->psk_identity.reset(raw);
  1097. }
  1098. // Depending on the key exchange method, compute |premaster_secret|.
  1099. Array<uint8_t> premaster_secret;
  1100. if (alg_k & SSL_kRSA) {
  1101. CBS encrypted_premaster_secret;
  1102. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1103. &encrypted_premaster_secret) ||
  1104. CBS_len(&client_key_exchange) != 0) {
  1105. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1106. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1107. return ssl_hs_error;
  1108. }
  1109. // Allocate a buffer large enough for an RSA decryption.
  1110. Array<uint8_t> decrypt_buf;
  1111. if (!decrypt_buf.Init(EVP_PKEY_size(hs->local_pubkey.get()))) {
  1112. return ssl_hs_error;
  1113. }
  1114. // Decrypt with no padding. PKCS#1 padding will be removed as part of the
  1115. // timing-sensitive code below.
  1116. size_t decrypt_len;
  1117. switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
  1118. decrypt_buf.size(),
  1119. encrypted_premaster_secret)) {
  1120. case ssl_private_key_success:
  1121. break;
  1122. case ssl_private_key_failure:
  1123. return ssl_hs_error;
  1124. case ssl_private_key_retry:
  1125. return ssl_hs_private_key_operation;
  1126. }
  1127. if (decrypt_len != decrypt_buf.size()) {
  1128. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1129. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
  1130. return ssl_hs_error;
  1131. }
  1132. CONSTTIME_SECRET(decrypt_buf.data(), decrypt_len);
  1133. // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
  1134. // section 7.4.7.1.
  1135. if (!premaster_secret.Init(SSL_MAX_MASTER_KEY_LENGTH) ||
  1136. !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
  1137. return ssl_hs_error;
  1138. }
  1139. // The smallest padded premaster is 11 bytes of overhead. Small keys are
  1140. // publicly invalid.
  1141. if (decrypt_len < 11 + premaster_secret.size()) {
  1142. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1143. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
  1144. return ssl_hs_error;
  1145. }
  1146. // Check the padding. See RFC 3447, section 7.2.2.
  1147. size_t padding_len = decrypt_len - premaster_secret.size();
  1148. uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
  1149. constant_time_eq_int_8(decrypt_buf[1], 2);
  1150. for (size_t i = 2; i < padding_len - 1; i++) {
  1151. good &= ~constant_time_is_zero_8(decrypt_buf[i]);
  1152. }
  1153. good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
  1154. // The premaster secret must begin with |client_version|. This too must be
  1155. // checked in constant time (http://eprint.iacr.org/2003/052/).
  1156. good &= constant_time_eq_8(decrypt_buf[padding_len],
  1157. (unsigned)(hs->client_version >> 8));
  1158. good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
  1159. (unsigned)(hs->client_version & 0xff));
  1160. // Select, in constant time, either the decrypted premaster or the random
  1161. // premaster based on |good|.
  1162. for (size_t i = 0; i < premaster_secret.size(); i++) {
  1163. premaster_secret[i] = constant_time_select_8(
  1164. good, decrypt_buf[padding_len + i], premaster_secret[i]);
  1165. }
  1166. } else if (alg_k & SSL_kECDHE) {
  1167. // Parse the ClientKeyExchange.
  1168. CBS peer_key;
  1169. if (!CBS_get_u8_length_prefixed(&client_key_exchange, &peer_key) ||
  1170. CBS_len(&client_key_exchange) != 0) {
  1171. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1172. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1173. return ssl_hs_error;
  1174. }
  1175. // Compute the premaster.
  1176. uint8_t alert = SSL_AD_DECODE_ERROR;
  1177. if (!hs->key_shares[0]->Finish(&premaster_secret, &alert, peer_key)) {
  1178. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  1179. return ssl_hs_error;
  1180. }
  1181. // The key exchange state may now be discarded.
  1182. hs->key_shares[0].reset();
  1183. hs->key_shares[1].reset();
  1184. } else if (!(alg_k & SSL_kPSK)) {
  1185. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1186. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1187. return ssl_hs_error;
  1188. }
  1189. // For a PSK cipher suite, the actual pre-master secret is combined with the
  1190. // pre-shared key.
  1191. if (alg_a & SSL_aPSK) {
  1192. if (hs->config->psk_server_callback == NULL) {
  1193. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1194. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1195. return ssl_hs_error;
  1196. }
  1197. // Look up the key for the identity.
  1198. uint8_t psk[PSK_MAX_PSK_LEN];
  1199. unsigned psk_len = hs->config->psk_server_callback(
  1200. ssl, hs->new_session->psk_identity.get(), psk, sizeof(psk));
  1201. if (psk_len > PSK_MAX_PSK_LEN) {
  1202. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1203. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1204. return ssl_hs_error;
  1205. } else if (psk_len == 0) {
  1206. // PSK related to the given identity not found.
  1207. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1208. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
  1209. return ssl_hs_error;
  1210. }
  1211. if (alg_k & SSL_kPSK) {
  1212. // In plain PSK, other_secret is a block of 0s with the same length as the
  1213. // pre-shared key.
  1214. if (!premaster_secret.Init(psk_len)) {
  1215. return ssl_hs_error;
  1216. }
  1217. OPENSSL_memset(premaster_secret.data(), 0, premaster_secret.size());
  1218. }
  1219. ScopedCBB new_premaster;
  1220. CBB child;
  1221. if (!CBB_init(new_premaster.get(),
  1222. 2 + psk_len + 2 + premaster_secret.size()) ||
  1223. !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
  1224. !CBB_add_bytes(&child, premaster_secret.data(),
  1225. premaster_secret.size()) ||
  1226. !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
  1227. !CBB_add_bytes(&child, psk, psk_len) ||
  1228. !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
  1229. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1230. return ssl_hs_error;
  1231. }
  1232. }
  1233. if (!ssl_hash_message(hs, msg)) {
  1234. return ssl_hs_error;
  1235. }
  1236. // Compute the master secret.
  1237. hs->new_session->master_key_length = tls1_generate_master_secret(
  1238. hs, hs->new_session->master_key, premaster_secret);
  1239. if (hs->new_session->master_key_length == 0) {
  1240. return ssl_hs_error;
  1241. }
  1242. hs->new_session->extended_master_secret = hs->extended_master_secret;
  1243. CONSTTIME_DECLASSIFY(hs->new_session->master_key,
  1244. hs->new_session->master_key_length);
  1245. ssl->method->next_message(ssl);
  1246. hs->state = state12_read_client_certificate_verify;
  1247. return ssl_hs_ok;
  1248. }
  1249. static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
  1250. SSL *const ssl = hs->ssl;
  1251. // Only RSA and ECDSA client certificates are supported, so a
  1252. // CertificateVerify is required if and only if there's a client certificate.
  1253. if (!hs->peer_pubkey) {
  1254. hs->transcript.FreeBuffer();
  1255. hs->state = state12_read_change_cipher_spec;
  1256. return ssl_hs_ok;
  1257. }
  1258. SSLMessage msg;
  1259. if (!ssl->method->get_message(ssl, &msg)) {
  1260. return ssl_hs_read_message;
  1261. }
  1262. if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
  1263. return ssl_hs_error;
  1264. }
  1265. CBS certificate_verify = msg.body, signature;
  1266. // Determine the signature algorithm.
  1267. uint16_t signature_algorithm = 0;
  1268. if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
  1269. if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
  1270. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1271. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1272. return ssl_hs_error;
  1273. }
  1274. uint8_t alert = SSL_AD_DECODE_ERROR;
  1275. if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
  1276. ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
  1277. return ssl_hs_error;
  1278. }
  1279. hs->new_session->peer_signature_algorithm = signature_algorithm;
  1280. } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
  1281. hs->peer_pubkey.get())) {
  1282. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  1283. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
  1284. return ssl_hs_error;
  1285. }
  1286. // Parse and verify the signature.
  1287. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  1288. CBS_len(&certificate_verify) != 0) {
  1289. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1290. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1291. return ssl_hs_error;
  1292. }
  1293. if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
  1294. hs->peer_pubkey.get(), hs->transcript.buffer())) {
  1295. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1296. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
  1297. return ssl_hs_error;
  1298. }
  1299. // The handshake buffer is no longer necessary, and we may hash the current
  1300. // message.
  1301. hs->transcript.FreeBuffer();
  1302. if (!ssl_hash_message(hs, msg)) {
  1303. return ssl_hs_error;
  1304. }
  1305. ssl->method->next_message(ssl);
  1306. hs->state = state12_read_change_cipher_spec;
  1307. return ssl_hs_ok;
  1308. }
  1309. static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
  1310. if (hs->handback && hs->ssl->session != NULL) {
  1311. return ssl_hs_handback;
  1312. }
  1313. hs->state = state12_process_change_cipher_spec;
  1314. return ssl_hs_read_change_cipher_spec;
  1315. }
  1316. static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
  1317. if (!tls1_change_cipher_state(hs, evp_aead_open)) {
  1318. return ssl_hs_error;
  1319. }
  1320. hs->state = state12_read_next_proto;
  1321. return ssl_hs_ok;
  1322. }
  1323. static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
  1324. SSL *const ssl = hs->ssl;
  1325. if (!hs->next_proto_neg_seen) {
  1326. hs->state = state12_read_channel_id;
  1327. return ssl_hs_ok;
  1328. }
  1329. SSLMessage msg;
  1330. if (!ssl->method->get_message(ssl, &msg)) {
  1331. return ssl_hs_read_message;
  1332. }
  1333. if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
  1334. !ssl_hash_message(hs, msg)) {
  1335. return ssl_hs_error;
  1336. }
  1337. CBS next_protocol = msg.body, selected_protocol, padding;
  1338. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  1339. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  1340. CBS_len(&next_protocol) != 0) {
  1341. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1342. ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1343. return ssl_hs_error;
  1344. }
  1345. if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
  1346. return ssl_hs_error;
  1347. }
  1348. ssl->method->next_message(ssl);
  1349. hs->state = state12_read_channel_id;
  1350. return ssl_hs_ok;
  1351. }
  1352. static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
  1353. SSL *const ssl = hs->ssl;
  1354. if (!ssl->s3->channel_id_valid) {
  1355. hs->state = state12_read_client_finished;
  1356. return ssl_hs_ok;
  1357. }
  1358. SSLMessage msg;
  1359. if (!ssl->method->get_message(ssl, &msg)) {
  1360. return ssl_hs_read_message;
  1361. }
  1362. if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
  1363. !tls1_verify_channel_id(hs, msg) ||
  1364. !ssl_hash_message(hs, msg)) {
  1365. return ssl_hs_error;
  1366. }
  1367. ssl->method->next_message(ssl);
  1368. hs->state = state12_read_client_finished;
  1369. return ssl_hs_ok;
  1370. }
  1371. static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
  1372. SSL *const ssl = hs->ssl;
  1373. enum ssl_hs_wait_t wait = ssl_get_finished(hs);
  1374. if (wait != ssl_hs_ok) {
  1375. return wait;
  1376. }
  1377. if (ssl->session != NULL) {
  1378. hs->state = state12_finish_server_handshake;
  1379. } else {
  1380. hs->state = state12_send_server_finished;
  1381. }
  1382. // If this is a full handshake with ChannelID then record the handshake
  1383. // hashes in |hs->new_session| in case we need them to verify a
  1384. // ChannelID signature on a resumption of this session in the future.
  1385. if (ssl->session == NULL && ssl->s3->channel_id_valid &&
  1386. !tls1_record_handshake_hashes_for_channel_id(hs)) {
  1387. return ssl_hs_error;
  1388. }
  1389. return ssl_hs_ok;
  1390. }
  1391. static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
  1392. SSL *const ssl = hs->ssl;
  1393. if (hs->ticket_expected) {
  1394. const SSL_SESSION *session;
  1395. UniquePtr<SSL_SESSION> session_copy;
  1396. if (ssl->session == NULL) {
  1397. // Fix the timeout to measure from the ticket issuance time.
  1398. ssl_session_rebase_time(ssl, hs->new_session.get());
  1399. session = hs->new_session.get();
  1400. } else {
  1401. // We are renewing an existing session. Duplicate the session to adjust
  1402. // the timeout.
  1403. session_copy =
  1404. SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
  1405. if (!session_copy) {
  1406. return ssl_hs_error;
  1407. }
  1408. ssl_session_rebase_time(ssl, session_copy.get());
  1409. session = session_copy.get();
  1410. }
  1411. ScopedCBB cbb;
  1412. CBB body, ticket;
  1413. if (!ssl->method->init_message(ssl, cbb.get(), &body,
  1414. SSL3_MT_NEW_SESSION_TICKET) ||
  1415. !CBB_add_u32(&body, session->timeout) ||
  1416. !CBB_add_u16_length_prefixed(&body, &ticket) ||
  1417. !ssl_encrypt_ticket(hs, &ticket, session) ||
  1418. !ssl_add_message_cbb(ssl, cbb.get())) {
  1419. return ssl_hs_error;
  1420. }
  1421. }
  1422. if (!ssl->method->add_change_cipher_spec(ssl) ||
  1423. !tls1_change_cipher_state(hs, evp_aead_seal) ||
  1424. !ssl_send_finished(hs)) {
  1425. return ssl_hs_error;
  1426. }
  1427. if (ssl->session != NULL) {
  1428. hs->state = state12_read_change_cipher_spec;
  1429. } else {
  1430. hs->state = state12_finish_server_handshake;
  1431. }
  1432. return ssl_hs_flush;
  1433. }
  1434. static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
  1435. SSL *const ssl = hs->ssl;
  1436. if (hs->handback) {
  1437. return ssl_hs_handback;
  1438. }
  1439. ssl->method->on_handshake_complete(ssl);
  1440. // If we aren't retaining peer certificates then we can discard it now.
  1441. if (hs->new_session != NULL &&
  1442. hs->config->retain_only_sha256_of_client_certs) {
  1443. hs->new_session->certs.reset();
  1444. ssl->ctx->x509_method->session_clear(hs->new_session.get());
  1445. }
  1446. if (ssl->session != NULL) {
  1447. ssl->s3->established_session = UpRef(ssl->session);
  1448. } else {
  1449. ssl->s3->established_session = std::move(hs->new_session);
  1450. ssl->s3->established_session->not_resumable = false;
  1451. }
  1452. hs->handshake_finalized = true;
  1453. ssl->s3->initial_handshake_complete = true;
  1454. ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
  1455. hs->state = state12_done;
  1456. return ssl_hs_ok;
  1457. }
  1458. enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
  1459. while (hs->state != state12_done) {
  1460. enum ssl_hs_wait_t ret = ssl_hs_error;
  1461. enum tls12_server_hs_state_t state =
  1462. static_cast<enum tls12_server_hs_state_t>(hs->state);
  1463. switch (state) {
  1464. case state12_start_accept:
  1465. ret = do_start_accept(hs);
  1466. break;
  1467. case state12_read_client_hello:
  1468. ret = do_read_client_hello(hs);
  1469. break;
  1470. case state12_select_certificate:
  1471. ret = do_select_certificate(hs);
  1472. break;
  1473. case state12_tls13:
  1474. ret = do_tls13(hs);
  1475. break;
  1476. case state12_select_parameters:
  1477. ret = do_select_parameters(hs);
  1478. break;
  1479. case state12_send_server_hello:
  1480. ret = do_send_server_hello(hs);
  1481. break;
  1482. case state12_send_server_certificate:
  1483. ret = do_send_server_certificate(hs);
  1484. break;
  1485. case state12_send_server_key_exchange:
  1486. ret = do_send_server_key_exchange(hs);
  1487. break;
  1488. case state12_send_server_hello_done:
  1489. ret = do_send_server_hello_done(hs);
  1490. break;
  1491. case state12_read_client_certificate:
  1492. ret = do_read_client_certificate(hs);
  1493. break;
  1494. case state12_verify_client_certificate:
  1495. ret = do_verify_client_certificate(hs);
  1496. break;
  1497. case state12_read_client_key_exchange:
  1498. ret = do_read_client_key_exchange(hs);
  1499. break;
  1500. case state12_read_client_certificate_verify:
  1501. ret = do_read_client_certificate_verify(hs);
  1502. break;
  1503. case state12_read_change_cipher_spec:
  1504. ret = do_read_change_cipher_spec(hs);
  1505. break;
  1506. case state12_process_change_cipher_spec:
  1507. ret = do_process_change_cipher_spec(hs);
  1508. break;
  1509. case state12_read_next_proto:
  1510. ret = do_read_next_proto(hs);
  1511. break;
  1512. case state12_read_channel_id:
  1513. ret = do_read_channel_id(hs);
  1514. break;
  1515. case state12_read_client_finished:
  1516. ret = do_read_client_finished(hs);
  1517. break;
  1518. case state12_send_server_finished:
  1519. ret = do_send_server_finished(hs);
  1520. break;
  1521. case state12_finish_server_handshake:
  1522. ret = do_finish_server_handshake(hs);
  1523. break;
  1524. case state12_done:
  1525. ret = ssl_hs_ok;
  1526. break;
  1527. }
  1528. if (hs->state != state) {
  1529. ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
  1530. }
  1531. if (ret != ssl_hs_ok) {
  1532. return ret;
  1533. }
  1534. }
  1535. ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
  1536. return ssl_hs_ok;
  1537. }
  1538. const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
  1539. enum tls12_server_hs_state_t state =
  1540. static_cast<enum tls12_server_hs_state_t>(hs->state);
  1541. switch (state) {
  1542. case state12_start_accept:
  1543. return "TLS server start_accept";
  1544. case state12_read_client_hello:
  1545. return "TLS server read_client_hello";
  1546. case state12_select_certificate:
  1547. return "TLS server select_certificate";
  1548. case state12_tls13:
  1549. return tls13_server_handshake_state(hs);
  1550. case state12_select_parameters:
  1551. return "TLS server select_parameters";
  1552. case state12_send_server_hello:
  1553. return "TLS server send_server_hello";
  1554. case state12_send_server_certificate:
  1555. return "TLS server send_server_certificate";
  1556. case state12_send_server_key_exchange:
  1557. return "TLS server send_server_key_exchange";
  1558. case state12_send_server_hello_done:
  1559. return "TLS server send_server_hello_done";
  1560. case state12_read_client_certificate:
  1561. return "TLS server read_client_certificate";
  1562. case state12_verify_client_certificate:
  1563. return "TLS server verify_client_certificate";
  1564. case state12_read_client_key_exchange:
  1565. return "TLS server read_client_key_exchange";
  1566. case state12_read_client_certificate_verify:
  1567. return "TLS server read_client_certificate_verify";
  1568. case state12_read_change_cipher_spec:
  1569. return "TLS server read_change_cipher_spec";
  1570. case state12_process_change_cipher_spec:
  1571. return "TLS server process_change_cipher_spec";
  1572. case state12_read_next_proto:
  1573. return "TLS server read_next_proto";
  1574. case state12_read_channel_id:
  1575. return "TLS server read_channel_id";
  1576. case state12_read_client_finished:
  1577. return "TLS server read_client_finished";
  1578. case state12_send_server_finished:
  1579. return "TLS server send_server_finished";
  1580. case state12_finish_server_handshake:
  1581. return "TLS server finish_server_handshake";
  1582. case state12_done:
  1583. return "TLS server done";
  1584. }
  1585. return "TLS server unknown";
  1586. }
  1587. BSSL_NAMESPACE_END