2
0

s_cb.c 48 KB

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