s_cb.c 47 KB

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