s_cb.c 49 KB

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