s_cb.c 49 KB

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