test_config.cc 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include "test_config.h"
  15. #include <assert.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <memory>
  20. #include <openssl/base64.h>
  21. #include <openssl/rand.h>
  22. #include <openssl/ssl.h>
  23. #include "../../crypto/internal.h"
  24. #include "../internal.h"
  25. #include "test_state.h"
  26. namespace {
  27. template <typename T>
  28. struct Flag {
  29. const char *flag;
  30. T TestConfig::*member;
  31. };
  32. // FindField looks for the flag in |flags| that matches |flag|. If one is found,
  33. // it returns a pointer to the corresponding field in |config|. Otherwise, it
  34. // returns NULL.
  35. template<typename T, size_t N>
  36. T *FindField(TestConfig *config, const Flag<T> (&flags)[N], const char *flag) {
  37. for (size_t i = 0; i < N; i++) {
  38. if (strcmp(flag, flags[i].flag) == 0) {
  39. return &(config->*(flags[i].member));
  40. }
  41. }
  42. return NULL;
  43. }
  44. const Flag<bool> kBoolFlags[] = {
  45. {"-server", &TestConfig::is_server},
  46. {"-dtls", &TestConfig::is_dtls},
  47. {"-fallback-scsv", &TestConfig::fallback_scsv},
  48. {"-require-any-client-certificate",
  49. &TestConfig::require_any_client_certificate},
  50. {"-false-start", &TestConfig::false_start},
  51. {"-async", &TestConfig::async},
  52. {"-write-different-record-sizes",
  53. &TestConfig::write_different_record_sizes},
  54. {"-cbc-record-splitting", &TestConfig::cbc_record_splitting},
  55. {"-partial-write", &TestConfig::partial_write},
  56. {"-no-tls13", &TestConfig::no_tls13},
  57. {"-no-tls12", &TestConfig::no_tls12},
  58. {"-no-tls11", &TestConfig::no_tls11},
  59. {"-no-tls1", &TestConfig::no_tls1},
  60. {"-no-ticket", &TestConfig::no_ticket},
  61. {"-enable-channel-id", &TestConfig::enable_channel_id},
  62. {"-shim-writes-first", &TestConfig::shim_writes_first},
  63. {"-expect-session-miss", &TestConfig::expect_session_miss},
  64. {"-decline-alpn", &TestConfig::decline_alpn},
  65. {"-select-empty-alpn", &TestConfig::select_empty_alpn},
  66. {"-expect-extended-master-secret",
  67. &TestConfig::expect_extended_master_secret},
  68. {"-enable-ocsp-stapling", &TestConfig::enable_ocsp_stapling},
  69. {"-enable-signed-cert-timestamps",
  70. &TestConfig::enable_signed_cert_timestamps},
  71. {"-implicit-handshake", &TestConfig::implicit_handshake},
  72. {"-use-early-callback", &TestConfig::use_early_callback},
  73. {"-fail-early-callback", &TestConfig::fail_early_callback},
  74. {"-install-ddos-callback", &TestConfig::install_ddos_callback},
  75. {"-fail-ddos-callback", &TestConfig::fail_ddos_callback},
  76. {"-fail-cert-callback", &TestConfig::fail_cert_callback},
  77. {"-handshake-never-done", &TestConfig::handshake_never_done},
  78. {"-use-export-context", &TestConfig::use_export_context},
  79. {"-tls-unique", &TestConfig::tls_unique},
  80. {"-expect-ticket-renewal", &TestConfig::expect_ticket_renewal},
  81. {"-expect-no-session", &TestConfig::expect_no_session},
  82. {"-expect-ticket-supports-early-data",
  83. &TestConfig::expect_ticket_supports_early_data},
  84. {"-use-ticket-callback", &TestConfig::use_ticket_callback},
  85. {"-renew-ticket", &TestConfig::renew_ticket},
  86. {"-enable-early-data", &TestConfig::enable_early_data},
  87. {"-check-close-notify", &TestConfig::check_close_notify},
  88. {"-shim-shuts-down", &TestConfig::shim_shuts_down},
  89. {"-verify-fail", &TestConfig::verify_fail},
  90. {"-verify-peer", &TestConfig::verify_peer},
  91. {"-verify-peer-if-no-obc", &TestConfig::verify_peer_if_no_obc},
  92. {"-expect-verify-result", &TestConfig::expect_verify_result},
  93. {"-renegotiate-once", &TestConfig::renegotiate_once},
  94. {"-renegotiate-freely", &TestConfig::renegotiate_freely},
  95. {"-renegotiate-ignore", &TestConfig::renegotiate_ignore},
  96. {"-forbid-renegotiation-after-handshake",
  97. &TestConfig::forbid_renegotiation_after_handshake},
  98. {"-enable-all-curves", &TestConfig::enable_all_curves},
  99. {"-use-old-client-cert-callback",
  100. &TestConfig::use_old_client_cert_callback},
  101. {"-send-alert", &TestConfig::send_alert},
  102. {"-peek-then-read", &TestConfig::peek_then_read},
  103. {"-enable-grease", &TestConfig::enable_grease},
  104. {"-use-exporter-between-reads", &TestConfig::use_exporter_between_reads},
  105. {"-retain-only-sha256-client-cert",
  106. &TestConfig::retain_only_sha256_client_cert},
  107. {"-expect-sha256-client-cert", &TestConfig::expect_sha256_client_cert},
  108. {"-read-with-unfinished-write", &TestConfig::read_with_unfinished_write},
  109. {"-expect-secure-renegotiation", &TestConfig::expect_secure_renegotiation},
  110. {"-expect-no-secure-renegotiation",
  111. &TestConfig::expect_no_secure_renegotiation},
  112. {"-expect-session-id", &TestConfig::expect_session_id},
  113. {"-expect-no-session-id", &TestConfig::expect_no_session_id},
  114. {"-expect-accept-early-data", &TestConfig::expect_accept_early_data},
  115. {"-expect-reject-early-data", &TestConfig::expect_reject_early_data},
  116. {"-expect-no-offer-early-data", &TestConfig::expect_no_offer_early_data},
  117. {"-no-op-extra-handshake", &TestConfig::no_op_extra_handshake},
  118. {"-handshake-twice", &TestConfig::handshake_twice},
  119. {"-allow-unknown-alpn-protos", &TestConfig::allow_unknown_alpn_protos},
  120. {"-enable-ed25519", &TestConfig::enable_ed25519},
  121. {"-use-custom-verify-callback", &TestConfig::use_custom_verify_callback},
  122. {"-allow-false-start-without-alpn",
  123. &TestConfig::allow_false_start_without_alpn},
  124. {"-ignore-tls13-downgrade", &TestConfig::ignore_tls13_downgrade},
  125. {"-expect-tls13-downgrade", &TestConfig::expect_tls13_downgrade},
  126. {"-handoff", &TestConfig::handoff},
  127. {"-no-rsa-pss-rsae-certs", &TestConfig::no_rsa_pss_rsae_certs},
  128. {"-use-ocsp-callback", &TestConfig::use_ocsp_callback},
  129. {"-set-ocsp-in-callback", &TestConfig::set_ocsp_in_callback},
  130. {"-decline-ocsp-callback", &TestConfig::decline_ocsp_callback},
  131. {"-fail-ocsp-callback", &TestConfig::fail_ocsp_callback},
  132. {"-install-cert-compression-algs",
  133. &TestConfig::install_cert_compression_algs},
  134. {"-is-handshaker-supported", &TestConfig::is_handshaker_supported},
  135. {"-handshaker-resume", &TestConfig::handshaker_resume},
  136. {"-reverify-on-resume", &TestConfig::reverify_on_resume},
  137. {"-enforce-rsa-key-usage", &TestConfig::enforce_rsa_key_usage},
  138. {"-jdk11-workaround", &TestConfig::jdk11_workaround},
  139. {"-server-preference", &TestConfig::server_preference},
  140. {"-export-traffic-secrets", &TestConfig::export_traffic_secrets},
  141. {"-key-update", &TestConfig::key_update},
  142. {"-expect-delegated-credential-used",
  143. &TestConfig::expect_delegated_credential_used},
  144. {"-enable-pq-experiment-signal", &TestConfig::enable_pq_experiment_signal},
  145. {"-expect-pq-experiment-signal", &TestConfig::expect_pq_experiment_signal},
  146. };
  147. const Flag<std::string> kStringFlags[] = {
  148. {"-write-settings", &TestConfig::write_settings},
  149. {"-key-file", &TestConfig::key_file},
  150. {"-cert-file", &TestConfig::cert_file},
  151. {"-expect-server-name", &TestConfig::expect_server_name},
  152. {"-advertise-npn", &TestConfig::advertise_npn},
  153. {"-expect-next-proto", &TestConfig::expect_next_proto},
  154. {"-select-next-proto", &TestConfig::select_next_proto},
  155. {"-send-channel-id", &TestConfig::send_channel_id},
  156. {"-host-name", &TestConfig::host_name},
  157. {"-advertise-alpn", &TestConfig::advertise_alpn},
  158. {"-expect-alpn", &TestConfig::expect_alpn},
  159. {"-expect-late-alpn", &TestConfig::expect_late_alpn},
  160. {"-expect-advertised-alpn", &TestConfig::expect_advertised_alpn},
  161. {"-select-alpn", &TestConfig::select_alpn},
  162. {"-psk", &TestConfig::psk},
  163. {"-psk-identity", &TestConfig::psk_identity},
  164. {"-srtp-profiles", &TestConfig::srtp_profiles},
  165. {"-cipher", &TestConfig::cipher},
  166. {"-export-label", &TestConfig::export_label},
  167. {"-export-context", &TestConfig::export_context},
  168. {"-expect-peer-cert-file", &TestConfig::expect_peer_cert_file},
  169. {"-use-client-ca-list", &TestConfig::use_client_ca_list},
  170. {"-expect-client-ca-list", &TestConfig::expect_client_ca_list},
  171. {"-expect-msg-callback", &TestConfig::expect_msg_callback},
  172. {"-handshaker-path", &TestConfig::handshaker_path},
  173. {"-delegated-credential", &TestConfig::delegated_credential},
  174. {"-expect-early-data-reason", &TestConfig::expect_early_data_reason},
  175. };
  176. const Flag<std::string> kBase64Flags[] = {
  177. {"-expect-certificate-types", &TestConfig::expect_certificate_types},
  178. {"-expect-channel-id", &TestConfig::expect_channel_id},
  179. {"-token-binding-params", &TestConfig::send_token_binding_params},
  180. {"-expect-ocsp-response", &TestConfig::expect_ocsp_response},
  181. {"-expect-signed-cert-timestamps",
  182. &TestConfig::expect_signed_cert_timestamps},
  183. {"-ocsp-response", &TestConfig::ocsp_response},
  184. {"-signed-cert-timestamps", &TestConfig::signed_cert_timestamps},
  185. {"-ticket-key", &TestConfig::ticket_key},
  186. {"-quic-transport-params", &TestConfig::quic_transport_params},
  187. {"-expect-quic-transport-params",
  188. &TestConfig::expect_quic_transport_params},
  189. };
  190. const Flag<int> kIntFlags[] = {
  191. {"-port", &TestConfig::port},
  192. {"-resume-count", &TestConfig::resume_count},
  193. {"-expect-token-binding-param", &TestConfig::expect_token_binding_param},
  194. {"-min-version", &TestConfig::min_version},
  195. {"-max-version", &TestConfig::max_version},
  196. {"-expect-version", &TestConfig::expect_version},
  197. {"-mtu", &TestConfig::mtu},
  198. {"-export-keying-material", &TestConfig::export_keying_material},
  199. {"-expect-total-renegotiations", &TestConfig::expect_total_renegotiations},
  200. {"-expect-peer-signature-algorithm",
  201. &TestConfig::expect_peer_signature_algorithm},
  202. {"-expect-curve-id", &TestConfig::expect_curve_id},
  203. {"-initial-timeout-duration-ms", &TestConfig::initial_timeout_duration_ms},
  204. {"-max-cert-list", &TestConfig::max_cert_list},
  205. {"-expect-cipher-aes", &TestConfig::expect_cipher_aes},
  206. {"-expect-cipher-no-aes", &TestConfig::expect_cipher_no_aes},
  207. {"-resumption-delay", &TestConfig::resumption_delay},
  208. {"-max-send-fragment", &TestConfig::max_send_fragment},
  209. {"-read-size", &TestConfig::read_size},
  210. {"-expect-ticket-age-skew", &TestConfig::expect_ticket_age_skew},
  211. };
  212. const Flag<std::vector<int>> kIntVectorFlags[] = {
  213. {"-signing-prefs", &TestConfig::signing_prefs},
  214. {"-verify-prefs", &TestConfig::verify_prefs},
  215. {"-expect-peer-verify-pref", &TestConfig::expect_peer_verify_prefs},
  216. {"-curves", &TestConfig::curves},
  217. };
  218. bool ParseFlag(char *flag, int argc, char **argv, int *i,
  219. bool skip, TestConfig *out_config) {
  220. bool *bool_field = FindField(out_config, kBoolFlags, flag);
  221. if (bool_field != NULL) {
  222. if (!skip) {
  223. *bool_field = true;
  224. }
  225. return true;
  226. }
  227. std::string *string_field = FindField(out_config, kStringFlags, flag);
  228. if (string_field != NULL) {
  229. *i = *i + 1;
  230. if (*i >= argc) {
  231. fprintf(stderr, "Missing parameter.\n");
  232. return false;
  233. }
  234. if (!skip) {
  235. string_field->assign(argv[*i]);
  236. }
  237. return true;
  238. }
  239. std::string *base64_field = FindField(out_config, kBase64Flags, flag);
  240. if (base64_field != NULL) {
  241. *i = *i + 1;
  242. if (*i >= argc) {
  243. fprintf(stderr, "Missing parameter.\n");
  244. return false;
  245. }
  246. size_t len;
  247. if (!EVP_DecodedLength(&len, strlen(argv[*i]))) {
  248. fprintf(stderr, "Invalid base64: %s.\n", argv[*i]);
  249. return false;
  250. }
  251. std::unique_ptr<uint8_t[]> decoded(new uint8_t[len]);
  252. if (!EVP_DecodeBase64(decoded.get(), &len, len,
  253. reinterpret_cast<const uint8_t *>(argv[*i]),
  254. strlen(argv[*i]))) {
  255. fprintf(stderr, "Invalid base64: %s.\n", argv[*i]);
  256. return false;
  257. }
  258. if (!skip) {
  259. base64_field->assign(reinterpret_cast<const char *>(decoded.get()),
  260. len);
  261. }
  262. return true;
  263. }
  264. int *int_field = FindField(out_config, kIntFlags, flag);
  265. if (int_field) {
  266. *i = *i + 1;
  267. if (*i >= argc) {
  268. fprintf(stderr, "Missing parameter.\n");
  269. return false;
  270. }
  271. if (!skip) {
  272. *int_field = atoi(argv[*i]);
  273. }
  274. return true;
  275. }
  276. std::vector<int> *int_vector_field =
  277. FindField(out_config, kIntVectorFlags, flag);
  278. if (int_vector_field) {
  279. *i = *i + 1;
  280. if (*i >= argc) {
  281. fprintf(stderr, "Missing parameter.\n");
  282. return false;
  283. }
  284. // Each instance of the flag adds to the list.
  285. if (!skip) {
  286. int_vector_field->push_back(atoi(argv[*i]));
  287. }
  288. return true;
  289. }
  290. fprintf(stderr, "Unknown argument: %s.\n", flag);
  291. return false;
  292. }
  293. const char kInit[] = "-on-initial";
  294. const char kResume[] = "-on-resume";
  295. const char kRetry[] = "-on-retry";
  296. } // namespace
  297. bool ParseConfig(int argc, char **argv,
  298. TestConfig *out_initial,
  299. TestConfig *out_resume,
  300. TestConfig *out_retry) {
  301. out_initial->argc = out_resume->argc = out_retry->argc = argc;
  302. out_initial->argv = out_resume->argv = out_retry->argv = argv;
  303. for (int i = 0; i < argc; i++) {
  304. bool skip = false;
  305. char *flag = argv[i];
  306. if (strncmp(flag, kInit, strlen(kInit)) == 0) {
  307. if (!ParseFlag(flag + strlen(kInit), argc, argv, &i, skip, out_initial)) {
  308. return false;
  309. }
  310. } else if (strncmp(flag, kResume, strlen(kResume)) == 0) {
  311. if (!ParseFlag(flag + strlen(kResume), argc, argv, &i, skip,
  312. out_resume)) {
  313. return false;
  314. }
  315. } else if (strncmp(flag, kRetry, strlen(kRetry)) == 0) {
  316. if (!ParseFlag(flag + strlen(kRetry), argc, argv, &i, skip, out_retry)) {
  317. return false;
  318. }
  319. } else {
  320. int i_init = i;
  321. int i_resume = i;
  322. if (!ParseFlag(flag, argc, argv, &i_init, skip, out_initial) ||
  323. !ParseFlag(flag, argc, argv, &i_resume, skip, out_resume) ||
  324. !ParseFlag(flag, argc, argv, &i, skip, out_retry)) {
  325. return false;
  326. }
  327. }
  328. }
  329. return true;
  330. }
  331. static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
  332. static int g_config_index = 0;
  333. static CRYPTO_BUFFER_POOL *g_pool = nullptr;
  334. static void init_once() {
  335. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  336. if (g_config_index < 0) {
  337. abort();
  338. }
  339. g_pool = CRYPTO_BUFFER_POOL_new();
  340. if (!g_pool) {
  341. abort();
  342. }
  343. }
  344. bool SetTestConfig(SSL *ssl, const TestConfig *config) {
  345. CRYPTO_once(&once, init_once);
  346. return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
  347. }
  348. const TestConfig *GetTestConfig(const SSL *ssl) {
  349. CRYPTO_once(&once, init_once);
  350. return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
  351. }
  352. static int LegacyOCSPCallback(SSL *ssl, void *arg) {
  353. const TestConfig *config = GetTestConfig(ssl);
  354. if (!SSL_is_server(ssl)) {
  355. return !config->fail_ocsp_callback;
  356. }
  357. if (!config->ocsp_response.empty() && config->set_ocsp_in_callback &&
  358. !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
  359. config->ocsp_response.size())) {
  360. return SSL_TLSEXT_ERR_ALERT_FATAL;
  361. }
  362. if (config->fail_ocsp_callback) {
  363. return SSL_TLSEXT_ERR_ALERT_FATAL;
  364. }
  365. if (config->decline_ocsp_callback) {
  366. return SSL_TLSEXT_ERR_NOACK;
  367. }
  368. return SSL_TLSEXT_ERR_OK;
  369. }
  370. static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
  371. // SNI must be accessible from the SNI callback.
  372. const TestConfig *config = GetTestConfig(ssl);
  373. const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  374. if (server_name == nullptr ||
  375. std::string(server_name) != config->expect_server_name) {
  376. fprintf(stderr, "servername mismatch (got %s; want %s).\n", server_name,
  377. config->expect_server_name.c_str());
  378. return SSL_TLSEXT_ERR_ALERT_FATAL;
  379. }
  380. return SSL_TLSEXT_ERR_OK;
  381. }
  382. static int NextProtoSelectCallback(SSL *ssl, uint8_t **out, uint8_t *outlen,
  383. const uint8_t *in, unsigned inlen,
  384. void *arg) {
  385. const TestConfig *config = GetTestConfig(ssl);
  386. if (config->select_next_proto.empty()) {
  387. return SSL_TLSEXT_ERR_NOACK;
  388. }
  389. *out = (uint8_t *)config->select_next_proto.data();
  390. *outlen = config->select_next_proto.size();
  391. return SSL_TLSEXT_ERR_OK;
  392. }
  393. static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
  394. unsigned int *out_len, void *arg) {
  395. const TestConfig *config = GetTestConfig(ssl);
  396. if (config->advertise_npn.empty()) {
  397. return SSL_TLSEXT_ERR_NOACK;
  398. }
  399. *out = (const uint8_t *)config->advertise_npn.data();
  400. *out_len = config->advertise_npn.size();
  401. return SSL_TLSEXT_ERR_OK;
  402. }
  403. static void MessageCallback(int is_write, int version, int content_type,
  404. const void *buf, size_t len, SSL *ssl, void *arg) {
  405. const uint8_t *buf_u8 = reinterpret_cast<const uint8_t *>(buf);
  406. const TestConfig *config = GetTestConfig(ssl);
  407. TestState *state = GetTestState(ssl);
  408. if (!state->msg_callback_ok) {
  409. return;
  410. }
  411. if (content_type == SSL3_RT_HEADER) {
  412. if (len !=
  413. (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) {
  414. fprintf(stderr, "Incorrect length for record header: %zu.\n", len);
  415. state->msg_callback_ok = false;
  416. }
  417. return;
  418. }
  419. state->msg_callback_text += is_write ? "write " : "read ";
  420. switch (content_type) {
  421. case 0:
  422. if (version != SSL2_VERSION) {
  423. fprintf(stderr, "Incorrect version for V2ClientHello: %x.\n", version);
  424. state->msg_callback_ok = false;
  425. return;
  426. }
  427. state->msg_callback_text += "v2clienthello\n";
  428. return;
  429. case SSL3_RT_HANDSHAKE: {
  430. CBS cbs;
  431. CBS_init(&cbs, buf_u8, len);
  432. uint8_t type;
  433. uint32_t msg_len;
  434. if (!CBS_get_u8(&cbs, &type) ||
  435. // TODO(davidben): Reporting on entire messages would be more
  436. // consistent than fragments.
  437. (config->is_dtls &&
  438. !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) ||
  439. !CBS_get_u24(&cbs, &msg_len) || !CBS_skip(&cbs, msg_len) ||
  440. CBS_len(&cbs) != 0) {
  441. fprintf(stderr, "Could not parse handshake message.\n");
  442. state->msg_callback_ok = false;
  443. return;
  444. }
  445. char text[16];
  446. snprintf(text, sizeof(text), "hs %d\n", type);
  447. state->msg_callback_text += text;
  448. return;
  449. }
  450. case SSL3_RT_CHANGE_CIPHER_SPEC:
  451. if (len != 1 || buf_u8[0] != 1) {
  452. fprintf(stderr, "Invalid ChangeCipherSpec.\n");
  453. state->msg_callback_ok = false;
  454. return;
  455. }
  456. state->msg_callback_text += "ccs\n";
  457. return;
  458. case SSL3_RT_ALERT:
  459. if (len != 2) {
  460. fprintf(stderr, "Invalid alert.\n");
  461. state->msg_callback_ok = false;
  462. return;
  463. }
  464. char text[16];
  465. snprintf(text, sizeof(text), "alert %d %d\n", buf_u8[0], buf_u8[1]);
  466. state->msg_callback_text += text;
  467. return;
  468. default:
  469. fprintf(stderr, "Invalid content_type: %d.\n", content_type);
  470. state->msg_callback_ok = false;
  471. }
  472. }
  473. static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
  474. EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
  475. int encrypt) {
  476. if (!encrypt) {
  477. if (GetTestState(ssl)->ticket_decrypt_done) {
  478. fprintf(stderr, "TicketKeyCallback called after completion.\n");
  479. return -1;
  480. }
  481. GetTestState(ssl)->ticket_decrypt_done = true;
  482. }
  483. // This is just test code, so use the all-zeros key.
  484. static const uint8_t kZeros[16] = {0};
  485. if (encrypt) {
  486. OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
  487. RAND_bytes(iv, 16);
  488. } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
  489. return 0;
  490. }
  491. if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
  492. !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
  493. return -1;
  494. }
  495. if (!encrypt) {
  496. return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
  497. }
  498. return 1;
  499. }
  500. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  501. // This callback is called as the handshake completes. |SSL_get_session|
  502. // must continue to work and, historically, |SSL_in_init| returned false at
  503. // this point.
  504. if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
  505. fprintf(stderr, "Invalid state for NewSessionCallback.\n");
  506. abort();
  507. }
  508. GetTestState(ssl)->got_new_session = true;
  509. GetTestState(ssl)->new_session.reset(session);
  510. return 1;
  511. }
  512. static void InfoCallback(const SSL *ssl, int type, int val) {
  513. if (type == SSL_CB_HANDSHAKE_DONE) {
  514. if (GetTestConfig(ssl)->handshake_never_done) {
  515. fprintf(stderr, "Handshake unexpectedly completed.\n");
  516. // Abort before any expected error code is printed, to ensure the overall
  517. // test fails.
  518. abort();
  519. }
  520. // This callback is called when the handshake completes. |SSL_get_session|
  521. // must continue to work and |SSL_in_init| must return false.
  522. if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
  523. fprintf(stderr, "Invalid state for SSL_CB_HANDSHAKE_DONE.\n");
  524. abort();
  525. }
  526. GetTestState(ssl)->handshake_done = true;
  527. // Callbacks may be called again on a new handshake.
  528. GetTestState(ssl)->ticket_decrypt_done = false;
  529. GetTestState(ssl)->alpn_select_done = false;
  530. }
  531. }
  532. static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
  533. *out_pkey = GetTestState(ssl)->channel_id.release();
  534. }
  535. static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len,
  536. int *copy) {
  537. TestState *async_state = GetTestState(ssl);
  538. if (async_state->session) {
  539. *copy = 0;
  540. return async_state->session.release();
  541. } else if (async_state->pending_session) {
  542. return SSL_magic_pending_session_ptr();
  543. } else {
  544. return NULL;
  545. }
  546. }
  547. static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
  548. *out_clock = *GetClock();
  549. }
  550. static int AlpnSelectCallback(SSL *ssl, const uint8_t **out, uint8_t *outlen,
  551. const uint8_t *in, unsigned inlen, void *arg) {
  552. if (GetTestState(ssl)->alpn_select_done) {
  553. fprintf(stderr, "AlpnSelectCallback called after completion.\n");
  554. exit(1);
  555. }
  556. GetTestState(ssl)->alpn_select_done = true;
  557. const TestConfig *config = GetTestConfig(ssl);
  558. if (config->decline_alpn) {
  559. return SSL_TLSEXT_ERR_NOACK;
  560. }
  561. if (!config->expect_advertised_alpn.empty() &&
  562. (config->expect_advertised_alpn.size() != inlen ||
  563. OPENSSL_memcmp(config->expect_advertised_alpn.data(), in, inlen) !=
  564. 0)) {
  565. fprintf(stderr, "bad ALPN select callback inputs.\n");
  566. exit(1);
  567. }
  568. assert(config->select_alpn.empty() || !config->select_empty_alpn);
  569. *out = (const uint8_t *)config->select_alpn.data();
  570. *outlen = config->select_alpn.size();
  571. return SSL_TLSEXT_ERR_OK;
  572. }
  573. static bool CheckVerifyCallback(SSL *ssl) {
  574. const TestConfig *config = GetTestConfig(ssl);
  575. if (!config->expect_ocsp_response.empty()) {
  576. const uint8_t *data;
  577. size_t len;
  578. SSL_get0_ocsp_response(ssl, &data, &len);
  579. if (len == 0) {
  580. fprintf(stderr, "OCSP response not available in verify callback.\n");
  581. return false;
  582. }
  583. }
  584. if (GetTestState(ssl)->cert_verified) {
  585. fprintf(stderr, "Certificate verified twice.\n");
  586. return false;
  587. }
  588. return true;
  589. }
  590. static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
  591. SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(
  592. store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  593. const TestConfig *config = GetTestConfig(ssl);
  594. if (!CheckVerifyCallback(ssl)) {
  595. return 0;
  596. }
  597. GetTestState(ssl)->cert_verified = true;
  598. if (config->verify_fail) {
  599. store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
  600. return 0;
  601. }
  602. return 1;
  603. }
  604. bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
  605. bssl::UniquePtr<STACK_OF(X509)> *out_chain,
  606. const std::string &file) {
  607. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  608. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  609. return false;
  610. }
  611. out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
  612. if (!*out_x509) {
  613. return false;
  614. }
  615. out_chain->reset(sk_X509_new_null());
  616. if (!*out_chain) {
  617. return false;
  618. }
  619. // Keep reading the certificate chain.
  620. for (;;) {
  621. bssl::UniquePtr<X509> cert(
  622. PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
  623. if (!cert) {
  624. break;
  625. }
  626. if (!bssl::PushToStack(out_chain->get(), std::move(cert))) {
  627. return false;
  628. }
  629. }
  630. uint32_t err = ERR_peek_last_error();
  631. if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
  632. ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
  633. return false;
  634. }
  635. ERR_clear_error();
  636. return true;
  637. }
  638. bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
  639. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  640. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  641. return nullptr;
  642. }
  643. return bssl::UniquePtr<EVP_PKEY>(
  644. PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
  645. }
  646. static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
  647. bssl::UniquePtr<STACK_OF(X509)> *out_chain,
  648. bssl::UniquePtr<EVP_PKEY> *out_pkey) {
  649. const TestConfig *config = GetTestConfig(ssl);
  650. if (!config->signing_prefs.empty()) {
  651. std::vector<uint16_t> u16s(config->signing_prefs.begin(),
  652. config->signing_prefs.end());
  653. if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
  654. return false;
  655. }
  656. }
  657. if (!config->key_file.empty()) {
  658. *out_pkey = LoadPrivateKey(config->key_file.c_str());
  659. if (!*out_pkey) {
  660. return false;
  661. }
  662. }
  663. if (!config->cert_file.empty() &&
  664. !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
  665. return false;
  666. }
  667. if (!config->ocsp_response.empty() && !config->set_ocsp_in_callback &&
  668. !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
  669. config->ocsp_response.size())) {
  670. return false;
  671. }
  672. return true;
  673. }
  674. static bool FromHexDigit(uint8_t *out, char c) {
  675. if ('0' <= c && c <= '9') {
  676. *out = c - '0';
  677. return true;
  678. }
  679. if ('a' <= c && c <= 'f') {
  680. *out = c - 'a' + 10;
  681. return true;
  682. }
  683. if ('A' <= c && c <= 'F') {
  684. *out = c - 'A' + 10;
  685. return true;
  686. }
  687. return false;
  688. }
  689. static bool HexDecode(std::string *out, const std::string &in) {
  690. if ((in.size() & 1) != 0) {
  691. return false;
  692. }
  693. std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
  694. for (size_t i = 0; i < in.size() / 2; i++) {
  695. uint8_t high, low;
  696. if (!FromHexDigit(&high, in[i * 2]) || !FromHexDigit(&low, in[i * 2 + 1])) {
  697. return false;
  698. }
  699. buf[i] = (high << 4) | low;
  700. }
  701. out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
  702. return true;
  703. }
  704. static std::vector<std::string> SplitParts(const std::string &in,
  705. const char delim) {
  706. std::vector<std::string> ret;
  707. size_t start = 0;
  708. for (size_t i = 0; i < in.size(); i++) {
  709. if (in[i] == delim) {
  710. ret.push_back(in.substr(start, i - start));
  711. start = i + 1;
  712. }
  713. }
  714. ret.push_back(in.substr(start, std::string::npos));
  715. return ret;
  716. }
  717. static std::vector<std::string> DecodeHexStrings(
  718. const std::string &hex_strings) {
  719. std::vector<std::string> ret;
  720. const std::vector<std::string> parts = SplitParts(hex_strings, ',');
  721. for (const auto &part : parts) {
  722. std::string binary;
  723. if (!HexDecode(&binary, part)) {
  724. fprintf(stderr, "Bad hex string: %s.\n", part.c_str());
  725. return ret;
  726. }
  727. ret.push_back(binary);
  728. }
  729. return ret;
  730. }
  731. static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
  732. const std::string &hex_names) {
  733. const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
  734. bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
  735. if (!ret) {
  736. return nullptr;
  737. }
  738. for (const auto &der_name : der_names) {
  739. const uint8_t *const data =
  740. reinterpret_cast<const uint8_t *>(der_name.data());
  741. const uint8_t *derp = data;
  742. bssl::UniquePtr<X509_NAME> name(
  743. d2i_X509_NAME(nullptr, &derp, der_name.size()));
  744. if (!name || derp != data + der_name.size()) {
  745. fprintf(stderr, "Failed to parse X509_NAME.\n");
  746. return nullptr;
  747. }
  748. if (!bssl::PushToStack(ret.get(), std::move(name))) {
  749. return nullptr;
  750. }
  751. }
  752. return ret;
  753. }
  754. static bool CheckPeerVerifyPrefs(SSL *ssl) {
  755. const TestConfig *config = GetTestConfig(ssl);
  756. if (!config->expect_peer_verify_prefs.empty()) {
  757. const uint16_t *peer_sigalgs;
  758. size_t num_peer_sigalgs =
  759. SSL_get0_peer_verify_algorithms(ssl, &peer_sigalgs);
  760. if (config->expect_peer_verify_prefs.size() != num_peer_sigalgs) {
  761. fprintf(stderr,
  762. "peer verify preferences length mismatch (got %zu, wanted %zu)\n",
  763. num_peer_sigalgs, config->expect_peer_verify_prefs.size());
  764. return false;
  765. }
  766. for (size_t i = 0; i < num_peer_sigalgs; i++) {
  767. if (static_cast<int>(peer_sigalgs[i]) !=
  768. config->expect_peer_verify_prefs[i]) {
  769. fprintf(stderr,
  770. "peer verify preference %zu mismatch (got %04x, wanted %04x\n",
  771. i, peer_sigalgs[i], config->expect_peer_verify_prefs[i]);
  772. return false;
  773. }
  774. }
  775. }
  776. return true;
  777. }
  778. static bool CheckCertificateRequest(SSL *ssl) {
  779. const TestConfig *config = GetTestConfig(ssl);
  780. if (!CheckPeerVerifyPrefs(ssl)) {
  781. return false;
  782. }
  783. if (!config->expect_certificate_types.empty()) {
  784. const uint8_t *certificate_types;
  785. size_t certificate_types_len =
  786. SSL_get0_certificate_types(ssl, &certificate_types);
  787. if (certificate_types_len != config->expect_certificate_types.size() ||
  788. OPENSSL_memcmp(certificate_types,
  789. config->expect_certificate_types.data(),
  790. certificate_types_len) != 0) {
  791. fprintf(stderr, "certificate types mismatch.\n");
  792. return false;
  793. }
  794. }
  795. if (!config->expect_client_ca_list.empty()) {
  796. bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
  797. DecodeHexX509Names(config->expect_client_ca_list);
  798. const size_t num_expected = sk_X509_NAME_num(expected.get());
  799. const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
  800. const size_t num_received = sk_X509_NAME_num(received);
  801. if (num_received != num_expected) {
  802. fprintf(stderr, "expected %u names in CertificateRequest but got %u.\n",
  803. static_cast<unsigned>(num_expected),
  804. static_cast<unsigned>(num_received));
  805. return false;
  806. }
  807. for (size_t i = 0; i < num_received; i++) {
  808. if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
  809. sk_X509_NAME_value(expected.get(), i)) != 0) {
  810. fprintf(stderr, "names in CertificateRequest differ at index #%d.\n",
  811. static_cast<unsigned>(i));
  812. return false;
  813. }
  814. }
  815. const STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
  816. if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
  817. fprintf(stderr,
  818. "Mismatch between SSL_get_server_requested_CAs and "
  819. "SSL_get_client_CA_list.\n");
  820. return false;
  821. }
  822. }
  823. return true;
  824. }
  825. static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
  826. if (!CheckCertificateRequest(ssl)) {
  827. return -1;
  828. }
  829. if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
  830. return -1;
  831. }
  832. bssl::UniquePtr<X509> x509;
  833. bssl::UniquePtr<STACK_OF(X509)> chain;
  834. bssl::UniquePtr<EVP_PKEY> pkey;
  835. if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
  836. return -1;
  837. }
  838. // Return zero for no certificate.
  839. if (!x509) {
  840. return 0;
  841. }
  842. // Chains and asynchronous private keys are not supported with client_cert_cb.
  843. *out_x509 = x509.release();
  844. *out_pkey = pkey.release();
  845. return 1;
  846. }
  847. static ssl_private_key_result_t AsyncPrivateKeySign(
  848. SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
  849. uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
  850. TestState *test_state = GetTestState(ssl);
  851. if (!test_state->private_key_result.empty()) {
  852. fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
  853. abort();
  854. }
  855. if (EVP_PKEY_id(test_state->private_key.get()) !=
  856. SSL_get_signature_algorithm_key_type(signature_algorithm)) {
  857. fprintf(stderr, "Key type does not match signature algorithm.\n");
  858. abort();
  859. }
  860. // Determine the hash.
  861. const EVP_MD *md = SSL_get_signature_algorithm_digest(signature_algorithm);
  862. bssl::ScopedEVP_MD_CTX ctx;
  863. EVP_PKEY_CTX *pctx;
  864. if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
  865. test_state->private_key.get())) {
  866. return ssl_private_key_failure;
  867. }
  868. // Configure additional signature parameters.
  869. if (SSL_is_signature_algorithm_rsa_pss(signature_algorithm)) {
  870. if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
  871. !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1 /* salt len = hash len */)) {
  872. return ssl_private_key_failure;
  873. }
  874. }
  875. // Write the signature into |test_state|.
  876. size_t len = 0;
  877. if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
  878. return ssl_private_key_failure;
  879. }
  880. test_state->private_key_result.resize(len);
  881. if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
  882. in, in_len)) {
  883. return ssl_private_key_failure;
  884. }
  885. test_state->private_key_result.resize(len);
  886. // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
  887. return ssl_private_key_retry;
  888. }
  889. static ssl_private_key_result_t AsyncPrivateKeyDecrypt(SSL *ssl, uint8_t *out,
  890. size_t *out_len,
  891. size_t max_out,
  892. const uint8_t *in,
  893. size_t in_len) {
  894. TestState *test_state = GetTestState(ssl);
  895. if (!test_state->private_key_result.empty()) {
  896. fprintf(stderr, "AsyncPrivateKeyDecrypt called with operation pending.\n");
  897. abort();
  898. }
  899. RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
  900. if (rsa == NULL) {
  901. fprintf(stderr, "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
  902. abort();
  903. }
  904. test_state->private_key_result.resize(RSA_size(rsa));
  905. if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
  906. RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
  907. return ssl_private_key_failure;
  908. }
  909. test_state->private_key_result.resize(*out_len);
  910. // The decryption will be released asynchronously in |AsyncPrivateComplete|.
  911. return ssl_private_key_retry;
  912. }
  913. static ssl_private_key_result_t AsyncPrivateKeyComplete(SSL *ssl, uint8_t *out,
  914. size_t *out_len,
  915. size_t max_out) {
  916. TestState *test_state = GetTestState(ssl);
  917. if (test_state->private_key_result.empty()) {
  918. fprintf(stderr,
  919. "AsyncPrivateKeyComplete called without operation pending.\n");
  920. abort();
  921. }
  922. if (test_state->private_key_retries < 2) {
  923. // Only return the decryption on the second attempt, to test both incomplete
  924. // |decrypt| and |decrypt_complete|.
  925. return ssl_private_key_retry;
  926. }
  927. if (max_out < test_state->private_key_result.size()) {
  928. fprintf(stderr, "Output buffer too small.\n");
  929. return ssl_private_key_failure;
  930. }
  931. OPENSSL_memcpy(out, test_state->private_key_result.data(),
  932. test_state->private_key_result.size());
  933. *out_len = test_state->private_key_result.size();
  934. test_state->private_key_result.clear();
  935. test_state->private_key_retries = 0;
  936. return ssl_private_key_success;
  937. }
  938. static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
  939. AsyncPrivateKeySign,
  940. AsyncPrivateKeyDecrypt,
  941. AsyncPrivateKeyComplete,
  942. };
  943. static bool InstallCertificate(SSL *ssl) {
  944. bssl::UniquePtr<X509> x509;
  945. bssl::UniquePtr<STACK_OF(X509)> chain;
  946. bssl::UniquePtr<EVP_PKEY> pkey;
  947. if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
  948. return false;
  949. }
  950. if (pkey) {
  951. TestState *test_state = GetTestState(ssl);
  952. const TestConfig *config = GetTestConfig(ssl);
  953. if (config->async) {
  954. test_state->private_key = std::move(pkey);
  955. SSL_set_private_key_method(ssl, &g_async_private_key_method);
  956. } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
  957. return false;
  958. }
  959. }
  960. if (x509 && !SSL_use_certificate(ssl, x509.get())) {
  961. return false;
  962. }
  963. if (sk_X509_num(chain.get()) > 0 && !SSL_set1_chain(ssl, chain.get())) {
  964. return false;
  965. }
  966. return true;
  967. }
  968. static enum ssl_select_cert_result_t SelectCertificateCallback(
  969. const SSL_CLIENT_HELLO *client_hello) {
  970. const TestConfig *config = GetTestConfig(client_hello->ssl);
  971. GetTestState(client_hello->ssl)->early_callback_called = true;
  972. if (!config->expect_server_name.empty()) {
  973. const char *server_name =
  974. SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name);
  975. if (server_name == nullptr ||
  976. std::string(server_name) != config->expect_server_name) {
  977. fprintf(stderr,
  978. "Server name mismatch in early callback (got %s; want %s).\n",
  979. server_name, config->expect_server_name.c_str());
  980. return ssl_select_cert_error;
  981. }
  982. }
  983. if (config->fail_early_callback) {
  984. return ssl_select_cert_error;
  985. }
  986. // Install the certificate in the early callback.
  987. if (config->use_early_callback) {
  988. bool early_callback_ready =
  989. GetTestState(client_hello->ssl)->early_callback_ready;
  990. if (config->async && !early_callback_ready) {
  991. // Install the certificate asynchronously.
  992. return ssl_select_cert_retry;
  993. }
  994. if (!InstallCertificate(client_hello->ssl)) {
  995. return ssl_select_cert_error;
  996. }
  997. }
  998. return ssl_select_cert_success;
  999. }
  1000. bssl::UniquePtr<SSL_CTX> TestConfig::SetupCtx(SSL_CTX *old_ctx) const {
  1001. bssl::UniquePtr<SSL_CTX> ssl_ctx(
  1002. SSL_CTX_new(is_dtls ? DTLS_method() : TLS_method()));
  1003. if (!ssl_ctx) {
  1004. return nullptr;
  1005. }
  1006. CRYPTO_once(&once, init_once);
  1007. SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
  1008. // Enable TLS 1.3 for tests.
  1009. if (!is_dtls &&
  1010. !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
  1011. return nullptr;
  1012. }
  1013. std::string cipher_list = "ALL";
  1014. if (!cipher.empty()) {
  1015. cipher_list = cipher;
  1016. SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
  1017. }
  1018. if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
  1019. return nullptr;
  1020. }
  1021. if (async && is_server) {
  1022. // Disable the internal session cache. To test asynchronous session lookup,
  1023. // we use an external session cache.
  1024. SSL_CTX_set_session_cache_mode(
  1025. ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
  1026. SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
  1027. } else {
  1028. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  1029. }
  1030. SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
  1031. if (use_old_client_cert_callback) {
  1032. SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
  1033. }
  1034. SSL_CTX_set_next_protos_advertised_cb(ssl_ctx.get(),
  1035. NextProtosAdvertisedCallback, NULL);
  1036. if (!select_next_proto.empty()) {
  1037. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  1038. NULL);
  1039. }
  1040. if (!select_alpn.empty() || decline_alpn || select_empty_alpn) {
  1041. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  1042. }
  1043. SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
  1044. SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
  1045. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  1046. SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
  1047. if (use_ticket_callback) {
  1048. SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
  1049. }
  1050. if (!use_custom_verify_callback) {
  1051. SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL);
  1052. }
  1053. if (!signed_cert_timestamps.empty() &&
  1054. !SSL_CTX_set_signed_cert_timestamp_list(
  1055. ssl_ctx.get(), (const uint8_t *)signed_cert_timestamps.data(),
  1056. signed_cert_timestamps.size())) {
  1057. return nullptr;
  1058. }
  1059. if (!use_client_ca_list.empty()) {
  1060. if (use_client_ca_list == "<NULL>") {
  1061. SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
  1062. } else if (use_client_ca_list == "<EMPTY>") {
  1063. bssl::UniquePtr<STACK_OF(X509_NAME)> names;
  1064. SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
  1065. } else {
  1066. bssl::UniquePtr<STACK_OF(X509_NAME)> names =
  1067. DecodeHexX509Names(use_client_ca_list);
  1068. SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
  1069. }
  1070. }
  1071. if (enable_grease) {
  1072. SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
  1073. }
  1074. if (!expect_server_name.empty()) {
  1075. SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
  1076. }
  1077. if (enable_early_data) {
  1078. SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
  1079. }
  1080. if (allow_unknown_alpn_protos) {
  1081. SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
  1082. }
  1083. if (enable_ed25519) {
  1084. SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
  1085. }
  1086. if (no_rsa_pss_rsae_certs) {
  1087. SSL_CTX_set_rsa_pss_rsae_certs_enabled(ssl_ctx.get(), 0);
  1088. }
  1089. if (!verify_prefs.empty()) {
  1090. std::vector<uint16_t> u16s(verify_prefs.begin(), verify_prefs.end());
  1091. if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
  1092. u16s.size())) {
  1093. return nullptr;
  1094. }
  1095. }
  1096. SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback);
  1097. if (allow_false_start_without_alpn) {
  1098. SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1);
  1099. }
  1100. if (ignore_tls13_downgrade) {
  1101. SSL_CTX_set_ignore_tls13_downgrade(ssl_ctx.get(), 1);
  1102. }
  1103. if (use_ocsp_callback) {
  1104. SSL_CTX_set_tlsext_status_cb(ssl_ctx.get(), LegacyOCSPCallback);
  1105. }
  1106. if (old_ctx) {
  1107. uint8_t keys[48];
  1108. if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
  1109. !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
  1110. return nullptr;
  1111. }
  1112. CopySessions(ssl_ctx.get(), old_ctx);
  1113. } else if (!ticket_key.empty() &&
  1114. !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), ticket_key.data(),
  1115. ticket_key.size())) {
  1116. return nullptr;
  1117. }
  1118. if (install_cert_compression_algs &&
  1119. (!SSL_CTX_add_cert_compression_alg(
  1120. ssl_ctx.get(), 0xff02,
  1121. [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int {
  1122. if (!CBB_add_u8(out, 1) || !CBB_add_u8(out, 2) ||
  1123. !CBB_add_u8(out, 3) || !CBB_add_u8(out, 4) ||
  1124. !CBB_add_bytes(out, in, in_len)) {
  1125. return 0;
  1126. }
  1127. return 1;
  1128. },
  1129. [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
  1130. const uint8_t *in, size_t in_len) -> int {
  1131. if (in_len < 4 || in[0] != 1 || in[1] != 2 || in[2] != 3 ||
  1132. in[3] != 4 || uncompressed_len != in_len - 4) {
  1133. return 0;
  1134. }
  1135. const bssl::Span<const uint8_t> uncompressed(in + 4, in_len - 4);
  1136. *out = CRYPTO_BUFFER_new(uncompressed.data(), uncompressed.size(),
  1137. nullptr);
  1138. return 1;
  1139. }) ||
  1140. !SSL_CTX_add_cert_compression_alg(
  1141. ssl_ctx.get(), 0xff01,
  1142. [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int {
  1143. if (in_len < 2 || in[0] != 0 || in[1] != 0) {
  1144. return 0;
  1145. }
  1146. return CBB_add_bytes(out, in + 2, in_len - 2);
  1147. },
  1148. [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
  1149. const uint8_t *in, size_t in_len) -> int {
  1150. if (uncompressed_len != 2 + in_len) {
  1151. return 0;
  1152. }
  1153. std::unique_ptr<uint8_t[]> buf(new uint8_t[2 + in_len]);
  1154. buf[0] = 0;
  1155. buf[1] = 0;
  1156. OPENSSL_memcpy(&buf[2], in, in_len);
  1157. *out = CRYPTO_BUFFER_new(buf.get(), 2 + in_len, nullptr);
  1158. return 1;
  1159. }))) {
  1160. fprintf(stderr, "SSL_CTX_add_cert_compression_alg failed.\n");
  1161. abort();
  1162. }
  1163. if (server_preference) {
  1164. SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
  1165. }
  1166. if (enable_pq_experiment_signal) {
  1167. SSL_CTX_enable_pq_experiment_signal(ssl_ctx.get());
  1168. }
  1169. return ssl_ctx;
  1170. }
  1171. static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
  1172. const TestConfig *config = GetTestConfig(client_hello->ssl);
  1173. return config->fail_ddos_callback ? 0 : 1;
  1174. }
  1175. static unsigned PskClientCallback(SSL *ssl, const char *hint,
  1176. char *out_identity, unsigned max_identity_len,
  1177. uint8_t *out_psk, unsigned max_psk_len) {
  1178. const TestConfig *config = GetTestConfig(ssl);
  1179. if (config->psk_identity.empty()) {
  1180. if (hint != nullptr) {
  1181. fprintf(stderr, "Server PSK hint was non-null.\n");
  1182. return 0;
  1183. }
  1184. } else if (hint == nullptr ||
  1185. strcmp(hint, config->psk_identity.c_str()) != 0) {
  1186. fprintf(stderr, "Server PSK hint did not match.\n");
  1187. return 0;
  1188. }
  1189. // Account for the trailing '\0' for the identity.
  1190. if (config->psk_identity.size() >= max_identity_len ||
  1191. config->psk.size() > max_psk_len) {
  1192. fprintf(stderr, "PSK buffers too small.\n");
  1193. return 0;
  1194. }
  1195. BUF_strlcpy(out_identity, config->psk_identity.c_str(), max_identity_len);
  1196. OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
  1197. return config->psk.size();
  1198. }
  1199. static unsigned PskServerCallback(SSL *ssl, const char *identity,
  1200. uint8_t *out_psk, unsigned max_psk_len) {
  1201. const TestConfig *config = GetTestConfig(ssl);
  1202. if (strcmp(identity, config->psk_identity.c_str()) != 0) {
  1203. fprintf(stderr, "Client PSK identity did not match.\n");
  1204. return 0;
  1205. }
  1206. if (config->psk.size() > max_psk_len) {
  1207. fprintf(stderr, "PSK buffers too small.\n");
  1208. return 0;
  1209. }
  1210. OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
  1211. return config->psk.size();
  1212. }
  1213. static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) {
  1214. const TestConfig *config = GetTestConfig(ssl);
  1215. if (!CheckVerifyCallback(ssl)) {
  1216. return ssl_verify_invalid;
  1217. }
  1218. if (config->async && !GetTestState(ssl)->custom_verify_ready) {
  1219. return ssl_verify_retry;
  1220. }
  1221. GetTestState(ssl)->cert_verified = true;
  1222. if (config->verify_fail) {
  1223. return ssl_verify_invalid;
  1224. }
  1225. return ssl_verify_ok;
  1226. }
  1227. static int CertCallback(SSL *ssl, void *arg) {
  1228. const TestConfig *config = GetTestConfig(ssl);
  1229. // Check the peer certificate metadata is as expected.
  1230. if ((!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) ||
  1231. !CheckPeerVerifyPrefs(ssl)) {
  1232. return -1;
  1233. }
  1234. if (config->fail_cert_callback) {
  1235. return 0;
  1236. }
  1237. // The certificate will be installed via other means.
  1238. if (!config->async || config->use_early_callback) {
  1239. return 1;
  1240. }
  1241. if (!GetTestState(ssl)->cert_ready) {
  1242. return -1;
  1243. }
  1244. if (!InstallCertificate(ssl)) {
  1245. return 0;
  1246. }
  1247. return 1;
  1248. }
  1249. bssl::UniquePtr<SSL> TestConfig::NewSSL(
  1250. SSL_CTX *ssl_ctx, SSL_SESSION *session, bool is_resume,
  1251. std::unique_ptr<TestState> test_state) const {
  1252. bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
  1253. if (!ssl) {
  1254. return nullptr;
  1255. }
  1256. if (!SetTestConfig(ssl.get(), this)) {
  1257. return nullptr;
  1258. }
  1259. if (test_state != nullptr) {
  1260. if (!SetTestState(ssl.get(), std::move(test_state))) {
  1261. return nullptr;
  1262. }
  1263. GetTestState(ssl.get())->is_resume = is_resume;
  1264. }
  1265. if (fallback_scsv && !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  1266. return nullptr;
  1267. }
  1268. // Install the certificate synchronously if nothing else will handle it.
  1269. if (!use_early_callback && !use_old_client_cert_callback && !async &&
  1270. !InstallCertificate(ssl.get())) {
  1271. return nullptr;
  1272. }
  1273. if (!use_old_client_cert_callback) {
  1274. SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
  1275. }
  1276. int mode = SSL_VERIFY_NONE;
  1277. if (require_any_client_certificate) {
  1278. mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  1279. }
  1280. if (verify_peer) {
  1281. mode = SSL_VERIFY_PEER;
  1282. }
  1283. if (verify_peer_if_no_obc) {
  1284. // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
  1285. // certificates were requested is easy.
  1286. mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
  1287. SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  1288. }
  1289. if (use_custom_verify_callback) {
  1290. SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback);
  1291. } else if (mode != SSL_VERIFY_NONE) {
  1292. SSL_set_verify(ssl.get(), mode, NULL);
  1293. }
  1294. if (false_start) {
  1295. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
  1296. }
  1297. if (cbc_record_splitting) {
  1298. SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
  1299. }
  1300. if (partial_write) {
  1301. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  1302. }
  1303. if (reverify_on_resume) {
  1304. SSL_CTX_set_reverify_on_resume(ssl_ctx, 1);
  1305. }
  1306. if (enforce_rsa_key_usage) {
  1307. SSL_set_enforce_rsa_key_usage(ssl.get(), 1);
  1308. }
  1309. if (no_tls13) {
  1310. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
  1311. }
  1312. if (no_tls12) {
  1313. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  1314. }
  1315. if (no_tls11) {
  1316. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  1317. }
  1318. if (no_tls1) {
  1319. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  1320. }
  1321. if (no_ticket) {
  1322. SSL_set_options(ssl.get(), SSL_OP_NO_TICKET);
  1323. }
  1324. if (!expect_channel_id.empty() || enable_channel_id) {
  1325. SSL_set_tls_channel_id_enabled(ssl.get(), 1);
  1326. }
  1327. if (!send_channel_id.empty()) {
  1328. SSL_set_tls_channel_id_enabled(ssl.get(), 1);
  1329. if (!async) {
  1330. // The async case will be supplied by |ChannelIdCallback|.
  1331. bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(send_channel_id);
  1332. if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
  1333. return nullptr;
  1334. }
  1335. }
  1336. }
  1337. if (!send_token_binding_params.empty()) {
  1338. SSL_set_token_binding_params(
  1339. ssl.get(),
  1340. reinterpret_cast<const uint8_t *>(send_token_binding_params.data()),
  1341. send_token_binding_params.length());
  1342. }
  1343. if (!host_name.empty() &&
  1344. !SSL_set_tlsext_host_name(ssl.get(), host_name.c_str())) {
  1345. return nullptr;
  1346. }
  1347. if (!advertise_alpn.empty() &&
  1348. SSL_set_alpn_protos(ssl.get(), (const uint8_t *)advertise_alpn.data(),
  1349. advertise_alpn.size()) != 0) {
  1350. return nullptr;
  1351. }
  1352. if (!psk.empty()) {
  1353. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  1354. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  1355. }
  1356. if (!psk_identity.empty() &&
  1357. !SSL_use_psk_identity_hint(ssl.get(), psk_identity.c_str())) {
  1358. return nullptr;
  1359. }
  1360. if (!srtp_profiles.empty() &&
  1361. !SSL_set_srtp_profiles(ssl.get(), srtp_profiles.c_str())) {
  1362. return nullptr;
  1363. }
  1364. if (enable_ocsp_stapling) {
  1365. SSL_enable_ocsp_stapling(ssl.get());
  1366. }
  1367. if (enable_signed_cert_timestamps) {
  1368. SSL_enable_signed_cert_timestamps(ssl.get());
  1369. }
  1370. if (min_version != 0 &&
  1371. !SSL_set_min_proto_version(ssl.get(), (uint16_t)min_version)) {
  1372. return nullptr;
  1373. }
  1374. if (max_version != 0 &&
  1375. !SSL_set_max_proto_version(ssl.get(), (uint16_t)max_version)) {
  1376. return nullptr;
  1377. }
  1378. if (mtu != 0) {
  1379. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  1380. SSL_set_mtu(ssl.get(), mtu);
  1381. }
  1382. if (install_ddos_callback) {
  1383. SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
  1384. }
  1385. SSL_set_shed_handshake_config(ssl.get(), true);
  1386. if (renegotiate_once) {
  1387. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
  1388. }
  1389. if (renegotiate_freely || forbid_renegotiation_after_handshake) {
  1390. // |forbid_renegotiation_after_handshake| will disable renegotiation later.
  1391. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
  1392. }
  1393. if (renegotiate_ignore) {
  1394. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
  1395. }
  1396. if (!check_close_notify) {
  1397. SSL_set_quiet_shutdown(ssl.get(), 1);
  1398. }
  1399. if (!curves.empty()) {
  1400. std::vector<int> nids;
  1401. for (auto curve : curves) {
  1402. switch (curve) {
  1403. case SSL_CURVE_SECP224R1:
  1404. nids.push_back(NID_secp224r1);
  1405. break;
  1406. case SSL_CURVE_SECP256R1:
  1407. nids.push_back(NID_X9_62_prime256v1);
  1408. break;
  1409. case SSL_CURVE_SECP384R1:
  1410. nids.push_back(NID_secp384r1);
  1411. break;
  1412. case SSL_CURVE_SECP521R1:
  1413. nids.push_back(NID_secp521r1);
  1414. break;
  1415. case SSL_CURVE_X25519:
  1416. nids.push_back(NID_X25519);
  1417. break;
  1418. case SSL_CURVE_CECPQ2:
  1419. nids.push_back(NID_CECPQ2);
  1420. break;
  1421. case SSL_CURVE_CECPQ2b:
  1422. nids.push_back(NID_CECPQ2b);
  1423. break;
  1424. }
  1425. if (!SSL_set1_curves(ssl.get(), &nids[0], nids.size())) {
  1426. return nullptr;
  1427. }
  1428. }
  1429. }
  1430. if (enable_all_curves) {
  1431. static const int kAllCurves[] = {
  1432. NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1,
  1433. NID_X25519, NID_CECPQ2, NID_CECPQ2b,
  1434. };
  1435. if (!SSL_set1_curves(ssl.get(), kAllCurves,
  1436. OPENSSL_ARRAY_SIZE(kAllCurves))) {
  1437. return nullptr;
  1438. }
  1439. }
  1440. if (initial_timeout_duration_ms > 0) {
  1441. DTLSv1_set_initial_timeout_duration(ssl.get(), initial_timeout_duration_ms);
  1442. }
  1443. if (max_cert_list > 0) {
  1444. SSL_set_max_cert_list(ssl.get(), max_cert_list);
  1445. }
  1446. if (retain_only_sha256_client_cert) {
  1447. SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
  1448. }
  1449. if (max_send_fragment > 0) {
  1450. SSL_set_max_send_fragment(ssl.get(), max_send_fragment);
  1451. }
  1452. if (!quic_transport_params.empty()) {
  1453. if (!SSL_set_quic_transport_params(
  1454. ssl.get(),
  1455. reinterpret_cast<const uint8_t *>(quic_transport_params.data()),
  1456. quic_transport_params.size())) {
  1457. return nullptr;
  1458. }
  1459. }
  1460. if (jdk11_workaround) {
  1461. SSL_set_jdk11_workaround(ssl.get(), 1);
  1462. }
  1463. if (session != NULL) {
  1464. if (!is_server) {
  1465. if (SSL_set_session(ssl.get(), session) != 1) {
  1466. return nullptr;
  1467. }
  1468. } else if (async) {
  1469. // The internal session cache is disabled, so install the session
  1470. // manually.
  1471. SSL_SESSION_up_ref(session);
  1472. GetTestState(ssl.get())->pending_session.reset(session);
  1473. }
  1474. }
  1475. if (!delegated_credential.empty()) {
  1476. std::string::size_type comma = delegated_credential.find(',');
  1477. if (comma == std::string::npos) {
  1478. fprintf(stderr,
  1479. "failed to find comma in delegated credential argument.\n");
  1480. return nullptr;
  1481. }
  1482. const std::string dc_hex = delegated_credential.substr(0, comma);
  1483. const std::string pkcs8_hex = delegated_credential.substr(comma + 1);
  1484. std::string dc, pkcs8;
  1485. if (!HexDecode(&dc, dc_hex) || !HexDecode(&pkcs8, pkcs8_hex)) {
  1486. fprintf(stderr, "failed to hex decode delegated credential argument.\n");
  1487. return nullptr;
  1488. }
  1489. CBS dc_cbs(bssl::Span<const uint8_t>(
  1490. reinterpret_cast<const uint8_t *>(dc.data()), dc.size()));
  1491. CBS pkcs8_cbs(bssl::Span<const uint8_t>(
  1492. reinterpret_cast<const uint8_t *>(pkcs8.data()), pkcs8.size()));
  1493. bssl::UniquePtr<EVP_PKEY> priv(EVP_parse_private_key(&pkcs8_cbs));
  1494. if (!priv) {
  1495. fprintf(stderr, "failed to parse delegated credential private key.\n");
  1496. return nullptr;
  1497. }
  1498. bssl::UniquePtr<CRYPTO_BUFFER> dc_buf(
  1499. CRYPTO_BUFFER_new_from_CBS(&dc_cbs, nullptr));
  1500. if (!SSL_set1_delegated_credential(ssl.get(), dc_buf.get(),
  1501. priv.get(), nullptr)) {
  1502. fprintf(stderr, "SSL_set1_delegated_credential failed.\n");
  1503. return nullptr;
  1504. }
  1505. }
  1506. return ssl;
  1507. }