s_cb.c 49 KB

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