s_cb.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. /*
  2. * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /* callback functions used by s_client, s_server, and s_time */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h> /* for memcpy() and strcmp() */
  13. #include "apps.h"
  14. #include <openssl/core_names.h>
  15. #include <openssl/params.h>
  16. #include <openssl/err.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/x509.h>
  19. #include <openssl/ssl.h>
  20. #include <openssl/bn.h>
  21. #ifndef OPENSSL_NO_DH
  22. # include <openssl/dh.h>
  23. #endif
  24. #include "s_apps.h"
  25. #define COOKIE_SECRET_LENGTH 16
  26. VERIFY_CB_ARGS verify_args = { -1, 0, X509_V_OK, 0 };
  27. #ifndef OPENSSL_NO_SOCK
  28. static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
  29. static int cookie_initialized = 0;
  30. #endif
  31. static BIO *bio_keylog = NULL;
  32. static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
  33. {
  34. for ( ; list->name; ++list)
  35. if (list->retval == val)
  36. return list->name;
  37. return def;
  38. }
  39. int verify_callback(int ok, X509_STORE_CTX *ctx)
  40. {
  41. X509 *err_cert;
  42. int err, depth;
  43. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  44. err = X509_STORE_CTX_get_error(ctx);
  45. depth = X509_STORE_CTX_get_error_depth(ctx);
  46. if (!verify_args.quiet || !ok) {
  47. BIO_printf(bio_err, "depth=%d ", depth);
  48. if (err_cert != NULL) {
  49. X509_NAME_print_ex(bio_err,
  50. X509_get_subject_name(err_cert),
  51. 0, get_nameopt());
  52. BIO_puts(bio_err, "\n");
  53. } else {
  54. BIO_puts(bio_err, "<no cert>\n");
  55. }
  56. }
  57. if (!ok) {
  58. BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
  59. X509_verify_cert_error_string(err));
  60. if (verify_args.depth < 0 || verify_args.depth >= depth) {
  61. if (!verify_args.return_error)
  62. ok = 1;
  63. verify_args.error = err;
  64. } else {
  65. ok = 0;
  66. verify_args.error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  67. }
  68. }
  69. switch (err) {
  70. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  71. if (err_cert != NULL) {
  72. BIO_puts(bio_err, "issuer= ");
  73. X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
  74. 0, get_nameopt());
  75. BIO_puts(bio_err, "\n");
  76. }
  77. break;
  78. case X509_V_ERR_CERT_NOT_YET_VALID:
  79. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  80. if (err_cert != NULL) {
  81. BIO_printf(bio_err, "notBefore=");
  82. ASN1_TIME_print(bio_err, X509_get0_notBefore(err_cert));
  83. BIO_printf(bio_err, "\n");
  84. }
  85. break;
  86. case X509_V_ERR_CERT_HAS_EXPIRED:
  87. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  88. if (err_cert != NULL) {
  89. BIO_printf(bio_err, "notAfter=");
  90. ASN1_TIME_print(bio_err, X509_get0_notAfter(err_cert));
  91. BIO_printf(bio_err, "\n");
  92. }
  93. break;
  94. case X509_V_ERR_NO_EXPLICIT_POLICY:
  95. if (!verify_args.quiet)
  96. policies_print(ctx);
  97. break;
  98. }
  99. if (err == X509_V_OK && ok == 2 && !verify_args.quiet)
  100. policies_print(ctx);
  101. if (ok && !verify_args.quiet)
  102. BIO_printf(bio_err, "verify return:%d\n", ok);
  103. return ok;
  104. }
  105. int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
  106. {
  107. if (cert_file != NULL) {
  108. if (SSL_CTX_use_certificate_file(ctx, cert_file,
  109. SSL_FILETYPE_PEM) <= 0) {
  110. BIO_printf(bio_err, "unable to get certificate from '%s'\n",
  111. cert_file);
  112. ERR_print_errors(bio_err);
  113. return 0;
  114. }
  115. if (key_file == NULL)
  116. key_file = cert_file;
  117. if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
  118. BIO_printf(bio_err, "unable to get private key from '%s'\n",
  119. key_file);
  120. ERR_print_errors(bio_err);
  121. return 0;
  122. }
  123. /*
  124. * If we are using DSA, we can copy the parameters from the private
  125. * key
  126. */
  127. /*
  128. * Now we know that a key and cert have been set against the SSL
  129. * context
  130. */
  131. if (!SSL_CTX_check_private_key(ctx)) {
  132. BIO_printf(bio_err,
  133. "Private key does not match the certificate public key\n");
  134. return 0;
  135. }
  136. }
  137. return 1;
  138. }
  139. int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
  140. STACK_OF(X509) *chain, int build_chain)
  141. {
  142. int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
  143. if (cert == NULL)
  144. return 1;
  145. if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
  146. BIO_printf(bio_err, "error setting certificate\n");
  147. ERR_print_errors(bio_err);
  148. return 0;
  149. }
  150. if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
  151. BIO_printf(bio_err, "error setting private key\n");
  152. ERR_print_errors(bio_err);
  153. return 0;
  154. }
  155. /*
  156. * Now we know that a key and cert have been set against the SSL context
  157. */
  158. if (!SSL_CTX_check_private_key(ctx)) {
  159. BIO_printf(bio_err,
  160. "Private key does not match the certificate public key\n");
  161. return 0;
  162. }
  163. if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
  164. BIO_printf(bio_err, "error setting certificate chain\n");
  165. ERR_print_errors(bio_err);
  166. return 0;
  167. }
  168. if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
  169. BIO_printf(bio_err, "error building certificate chain\n");
  170. ERR_print_errors(bio_err);
  171. return 0;
  172. }
  173. return 1;
  174. }
  175. static STRINT_PAIR cert_type_list[] = {
  176. {"RSA sign", TLS_CT_RSA_SIGN},
  177. {"DSA sign", TLS_CT_DSS_SIGN},
  178. {"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
  179. {"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
  180. {"ECDSA sign", TLS_CT_ECDSA_SIGN},
  181. {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
  182. {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
  183. {"GOST01 Sign", TLS_CT_GOST01_SIGN},
  184. {"GOST12 Sign", TLS_CT_GOST12_IANA_SIGN},
  185. {NULL}
  186. };
  187. static void ssl_print_client_cert_types(BIO *bio, SSL *s)
  188. {
  189. const unsigned char *p;
  190. int i;
  191. int cert_type_num = SSL_get0_certificate_types(s, &p);
  192. if (!cert_type_num)
  193. return;
  194. BIO_puts(bio, "Client Certificate Types: ");
  195. for (i = 0; i < cert_type_num; i++) {
  196. unsigned char cert_type = p[i];
  197. const char *cname = lookup((int)cert_type, cert_type_list, NULL);
  198. if (i)
  199. BIO_puts(bio, ", ");
  200. if (cname != NULL)
  201. BIO_puts(bio, cname);
  202. else
  203. BIO_printf(bio, "UNKNOWN (%d),", cert_type);
  204. }
  205. BIO_puts(bio, "\n");
  206. }
  207. static const char *get_sigtype(int nid)
  208. {
  209. switch (nid) {
  210. case EVP_PKEY_RSA:
  211. return "RSA";
  212. case EVP_PKEY_RSA_PSS:
  213. return "RSA-PSS";
  214. case EVP_PKEY_DSA:
  215. return "DSA";
  216. case EVP_PKEY_EC:
  217. return "ECDSA";
  218. case NID_ED25519:
  219. return "Ed25519";
  220. case NID_ED448:
  221. return "Ed448";
  222. case NID_id_GostR3410_2001:
  223. return "gost2001";
  224. case NID_id_GostR3410_2012_256:
  225. return "gost2012_256";
  226. case NID_id_GostR3410_2012_512:
  227. return "gost2012_512";
  228. default:
  229. return NULL;
  230. }
  231. }
  232. static int do_print_sigalgs(BIO *out, SSL *s, int shared)
  233. {
  234. int i, nsig, client;
  235. client = SSL_is_server(s) ? 0 : 1;
  236. if (shared)
  237. nsig = SSL_get_shared_sigalgs(s, 0, NULL, NULL, NULL, NULL, NULL);
  238. else
  239. nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
  240. if (nsig == 0)
  241. return 1;
  242. if (shared)
  243. BIO_puts(out, "Shared ");
  244. if (client)
  245. BIO_puts(out, "Requested ");
  246. BIO_puts(out, "Signature Algorithms: ");
  247. for (i = 0; i < nsig; i++) {
  248. int hash_nid, sign_nid;
  249. unsigned char rhash, rsign;
  250. const char *sstr = NULL;
  251. if (shared)
  252. SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
  253. &rsign, &rhash);
  254. else
  255. SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
  256. if (i)
  257. BIO_puts(out, ":");
  258. sstr = get_sigtype(sign_nid);
  259. if (sstr)
  260. BIO_printf(out, "%s", sstr);
  261. else
  262. BIO_printf(out, "0x%02X", (int)rsign);
  263. if (hash_nid != NID_undef)
  264. BIO_printf(out, "+%s", OBJ_nid2sn(hash_nid));
  265. else if (sstr == NULL)
  266. BIO_printf(out, "+0x%02X", (int)rhash);
  267. }
  268. BIO_puts(out, "\n");
  269. return 1;
  270. }
  271. int ssl_print_sigalgs(BIO *out, SSL *s)
  272. {
  273. int nid;
  274. if (!SSL_is_server(s))
  275. ssl_print_client_cert_types(out, s);
  276. do_print_sigalgs(out, s, 0);
  277. do_print_sigalgs(out, s, 1);
  278. if (SSL_get_peer_signature_nid(s, &nid) && nid != NID_undef)
  279. BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(nid));
  280. if (SSL_get_peer_signature_type_nid(s, &nid))
  281. BIO_printf(out, "Peer signature type: %s\n", get_sigtype(nid));
  282. return 1;
  283. }
  284. #ifndef OPENSSL_NO_EC
  285. int ssl_print_point_formats(BIO *out, SSL *s)
  286. {
  287. int i, nformats;
  288. const char *pformats;
  289. nformats = SSL_get0_ec_point_formats(s, &pformats);
  290. if (nformats <= 0)
  291. return 1;
  292. BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
  293. for (i = 0; i < nformats; i++, pformats++) {
  294. if (i)
  295. BIO_puts(out, ":");
  296. switch (*pformats) {
  297. case TLSEXT_ECPOINTFORMAT_uncompressed:
  298. BIO_puts(out, "uncompressed");
  299. break;
  300. case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
  301. BIO_puts(out, "ansiX962_compressed_prime");
  302. break;
  303. case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
  304. BIO_puts(out, "ansiX962_compressed_char2");
  305. break;
  306. default:
  307. BIO_printf(out, "unknown(%d)", (int)*pformats);
  308. break;
  309. }
  310. }
  311. BIO_puts(out, "\n");
  312. return 1;
  313. }
  314. int ssl_print_groups(BIO *out, SSL *s, int noshared)
  315. {
  316. int i, ngroups, *groups, nid;
  317. ngroups = SSL_get1_groups(s, NULL);
  318. if (ngroups <= 0)
  319. return 1;
  320. groups = app_malloc(ngroups * sizeof(int), "groups to print");
  321. SSL_get1_groups(s, groups);
  322. BIO_puts(out, "Supported groups: ");
  323. for (i = 0; i < ngroups; i++) {
  324. if (i)
  325. BIO_puts(out, ":");
  326. nid = groups[i];
  327. BIO_printf(out, "%s", SSL_group_to_name(s, nid));
  328. }
  329. OPENSSL_free(groups);
  330. if (noshared) {
  331. BIO_puts(out, "\n");
  332. return 1;
  333. }
  334. BIO_puts(out, "\nShared groups: ");
  335. ngroups = SSL_get_shared_group(s, -1);
  336. for (i = 0; i < ngroups; i++) {
  337. if (i)
  338. BIO_puts(out, ":");
  339. nid = SSL_get_shared_group(s, i);
  340. BIO_printf(out, "%s", SSL_group_to_name(s, nid));
  341. }
  342. if (ngroups == 0)
  343. BIO_puts(out, "NONE");
  344. BIO_puts(out, "\n");
  345. return 1;
  346. }
  347. #endif
  348. int ssl_print_tmp_key(BIO *out, SSL *s)
  349. {
  350. EVP_PKEY *key;
  351. if (!SSL_get_peer_tmp_key(s, &key))
  352. return 1;
  353. BIO_puts(out, "Server Temp Key: ");
  354. switch (EVP_PKEY_get_id(key)) {
  355. case EVP_PKEY_RSA:
  356. BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_get_bits(key));
  357. break;
  358. case EVP_PKEY_DH:
  359. BIO_printf(out, "DH, %d bits\n", EVP_PKEY_get_bits(key));
  360. break;
  361. #ifndef OPENSSL_NO_EC
  362. case EVP_PKEY_EC:
  363. {
  364. char name[80];
  365. size_t name_len;
  366. if (!EVP_PKEY_get_utf8_string_param(key, OSSL_PKEY_PARAM_GROUP_NAME,
  367. name, sizeof(name), &name_len))
  368. strcpy(name, "?");
  369. BIO_printf(out, "ECDH, %s, %d bits\n", name, EVP_PKEY_get_bits(key));
  370. }
  371. break;
  372. #endif
  373. default:
  374. BIO_printf(out, "%s, %d bits\n", OBJ_nid2sn(EVP_PKEY_get_id(key)),
  375. EVP_PKEY_get_bits(key));
  376. }
  377. EVP_PKEY_free(key);
  378. return 1;
  379. }
  380. long bio_dump_callback(BIO *bio, int cmd, const char *argp, size_t len,
  381. int argi, long argl, int ret, size_t *processed)
  382. {
  383. BIO *out;
  384. out = (BIO *)BIO_get_callback_arg(bio);
  385. if (out == NULL)
  386. return ret;
  387. if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
  388. if (ret > 0 && processed != NULL) {
  389. BIO_printf(out, "read from %p [%p] (%zu bytes => %zu (0x%zX))\n",
  390. (void *)bio, (void *)argp, len, *processed, *processed);
  391. BIO_dump(out, argp, (int)*processed);
  392. } else {
  393. BIO_printf(out, "read from %p [%p] (%zu bytes => %d)\n",
  394. (void *)bio, (void *)argp, len, ret);
  395. }
  396. } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
  397. if (ret > 0 && processed != NULL) {
  398. BIO_printf(out, "write to %p [%p] (%zu bytes => %zu (0x%zX))\n",
  399. (void *)bio, (void *)argp, len, *processed, *processed);
  400. BIO_dump(out, argp, (int)*processed);
  401. } else {
  402. BIO_printf(out, "write to %p [%p] (%zu bytes => %d)\n",
  403. (void *)bio, (void *)argp, len, ret);
  404. }
  405. }
  406. return ret;
  407. }
  408. void apps_ssl_info_callback(const SSL *s, int where, int ret)
  409. {
  410. const char *str;
  411. int w;
  412. w = where & ~SSL_ST_MASK;
  413. if (w & SSL_ST_CONNECT)
  414. str = "SSL_connect";
  415. else if (w & SSL_ST_ACCEPT)
  416. str = "SSL_accept";
  417. else
  418. str = "undefined";
  419. if (where & SSL_CB_LOOP) {
  420. BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
  421. } else if (where & SSL_CB_ALERT) {
  422. str = (where & SSL_CB_READ) ? "read" : "write";
  423. BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
  424. str,
  425. SSL_alert_type_string_long(ret),
  426. SSL_alert_desc_string_long(ret));
  427. } else if (where & SSL_CB_EXIT) {
  428. if (ret == 0)
  429. BIO_printf(bio_err, "%s:failed in %s\n",
  430. str, SSL_state_string_long(s));
  431. else if (ret < 0)
  432. BIO_printf(bio_err, "%s:error in %s\n",
  433. str, SSL_state_string_long(s));
  434. }
  435. }
  436. static STRINT_PAIR ssl_versions[] = {
  437. {"SSL 3.0", SSL3_VERSION},
  438. {"TLS 1.0", TLS1_VERSION},
  439. {"TLS 1.1", TLS1_1_VERSION},
  440. {"TLS 1.2", TLS1_2_VERSION},
  441. {"TLS 1.3", TLS1_3_VERSION},
  442. {"DTLS 1.0", DTLS1_VERSION},
  443. {"DTLS 1.0 (bad)", DTLS1_BAD_VER},
  444. {NULL}
  445. };
  446. static STRINT_PAIR alert_types[] = {
  447. {" close_notify", 0},
  448. {" end_of_early_data", 1},
  449. {" unexpected_message", 10},
  450. {" bad_record_mac", 20},
  451. {" decryption_failed", 21},
  452. {" record_overflow", 22},
  453. {" decompression_failure", 30},
  454. {" handshake_failure", 40},
  455. {" bad_certificate", 42},
  456. {" unsupported_certificate", 43},
  457. {" certificate_revoked", 44},
  458. {" certificate_expired", 45},
  459. {" certificate_unknown", 46},
  460. {" illegal_parameter", 47},
  461. {" unknown_ca", 48},
  462. {" access_denied", 49},
  463. {" decode_error", 50},
  464. {" decrypt_error", 51},
  465. {" export_restriction", 60},
  466. {" protocol_version", 70},
  467. {" insufficient_security", 71},
  468. {" internal_error", 80},
  469. {" inappropriate_fallback", 86},
  470. {" user_canceled", 90},
  471. {" no_renegotiation", 100},
  472. {" missing_extension", 109},
  473. {" unsupported_extension", 110},
  474. {" certificate_unobtainable", 111},
  475. {" unrecognized_name", 112},
  476. {" bad_certificate_status_response", 113},
  477. {" bad_certificate_hash_value", 114},
  478. {" unknown_psk_identity", 115},
  479. {" certificate_required", 116},
  480. {NULL}
  481. };
  482. static STRINT_PAIR handshakes[] = {
  483. {", HelloRequest", SSL3_MT_HELLO_REQUEST},
  484. {", ClientHello", SSL3_MT_CLIENT_HELLO},
  485. {", ServerHello", SSL3_MT_SERVER_HELLO},
  486. {", HelloVerifyRequest", DTLS1_MT_HELLO_VERIFY_REQUEST},
  487. {", NewSessionTicket", SSL3_MT_NEWSESSION_TICKET},
  488. {", EndOfEarlyData", SSL3_MT_END_OF_EARLY_DATA},
  489. {", EncryptedExtensions", SSL3_MT_ENCRYPTED_EXTENSIONS},
  490. {", Certificate", SSL3_MT_CERTIFICATE},
  491. {", ServerKeyExchange", SSL3_MT_SERVER_KEY_EXCHANGE},
  492. {", CertificateRequest", SSL3_MT_CERTIFICATE_REQUEST},
  493. {", ServerHelloDone", SSL3_MT_SERVER_DONE},
  494. {", CertificateVerify", SSL3_MT_CERTIFICATE_VERIFY},
  495. {", ClientKeyExchange", SSL3_MT_CLIENT_KEY_EXCHANGE},
  496. {", Finished", SSL3_MT_FINISHED},
  497. {", CertificateUrl", SSL3_MT_CERTIFICATE_URL},
  498. {", CertificateStatus", SSL3_MT_CERTIFICATE_STATUS},
  499. {", SupplementalData", SSL3_MT_SUPPLEMENTAL_DATA},
  500. {", KeyUpdate", SSL3_MT_KEY_UPDATE},
  501. #ifndef OPENSSL_NO_NEXTPROTONEG
  502. {", NextProto", SSL3_MT_NEXT_PROTO},
  503. #endif
  504. {", MessageHash", SSL3_MT_MESSAGE_HASH},
  505. {NULL}
  506. };
  507. void msg_cb(int write_p, int version, int content_type, const void *buf,
  508. size_t len, SSL *ssl, void *arg)
  509. {
  510. BIO *bio = arg;
  511. const char *str_write_p = write_p ? ">>>" : "<<<";
  512. char tmpbuf[128];
  513. const char *str_version, *str_content_type = "", *str_details1 = "", *str_details2 = "";
  514. const unsigned char* bp = buf;
  515. if (version == SSL3_VERSION ||
  516. version == TLS1_VERSION ||
  517. version == TLS1_1_VERSION ||
  518. version == TLS1_2_VERSION ||
  519. version == TLS1_3_VERSION ||
  520. version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
  521. str_version = lookup(version, ssl_versions, "???");
  522. switch (content_type) {
  523. case SSL3_RT_CHANGE_CIPHER_SPEC:
  524. /* type 20 */
  525. str_content_type = ", ChangeCipherSpec";
  526. break;
  527. case SSL3_RT_ALERT:
  528. /* type 21 */
  529. str_content_type = ", Alert";
  530. str_details1 = ", ???";
  531. if (len == 2) {
  532. switch (bp[0]) {
  533. case 1:
  534. str_details1 = ", warning";
  535. break;
  536. case 2:
  537. str_details1 = ", fatal";
  538. break;
  539. }
  540. str_details2 = lookup((int)bp[1], alert_types, " ???");
  541. }
  542. break;
  543. case SSL3_RT_HANDSHAKE:
  544. /* type 22 */
  545. str_content_type = ", Handshake";
  546. str_details1 = "???";
  547. if (len > 0)
  548. str_details1 = lookup((int)bp[0], handshakes, "???");
  549. break;
  550. case SSL3_RT_APPLICATION_DATA:
  551. /* type 23 */
  552. str_content_type = ", ApplicationData";
  553. break;
  554. case SSL3_RT_HEADER:
  555. /* type 256 */
  556. str_content_type = ", RecordHeader";
  557. break;
  558. case SSL3_RT_INNER_CONTENT_TYPE:
  559. /* type 257 */
  560. str_content_type = ", InnerContent";
  561. break;
  562. default:
  563. BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, ", Unknown (content_type=%d)", content_type);
  564. str_content_type = tmpbuf;
  565. }
  566. } else {
  567. BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, "Not TLS data or unknown version (version=%d, content_type=%d)", version, content_type);
  568. str_version = tmpbuf;
  569. }
  570. BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
  571. str_content_type, (unsigned long)len, str_details1,
  572. str_details2);
  573. if (len > 0) {
  574. size_t num, i;
  575. BIO_printf(bio, " ");
  576. num = len;
  577. for (i = 0; i < num; i++) {
  578. if (i % 16 == 0 && i > 0)
  579. BIO_printf(bio, "\n ");
  580. BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
  581. }
  582. if (i < len)
  583. BIO_printf(bio, " ...");
  584. BIO_printf(bio, "\n");
  585. }
  586. (void)BIO_flush(bio);
  587. }
  588. static STRINT_PAIR tlsext_types[] = {
  589. {"server name", TLSEXT_TYPE_server_name},
  590. {"max fragment length", TLSEXT_TYPE_max_fragment_length},
  591. {"client certificate URL", TLSEXT_TYPE_client_certificate_url},
  592. {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
  593. {"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
  594. {"status request", TLSEXT_TYPE_status_request},
  595. {"user mapping", TLSEXT_TYPE_user_mapping},
  596. {"client authz", TLSEXT_TYPE_client_authz},
  597. {"server authz", TLSEXT_TYPE_server_authz},
  598. {"cert type", TLSEXT_TYPE_cert_type},
  599. {"supported_groups", TLSEXT_TYPE_supported_groups},
  600. {"EC point formats", TLSEXT_TYPE_ec_point_formats},
  601. {"SRP", TLSEXT_TYPE_srp},
  602. {"signature algorithms", TLSEXT_TYPE_signature_algorithms},
  603. {"use SRTP", TLSEXT_TYPE_use_srtp},
  604. {"session ticket", TLSEXT_TYPE_session_ticket},
  605. {"renegotiation info", TLSEXT_TYPE_renegotiate},
  606. {"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp},
  607. {"TLS padding", TLSEXT_TYPE_padding},
  608. #ifdef TLSEXT_TYPE_next_proto_neg
  609. {"next protocol", TLSEXT_TYPE_next_proto_neg},
  610. #endif
  611. #ifdef TLSEXT_TYPE_encrypt_then_mac
  612. {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
  613. #endif
  614. #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
  615. {"application layer protocol negotiation",
  616. TLSEXT_TYPE_application_layer_protocol_negotiation},
  617. #endif
  618. #ifdef TLSEXT_TYPE_extended_master_secret
  619. {"extended master secret", TLSEXT_TYPE_extended_master_secret},
  620. #endif
  621. {"key share", TLSEXT_TYPE_key_share},
  622. {"supported versions", TLSEXT_TYPE_supported_versions},
  623. {"psk", TLSEXT_TYPE_psk},
  624. {"psk kex modes", TLSEXT_TYPE_psk_kex_modes},
  625. {"certificate authorities", TLSEXT_TYPE_certificate_authorities},
  626. {"post handshake auth", TLSEXT_TYPE_post_handshake_auth},
  627. {NULL}
  628. };
  629. /* from rfc8446 4.2.3. + gost (https://tools.ietf.org/id/draft-smyshlyaev-tls12-gost-suites-04.html) */
  630. static STRINT_PAIR signature_tls13_scheme_list[] = {
  631. {"rsa_pkcs1_sha1", 0x0201 /* TLSEXT_SIGALG_rsa_pkcs1_sha1 */},
  632. {"ecdsa_sha1", 0x0203 /* TLSEXT_SIGALG_ecdsa_sha1 */},
  633. /* {"rsa_pkcs1_sha224", 0x0301 TLSEXT_SIGALG_rsa_pkcs1_sha224}, not in rfc8446 */
  634. /* {"ecdsa_sha224", 0x0303 TLSEXT_SIGALG_ecdsa_sha224} not in rfc8446 */
  635. {"rsa_pkcs1_sha256", 0x0401 /* TLSEXT_SIGALG_rsa_pkcs1_sha256 */},
  636. {"ecdsa_secp256r1_sha256", 0x0403 /* TLSEXT_SIGALG_ecdsa_secp256r1_sha256 */},
  637. {"rsa_pkcs1_sha384", 0x0501 /* TLSEXT_SIGALG_rsa_pkcs1_sha384 */},
  638. {"ecdsa_secp384r1_sha384", 0x0503 /* TLSEXT_SIGALG_ecdsa_secp384r1_sha384 */},
  639. {"rsa_pkcs1_sha512", 0x0601 /* TLSEXT_SIGALG_rsa_pkcs1_sha512 */},
  640. {"ecdsa_secp521r1_sha512", 0x0603 /* TLSEXT_SIGALG_ecdsa_secp521r1_sha512 */},
  641. {"rsa_pss_rsae_sha256", 0x0804 /* TLSEXT_SIGALG_rsa_pss_rsae_sha256 */},
  642. {"rsa_pss_rsae_sha384", 0x0805 /* TLSEXT_SIGALG_rsa_pss_rsae_sha384 */},
  643. {"rsa_pss_rsae_sha512", 0x0806 /* TLSEXT_SIGALG_rsa_pss_rsae_sha512 */},
  644. {"ed25519", 0x0807 /* TLSEXT_SIGALG_ed25519 */},
  645. {"ed448", 0x0808 /* TLSEXT_SIGALG_ed448 */},
  646. {"rsa_pss_pss_sha256", 0x0809 /* TLSEXT_SIGALG_rsa_pss_pss_sha256 */},
  647. {"rsa_pss_pss_sha384", 0x080a /* TLSEXT_SIGALG_rsa_pss_pss_sha384 */},
  648. {"rsa_pss_pss_sha512", 0x080b /* TLSEXT_SIGALG_rsa_pss_pss_sha512 */},
  649. {"gostr34102001", 0xeded /* TLSEXT_SIGALG_gostr34102001_gostr3411 */},
  650. {"gostr34102012_256", 0xeeee /* TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256 */},
  651. {"gostr34102012_512", 0xefef /* TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512 */},
  652. {NULL}
  653. };
  654. /* from rfc5246 7.4.1.4.1. */
  655. static STRINT_PAIR signature_tls12_alg_list[] = {
  656. {"anonymous", TLSEXT_signature_anonymous /* 0 */},
  657. {"RSA", TLSEXT_signature_rsa /* 1 */},
  658. {"DSA", TLSEXT_signature_dsa /* 2 */},
  659. {"ECDSA", TLSEXT_signature_ecdsa /* 3 */},
  660. {NULL}
  661. };
  662. /* from rfc5246 7.4.1.4.1. */
  663. static STRINT_PAIR signature_tls12_hash_list[] = {
  664. {"none", TLSEXT_hash_none /* 0 */},
  665. {"MD5", TLSEXT_hash_md5 /* 1 */},
  666. {"SHA1", TLSEXT_hash_sha1 /* 2 */},
  667. {"SHA224", TLSEXT_hash_sha224 /* 3 */},
  668. {"SHA256", TLSEXT_hash_sha256 /* 4 */},
  669. {"SHA384", TLSEXT_hash_sha384 /* 5 */},
  670. {"SHA512", TLSEXT_hash_sha512 /* 6 */},
  671. {NULL}
  672. };
  673. void tlsext_cb(SSL *s, int client_server, int type,
  674. const unsigned char *data, int len, void *arg)
  675. {
  676. BIO *bio = arg;
  677. const char *extname = lookup(type, tlsext_types, "unknown");
  678. BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
  679. client_server ? "server" : "client", extname, type, len);
  680. BIO_dump(bio, (const char *)data, len);
  681. (void)BIO_flush(bio);
  682. }
  683. #ifndef OPENSSL_NO_SOCK
  684. int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
  685. size_t *cookie_len)
  686. {
  687. unsigned char *buffer = NULL;
  688. size_t length = 0;
  689. unsigned short port;
  690. BIO_ADDR *lpeer = NULL, *peer = NULL;
  691. int res = 0;
  692. /* Initialize a random secret */
  693. if (!cookie_initialized) {
  694. if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
  695. BIO_printf(bio_err, "error setting random cookie secret\n");
  696. return 0;
  697. }
  698. cookie_initialized = 1;
  699. }
  700. if (SSL_is_dtls(ssl)) {
  701. lpeer = peer = BIO_ADDR_new();
  702. if (peer == NULL) {
  703. BIO_printf(bio_err, "memory full\n");
  704. return 0;
  705. }
  706. /* Read peer information */
  707. (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
  708. } else {
  709. peer = ourpeer;
  710. }
  711. /* Create buffer with peer's address and port */
  712. if (!BIO_ADDR_rawaddress(peer, NULL, &length)) {
  713. BIO_printf(bio_err, "Failed getting peer address\n");
  714. BIO_ADDR_free(lpeer);
  715. return 0;
  716. }
  717. OPENSSL_assert(length != 0);
  718. port = BIO_ADDR_rawport(peer);
  719. length += sizeof(port);
  720. buffer = app_malloc(length, "cookie generate buffer");
  721. memcpy(buffer, &port, sizeof(port));
  722. BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
  723. if (EVP_Q_mac(NULL, "HMAC", NULL, "SHA1", NULL,
  724. cookie_secret, COOKIE_SECRET_LENGTH, buffer, length,
  725. cookie, DTLS1_COOKIE_LENGTH, cookie_len) == NULL) {
  726. BIO_printf(bio_err,
  727. "Error calculating HMAC-SHA1 of buffer with secret\n");
  728. goto end;
  729. }
  730. res = 1;
  731. end:
  732. OPENSSL_free(buffer);
  733. BIO_ADDR_free(lpeer);
  734. return res;
  735. }
  736. int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
  737. size_t cookie_len)
  738. {
  739. unsigned char result[EVP_MAX_MD_SIZE];
  740. size_t resultlength;
  741. /* Note: we check cookie_initialized because if it's not,
  742. * it cannot be valid */
  743. if (cookie_initialized
  744. && generate_stateless_cookie_callback(ssl, result, &resultlength)
  745. && cookie_len == resultlength
  746. && memcmp(result, cookie, resultlength) == 0)
  747. return 1;
  748. return 0;
  749. }
  750. int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
  751. unsigned int *cookie_len)
  752. {
  753. size_t temp = 0;
  754. int res = generate_stateless_cookie_callback(ssl, cookie, &temp);
  755. if (res != 0)
  756. *cookie_len = (unsigned int)temp;
  757. return res;
  758. }
  759. int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
  760. unsigned int cookie_len)
  761. {
  762. return verify_stateless_cookie_callback(ssl, cookie, cookie_len);
  763. }
  764. #endif
  765. /*
  766. * Example of extended certificate handling. Where the standard support of
  767. * one certificate per algorithm is not sufficient an application can decide
  768. * which certificate(s) to use at runtime based on whatever criteria it deems
  769. * appropriate.
  770. */
  771. /* Linked list of certificates, keys and chains */
  772. struct ssl_excert_st {
  773. int certform;
  774. const char *certfile;
  775. int keyform;
  776. const char *keyfile;
  777. const char *chainfile;
  778. X509 *cert;
  779. EVP_PKEY *key;
  780. STACK_OF(X509) *chain;
  781. int build_chain;
  782. struct ssl_excert_st *next, *prev;
  783. };
  784. static STRINT_PAIR chain_flags[] = {
  785. {"Overall Validity", CERT_PKEY_VALID},
  786. {"Sign with EE key", CERT_PKEY_SIGN},
  787. {"EE signature", CERT_PKEY_EE_SIGNATURE},
  788. {"CA signature", CERT_PKEY_CA_SIGNATURE},
  789. {"EE key parameters", CERT_PKEY_EE_PARAM},
  790. {"CA key parameters", CERT_PKEY_CA_PARAM},
  791. {"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
  792. {"Issuer Name", CERT_PKEY_ISSUER_NAME},
  793. {"Certificate Type", CERT_PKEY_CERT_TYPE},
  794. {NULL}
  795. };
  796. static void print_chain_flags(SSL *s, int flags)
  797. {
  798. STRINT_PAIR *pp;
  799. for (pp = chain_flags; pp->name; ++pp)
  800. BIO_printf(bio_err, "\t%s: %s\n",
  801. pp->name,
  802. (flags & pp->retval) ? "OK" : "NOT OK");
  803. BIO_printf(bio_err, "\tSuite B: ");
  804. if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
  805. BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
  806. else
  807. BIO_printf(bio_err, "not tested\n");
  808. }
  809. /*
  810. * Very basic selection callback: just use any certificate chain reported as
  811. * valid. More sophisticated could prioritise according to local policy.
  812. */
  813. static int set_cert_cb(SSL *ssl, void *arg)
  814. {
  815. int i, rv;
  816. SSL_EXCERT *exc = arg;
  817. #ifdef CERT_CB_TEST_RETRY
  818. static int retry_cnt;
  819. if (retry_cnt < 5) {
  820. retry_cnt++;
  821. BIO_printf(bio_err,
  822. "Certificate callback retry test: count %d\n",
  823. retry_cnt);
  824. return -1;
  825. }
  826. #endif
  827. SSL_certs_clear(ssl);
  828. if (exc == NULL)
  829. return 1;
  830. /*
  831. * Go to end of list and traverse backwards since we prepend newer
  832. * entries this retains the original order.
  833. */
  834. while (exc->next != NULL)
  835. exc = exc->next;
  836. i = 0;
  837. while (exc != NULL) {
  838. i++;
  839. rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
  840. BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
  841. X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
  842. get_nameopt());
  843. BIO_puts(bio_err, "\n");
  844. print_chain_flags(ssl, rv);
  845. if (rv & CERT_PKEY_VALID) {
  846. if (!SSL_use_certificate(ssl, exc->cert)
  847. || !SSL_use_PrivateKey(ssl, exc->key)) {
  848. return 0;
  849. }
  850. /*
  851. * NB: we wouldn't normally do this as it is not efficient
  852. * building chains on each connection better to cache the chain
  853. * in advance.
  854. */
  855. if (exc->build_chain) {
  856. if (!SSL_build_cert_chain(ssl, 0))
  857. return 0;
  858. } else if (exc->chain != NULL) {
  859. if (!SSL_set1_chain(ssl, exc->chain))
  860. return 0;
  861. }
  862. }
  863. exc = exc->prev;
  864. }
  865. return 1;
  866. }
  867. void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
  868. {
  869. SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
  870. }
  871. static int ssl_excert_prepend(SSL_EXCERT **pexc)
  872. {
  873. SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
  874. memset(exc, 0, sizeof(*exc));
  875. exc->next = *pexc;
  876. *pexc = exc;
  877. if (exc->next) {
  878. exc->certform = exc->next->certform;
  879. exc->keyform = exc->next->keyform;
  880. exc->next->prev = exc;
  881. } else {
  882. exc->certform = FORMAT_PEM;
  883. exc->keyform = FORMAT_PEM;
  884. }
  885. return 1;
  886. }
  887. void ssl_excert_free(SSL_EXCERT *exc)
  888. {
  889. SSL_EXCERT *curr;
  890. if (exc == NULL)
  891. return;
  892. while (exc) {
  893. X509_free(exc->cert);
  894. EVP_PKEY_free(exc->key);
  895. sk_X509_pop_free(exc->chain, X509_free);
  896. curr = exc;
  897. exc = exc->next;
  898. OPENSSL_free(curr);
  899. }
  900. }
  901. int load_excert(SSL_EXCERT **pexc)
  902. {
  903. SSL_EXCERT *exc = *pexc;
  904. if (exc == NULL)
  905. return 1;
  906. /* If nothing in list, free and set to NULL */
  907. if (exc->certfile == NULL && exc->next == NULL) {
  908. ssl_excert_free(exc);
  909. *pexc = NULL;
  910. return 1;
  911. }
  912. for (; exc; exc = exc->next) {
  913. if (exc->certfile == NULL) {
  914. BIO_printf(bio_err, "Missing filename\n");
  915. return 0;
  916. }
  917. exc->cert = load_cert(exc->certfile, exc->certform,
  918. "Server Certificate");
  919. if (exc->cert == NULL)
  920. return 0;
  921. if (exc->keyfile != NULL) {
  922. exc->key = load_key(exc->keyfile, exc->keyform,
  923. 0, NULL, NULL, "server key");
  924. } else {
  925. exc->key = load_key(exc->certfile, exc->certform,
  926. 0, NULL, NULL, "server key");
  927. }
  928. if (exc->key == NULL)
  929. return 0;
  930. if (exc->chainfile != NULL) {
  931. if (!load_certs(exc->chainfile, 0, &exc->chain, NULL, "server chain"))
  932. return 0;
  933. }
  934. }
  935. return 1;
  936. }
  937. enum range { OPT_X_ENUM };
  938. int args_excert(int opt, SSL_EXCERT **pexc)
  939. {
  940. SSL_EXCERT *exc = *pexc;
  941. assert(opt > OPT_X__FIRST);
  942. assert(opt < OPT_X__LAST);
  943. if (exc == NULL) {
  944. if (!ssl_excert_prepend(&exc)) {
  945. BIO_printf(bio_err, " %s: Error initialising xcert\n",
  946. opt_getprog());
  947. goto err;
  948. }
  949. *pexc = exc;
  950. }
  951. switch ((enum range)opt) {
  952. case OPT_X__FIRST:
  953. case OPT_X__LAST:
  954. return 0;
  955. case OPT_X_CERT:
  956. if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) {
  957. BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
  958. goto err;
  959. }
  960. *pexc = exc;
  961. exc->certfile = opt_arg();
  962. break;
  963. case OPT_X_KEY:
  964. if (exc->keyfile != NULL) {
  965. BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
  966. goto err;
  967. }
  968. exc->keyfile = opt_arg();
  969. break;
  970. case OPT_X_CHAIN:
  971. if (exc->chainfile != NULL) {
  972. BIO_printf(bio_err, "%s: Chain already specified\n",
  973. opt_getprog());
  974. goto err;
  975. }
  976. exc->chainfile = opt_arg();
  977. break;
  978. case OPT_X_CHAIN_BUILD:
  979. exc->build_chain = 1;
  980. break;
  981. case OPT_X_CERTFORM:
  982. if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->certform))
  983. return 0;
  984. break;
  985. case OPT_X_KEYFORM:
  986. if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->keyform))
  987. return 0;
  988. break;
  989. }
  990. return 1;
  991. err:
  992. ERR_print_errors(bio_err);
  993. ssl_excert_free(exc);
  994. *pexc = NULL;
  995. return 0;
  996. }
  997. static void print_raw_cipherlist(SSL *s)
  998. {
  999. const unsigned char *rlist;
  1000. static const unsigned char scsv_id[] = { 0, 0xFF };
  1001. size_t i, rlistlen, num;
  1002. if (!SSL_is_server(s))
  1003. return;
  1004. num = SSL_get0_raw_cipherlist(s, NULL);
  1005. OPENSSL_assert(num == 2);
  1006. rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
  1007. BIO_puts(bio_err, "Client cipher list: ");
  1008. for (i = 0; i < rlistlen; i += num, rlist += num) {
  1009. const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
  1010. if (i)
  1011. BIO_puts(bio_err, ":");
  1012. if (c != NULL) {
  1013. BIO_puts(bio_err, SSL_CIPHER_get_name(c));
  1014. } else if (memcmp(rlist, scsv_id, num) == 0) {
  1015. BIO_puts(bio_err, "SCSV");
  1016. } else {
  1017. size_t j;
  1018. BIO_puts(bio_err, "0x");
  1019. for (j = 0; j < num; j++)
  1020. BIO_printf(bio_err, "%02X", rlist[j]);
  1021. }
  1022. }
  1023. BIO_puts(bio_err, "\n");
  1024. }
  1025. /*
  1026. * Hex encoder for TLSA RRdata, not ':' delimited.
  1027. */
  1028. static char *hexencode(const unsigned char *data, size_t len)
  1029. {
  1030. static const char *hex = "0123456789abcdef";
  1031. char *out;
  1032. char *cp;
  1033. size_t outlen = 2 * len + 1;
  1034. int ilen = (int) outlen;
  1035. if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
  1036. BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n",
  1037. opt_getprog(), len);
  1038. exit(1);
  1039. }
  1040. cp = out = app_malloc(ilen, "TLSA hex data buffer");
  1041. while (len-- > 0) {
  1042. *cp++ = hex[(*data >> 4) & 0x0f];
  1043. *cp++ = hex[*data++ & 0x0f];
  1044. }
  1045. *cp = '\0';
  1046. return out;
  1047. }
  1048. void print_verify_detail(SSL *s, BIO *bio)
  1049. {
  1050. int mdpth;
  1051. EVP_PKEY *mspki;
  1052. long verify_err = SSL_get_verify_result(s);
  1053. if (verify_err == X509_V_OK) {
  1054. const char *peername = SSL_get0_peername(s);
  1055. BIO_printf(bio, "Verification: OK\n");
  1056. if (peername != NULL)
  1057. BIO_printf(bio, "Verified peername: %s\n", peername);
  1058. } else {
  1059. const char *reason = X509_verify_cert_error_string(verify_err);
  1060. BIO_printf(bio, "Verification error: %s\n", reason);
  1061. }
  1062. if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
  1063. uint8_t usage, selector, mtype;
  1064. const unsigned char *data = NULL;
  1065. size_t dlen = 0;
  1066. char *hexdata;
  1067. mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
  1068. /*
  1069. * The TLSA data field can be quite long when it is a certificate,
  1070. * public key or even a SHA2-512 digest. Because the initial octets of
  1071. * ASN.1 certificates and public keys contain mostly boilerplate OIDs
  1072. * and lengths, we show the last 12 bytes of the data instead, as these
  1073. * are more likely to distinguish distinct TLSA records.
  1074. */
  1075. #define TLSA_TAIL_SIZE 12
  1076. if (dlen > TLSA_TAIL_SIZE)
  1077. hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
  1078. else
  1079. hexdata = hexencode(data, dlen);
  1080. BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
  1081. usage, selector, mtype,
  1082. (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
  1083. (mspki != NULL) ? "signed the certificate" :
  1084. mdpth ? "matched TA certificate" : "matched EE certificate",
  1085. mdpth);
  1086. OPENSSL_free(hexdata);
  1087. }
  1088. }
  1089. void print_ssl_summary(SSL *s)
  1090. {
  1091. const SSL_CIPHER *c;
  1092. X509 *peer;
  1093. BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
  1094. print_raw_cipherlist(s);
  1095. c = SSL_get_current_cipher(s);
  1096. BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
  1097. do_print_sigalgs(bio_err, s, 0);
  1098. peer = SSL_get0_peer_certificate(s);
  1099. if (peer != NULL) {
  1100. int nid;
  1101. BIO_puts(bio_err, "Peer certificate: ");
  1102. X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
  1103. 0, get_nameopt());
  1104. BIO_puts(bio_err, "\n");
  1105. if (SSL_get_peer_signature_nid(s, &nid))
  1106. BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
  1107. if (SSL_get_peer_signature_type_nid(s, &nid))
  1108. BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid));
  1109. print_verify_detail(s, bio_err);
  1110. } else {
  1111. BIO_puts(bio_err, "No peer certificate\n");
  1112. }
  1113. #ifndef OPENSSL_NO_EC
  1114. ssl_print_point_formats(bio_err, s);
  1115. if (SSL_is_server(s))
  1116. ssl_print_groups(bio_err, s, 1);
  1117. else
  1118. ssl_print_tmp_key(bio_err, s);
  1119. #else
  1120. if (!SSL_is_server(s))
  1121. ssl_print_tmp_key(bio_err, s);
  1122. #endif
  1123. }
  1124. int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
  1125. SSL_CTX *ctx)
  1126. {
  1127. int i;
  1128. SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
  1129. for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
  1130. const char *flag = sk_OPENSSL_STRING_value(str, i);
  1131. const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
  1132. if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
  1133. BIO_printf(bio_err, "Call to SSL_CONF_cmd(%s, %s) failed\n",
  1134. flag, arg == NULL ? "<NULL>" : arg);
  1135. ERR_print_errors(bio_err);
  1136. return 0;
  1137. }
  1138. }
  1139. if (!SSL_CONF_CTX_finish(cctx)) {
  1140. BIO_puts(bio_err, "Error finishing context\n");
  1141. ERR_print_errors(bio_err);
  1142. return 0;
  1143. }
  1144. return 1;
  1145. }
  1146. static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
  1147. {
  1148. X509_CRL *crl;
  1149. int i, ret = 1;
  1150. for (i = 0; i < sk_X509_CRL_num(crls); i++) {
  1151. crl = sk_X509_CRL_value(crls, i);
  1152. if (!X509_STORE_add_crl(st, crl))
  1153. ret = 0;
  1154. }
  1155. return ret;
  1156. }
  1157. int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
  1158. {
  1159. X509_STORE *st;
  1160. st = SSL_CTX_get_cert_store(ctx);
  1161. add_crls_store(st, crls);
  1162. if (crl_download)
  1163. store_setup_crl_download(st);
  1164. return 1;
  1165. }
  1166. int ssl_load_stores(SSL_CTX *ctx,
  1167. const char *vfyCApath, const char *vfyCAfile,
  1168. const char *vfyCAstore,
  1169. const char *chCApath, const char *chCAfile,
  1170. const char *chCAstore,
  1171. STACK_OF(X509_CRL) *crls, int crl_download)
  1172. {
  1173. X509_STORE *vfy = NULL, *ch = NULL;
  1174. int rv = 0;
  1175. if (vfyCApath != NULL || vfyCAfile != NULL || vfyCAstore != NULL) {
  1176. vfy = X509_STORE_new();
  1177. if (vfy == NULL)
  1178. goto err;
  1179. if (vfyCAfile != NULL && !X509_STORE_load_file(vfy, vfyCAfile))
  1180. goto err;
  1181. if (vfyCApath != NULL && !X509_STORE_load_path(vfy, vfyCApath))
  1182. goto err;
  1183. if (vfyCAstore != NULL && !X509_STORE_load_store(vfy, vfyCAstore))
  1184. goto err;
  1185. add_crls_store(vfy, crls);
  1186. if (SSL_CTX_set1_verify_cert_store(ctx, vfy) == 0)
  1187. goto err;
  1188. if (crl_download)
  1189. store_setup_crl_download(vfy);
  1190. }
  1191. if (chCApath != NULL || chCAfile != NULL || chCAstore != NULL) {
  1192. ch = X509_STORE_new();
  1193. if (ch == NULL)
  1194. goto err;
  1195. if (chCAfile != NULL && !X509_STORE_load_file(ch, chCAfile))
  1196. goto err;
  1197. if (chCApath != NULL && !X509_STORE_load_path(ch, chCApath))
  1198. goto err;
  1199. if (chCAstore != NULL && !X509_STORE_load_store(ch, chCAstore))
  1200. goto err;
  1201. if (SSL_CTX_set1_chain_cert_store(ctx, ch) == 0)
  1202. goto err;
  1203. }
  1204. rv = 1;
  1205. err:
  1206. X509_STORE_free(vfy);
  1207. X509_STORE_free(ch);
  1208. return rv;
  1209. }
  1210. /* Verbose print out of security callback */
  1211. typedef struct {
  1212. BIO *out;
  1213. int verbose;
  1214. int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
  1215. void *other, void *ex);
  1216. } security_debug_ex;
  1217. static STRINT_PAIR callback_types[] = {
  1218. {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
  1219. {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
  1220. {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
  1221. #ifndef OPENSSL_NO_DH
  1222. {"Temp DH key bits", SSL_SECOP_TMP_DH},
  1223. #endif
  1224. {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
  1225. {"Shared Curve", SSL_SECOP_CURVE_SHARED},
  1226. {"Check Curve", SSL_SECOP_CURVE_CHECK},
  1227. {"Supported Signature Algorithm", SSL_SECOP_SIGALG_SUPPORTED},
  1228. {"Shared Signature Algorithm", SSL_SECOP_SIGALG_SHARED},
  1229. {"Check Signature Algorithm", SSL_SECOP_SIGALG_CHECK},
  1230. {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
  1231. {"Certificate chain EE key", SSL_SECOP_EE_KEY},
  1232. {"Certificate chain CA key", SSL_SECOP_CA_KEY},
  1233. {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
  1234. {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
  1235. {"Certificate chain CA digest", SSL_SECOP_CA_MD},
  1236. {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
  1237. {"SSL compression", SSL_SECOP_COMPRESSION},
  1238. {"Session ticket", SSL_SECOP_TICKET},
  1239. {NULL}
  1240. };
  1241. static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
  1242. int op, int bits, int nid,
  1243. void *other, void *ex)
  1244. {
  1245. security_debug_ex *sdb = ex;
  1246. int rv, show_bits = 1, cert_md = 0;
  1247. const char *nm;
  1248. int show_nm;
  1249. rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
  1250. if (rv == 1 && sdb->verbose < 2)
  1251. return 1;
  1252. BIO_puts(sdb->out, "Security callback: ");
  1253. nm = lookup(op, callback_types, NULL);
  1254. show_nm = nm != NULL;
  1255. switch (op) {
  1256. case SSL_SECOP_TICKET:
  1257. case SSL_SECOP_COMPRESSION:
  1258. show_bits = 0;
  1259. show_nm = 0;
  1260. break;
  1261. case SSL_SECOP_VERSION:
  1262. BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
  1263. show_bits = 0;
  1264. show_nm = 0;
  1265. break;
  1266. case SSL_SECOP_CA_MD:
  1267. case SSL_SECOP_PEER_CA_MD:
  1268. cert_md = 1;
  1269. break;
  1270. case SSL_SECOP_SIGALG_SUPPORTED:
  1271. case SSL_SECOP_SIGALG_SHARED:
  1272. case SSL_SECOP_SIGALG_CHECK:
  1273. case SSL_SECOP_SIGALG_MASK:
  1274. show_nm = 0;
  1275. break;
  1276. }
  1277. if (show_nm)
  1278. BIO_printf(sdb->out, "%s=", nm);
  1279. switch (op & SSL_SECOP_OTHER_TYPE) {
  1280. case SSL_SECOP_OTHER_CIPHER:
  1281. BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
  1282. break;
  1283. #ifndef OPENSSL_NO_EC
  1284. case SSL_SECOP_OTHER_CURVE:
  1285. {
  1286. const char *cname;
  1287. cname = EC_curve_nid2nist(nid);
  1288. if (cname == NULL)
  1289. cname = OBJ_nid2sn(nid);
  1290. BIO_puts(sdb->out, cname);
  1291. }
  1292. break;
  1293. #endif
  1294. case SSL_SECOP_OTHER_CERT:
  1295. {
  1296. if (cert_md) {
  1297. int sig_nid = X509_get_signature_nid(other);
  1298. BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
  1299. } else {
  1300. EVP_PKEY *pkey = X509_get0_pubkey(other);
  1301. if (pkey == NULL) {
  1302. BIO_printf(sdb->out, "Public key missing");
  1303. } else {
  1304. const char *algname = "";
  1305. EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
  1306. &algname, EVP_PKEY_get0_asn1(pkey));
  1307. BIO_printf(sdb->out, "%s, bits=%d",
  1308. algname, EVP_PKEY_get_bits(pkey));
  1309. }
  1310. }
  1311. break;
  1312. }
  1313. case SSL_SECOP_OTHER_SIGALG:
  1314. {
  1315. const unsigned char *salg = other;
  1316. const char *sname = NULL;
  1317. int raw_sig_code = (salg[0] << 8) + salg[1]; /* always big endian (msb, lsb) */
  1318. /* raw_sig_code: signature_scheme from tls1.3, or signature_and_hash from tls1.2 */
  1319. if (nm != NULL)
  1320. BIO_printf(sdb->out, "%s", nm);
  1321. else
  1322. BIO_printf(sdb->out, "s_cb.c:security_callback_debug op=0x%x", op);
  1323. sname = lookup(raw_sig_code, signature_tls13_scheme_list, NULL);
  1324. if (sname != NULL) {
  1325. BIO_printf(sdb->out, " scheme=%s", sname);
  1326. } else {
  1327. int alg_code = salg[1];
  1328. int hash_code = salg[0];
  1329. const char *alg_str = lookup(alg_code, signature_tls12_alg_list, NULL);
  1330. const char *hash_str = lookup(hash_code, signature_tls12_hash_list, NULL);
  1331. if (alg_str != NULL && hash_str != NULL)
  1332. BIO_printf(sdb->out, " digest=%s, algorithm=%s", hash_str, alg_str);
  1333. else
  1334. BIO_printf(sdb->out, " scheme=unknown(0x%04x)", raw_sig_code);
  1335. }
  1336. }
  1337. }
  1338. if (show_bits)
  1339. BIO_printf(sdb->out, ", security bits=%d", bits);
  1340. BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
  1341. return rv;
  1342. }
  1343. void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
  1344. {
  1345. static security_debug_ex sdb;
  1346. sdb.out = bio_err;
  1347. sdb.verbose = verbose;
  1348. sdb.old_cb = SSL_CTX_get_security_callback(ctx);
  1349. SSL_CTX_set_security_callback(ctx, security_callback_debug);
  1350. SSL_CTX_set0_security_ex_data(ctx, &sdb);
  1351. }
  1352. static void keylog_callback(const SSL *ssl, const char *line)
  1353. {
  1354. if (bio_keylog == NULL) {
  1355. BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n");
  1356. return;
  1357. }
  1358. /*
  1359. * There might be concurrent writers to the keylog file, so we must ensure
  1360. * that the given line is written at once.
  1361. */
  1362. BIO_printf(bio_keylog, "%s\n", line);
  1363. (void)BIO_flush(bio_keylog);
  1364. }
  1365. int set_keylog_file(SSL_CTX *ctx, const char *keylog_file)
  1366. {
  1367. /* Close any open files */
  1368. BIO_free_all(bio_keylog);
  1369. bio_keylog = NULL;
  1370. if (ctx == NULL || keylog_file == NULL) {
  1371. /* Keylogging is disabled, OK. */
  1372. return 0;
  1373. }
  1374. /*
  1375. * Append rather than write in order to allow concurrent modification.
  1376. * Furthermore, this preserves existing keylog files which is useful when
  1377. * the tool is run multiple times.
  1378. */
  1379. bio_keylog = BIO_new_file(keylog_file, "a");
  1380. if (bio_keylog == NULL) {
  1381. BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file);
  1382. return 1;
  1383. }
  1384. /* Write a header for seekable, empty files (this excludes pipes). */
  1385. if (BIO_tell(bio_keylog) == 0) {
  1386. BIO_puts(bio_keylog,
  1387. "# SSL/TLS secrets log file, generated by OpenSSL\n");
  1388. (void)BIO_flush(bio_keylog);
  1389. }
  1390. SSL_CTX_set_keylog_callback(ctx, keylog_callback);
  1391. return 0;
  1392. }
  1393. void print_ca_names(BIO *bio, SSL *s)
  1394. {
  1395. const char *cs = SSL_is_server(s) ? "server" : "client";
  1396. const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s);
  1397. int i;
  1398. if (sk == NULL || sk_X509_NAME_num(sk) == 0) {
  1399. if (!SSL_is_server(s))
  1400. BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs);
  1401. return;
  1402. }
  1403. BIO_printf(bio, "---\nAcceptable %s certificate CA names\n",cs);
  1404. for (i = 0; i < sk_X509_NAME_num(sk); i++) {
  1405. X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt());
  1406. BIO_write(bio, "\n", 1);
  1407. }
  1408. }