x509.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include "apps.h"
  13. #include "progs.h"
  14. #include <openssl/bio.h>
  15. #include <openssl/asn1.h>
  16. #include <openssl/err.h>
  17. #include <openssl/bn.h>
  18. #include <openssl/evp.h>
  19. #include <openssl/x509.h>
  20. #include <openssl/x509v3.h>
  21. #include <openssl/objects.h>
  22. #include <openssl/pem.h>
  23. #include <openssl/rsa.h>
  24. #ifndef OPENSSL_NO_DSA
  25. # include <openssl/dsa.h>
  26. #endif
  27. #undef POSTFIX
  28. #define POSTFIX ".srl"
  29. #define DEFAULT_DAYS 30 /* default cert validity period in days */
  30. #define UNSET_DAYS -2 /* -1 is used for testing expiration checks */
  31. #define EXT_COPY_UNSET -1
  32. static int callb(int ok, X509_STORE_CTX *ctx);
  33. static ASN1_INTEGER *x509_load_serial(const char *CAfile,
  34. const char *serialfile, int create);
  35. static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
  36. static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names);
  37. typedef enum OPTION_choice {
  38. OPT_COMMON,
  39. OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM,
  40. OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE,
  41. OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_KEY, OPT_SIGNKEY, OPT_CA, OPT_CAKEY,
  42. OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_SUBJ,
  43. OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_DATEOPT, OPT_NAMEOPT,
  44. OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL,
  45. OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH,
  46. OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES,
  47. OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST,
  48. OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST,
  49. OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID,
  50. OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, OPT_COPY_EXTENSIONS,
  51. OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES,
  52. OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT
  53. } OPTION_CHOICE;
  54. const OPTIONS x509_options[] = {
  55. OPT_SECTION("General"),
  56. {"help", OPT_HELP, '-', "Display this summary"},
  57. {"in", OPT_IN, '<',
  58. "Certificate input, or CSR input file with -req (default stdin)"},
  59. {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"},
  60. {"new", OPT_NEW, '-', "Generate a certificate from scratch"},
  61. {"x509toreq", OPT_X509TOREQ, '-',
  62. "Output a certification request (rather than a certificate)"},
  63. {"req", OPT_REQ, '-', "Input is a CSR file (rather than a certificate)"},
  64. {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
  65. "copy extensions when converting from CSR to x509 or vice versa"},
  66. {"inform", OPT_INFORM, 'f',
  67. "CSR input format to use (PEM or DER; by default try PEM first)"},
  68. {"vfyopt", OPT_VFYOPT, 's', "CSR verification parameter in n:v form"},
  69. {"key", OPT_KEY, 's',
  70. "Key for signing, and to include unless using -force_pubkey"},
  71. {"signkey", OPT_SIGNKEY, 's',
  72. "Same as -key"},
  73. {"keyform", OPT_KEYFORM, 'E',
  74. "Key input format (ENGINE, other values ignored)"},
  75. {"out", OPT_OUT, '>', "Output file - default stdout"},
  76. {"outform", OPT_OUTFORM, 'f',
  77. "Output format (DER or PEM) - default PEM"},
  78. {"nocert", OPT_NOCERT, '-',
  79. "No cert output (except for requested printing)"},
  80. {"noout", OPT_NOOUT, '-', "No output (except for requested printing)"},
  81. OPT_SECTION("Certificate printing"),
  82. {"text", OPT_TEXT, '-', "Print the certificate in text form"},
  83. {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."},
  84. {"certopt", OPT_CERTOPT, 's', "Various certificate text printing options"},
  85. {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"},
  86. {"alias", OPT_ALIAS, '-', "Print certificate alias"},
  87. {"serial", OPT_SERIAL, '-', "Print serial number value"},
  88. {"startdate", OPT_STARTDATE, '-', "Print the notBefore field"},
  89. {"enddate", OPT_ENDDATE, '-', "Print the notAfter field"},
  90. {"dates", OPT_DATES, '-', "Print both notBefore and notAfter fields"},
  91. {"subject", OPT_SUBJECT, '-', "Print subject DN"},
  92. {"issuer", OPT_ISSUER, '-', "Print issuer DN"},
  93. {"nameopt", OPT_NAMEOPT, 's',
  94. "Certificate subject/issuer name printing options"},
  95. {"email", OPT_EMAIL, '-', "Print email address(es)"},
  96. {"hash", OPT_HASH, '-', "Synonym for -subject_hash (for backward compat)"},
  97. {"subject_hash", OPT_HASH, '-', "Print subject hash value"},
  98. #ifndef OPENSSL_NO_MD5
  99. {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-',
  100. "Print old-style (MD5) subject hash value"},
  101. #endif
  102. {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"},
  103. #ifndef OPENSSL_NO_MD5
  104. {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-',
  105. "Print old-style (MD5) issuer hash value"},
  106. #endif
  107. {"ext", OPT_EXT, 's',
  108. "Restrict which X.509 extensions to print and/or copy"},
  109. {"ocspid", OPT_OCSPID, '-',
  110. "Print OCSP hash values for the subject name and public key"},
  111. {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"},
  112. {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"},
  113. {"pubkey", OPT_PUBKEY, '-', "Print the public key in PEM format"},
  114. {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
  115. OPT_SECTION("Certificate checking"),
  116. {"checkend", OPT_CHECKEND, 'M',
  117. "Check whether cert expires in the next arg seconds"},
  118. {OPT_MORE_STR, 1, 1, "Exit 1 (failure) if so, 0 if not"},
  119. {"checkhost", OPT_CHECKHOST, 's', "Check certificate matches host"},
  120. {"checkemail", OPT_CHECKEMAIL, 's', "Check certificate matches email"},
  121. {"checkip", OPT_CHECKIP, 's', "Check certificate matches ipaddr"},
  122. OPT_SECTION("Certificate output"),
  123. {"set_serial", OPT_SET_SERIAL, 's',
  124. "Serial number to use, overrides -CAserial"},
  125. {"next_serial", OPT_NEXT_SERIAL, '-',
  126. "Increment current certificate serial number"},
  127. {"days", OPT_DAYS, 'n',
  128. "Number of days until newly generated certificate expires - default 30"},
  129. {"preserve_dates", OPT_PRESERVE_DATES, '-',
  130. "Preserve existing validity dates"},
  131. {"subj", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"},
  132. {"force_pubkey", OPT_FORCE_PUBKEY, '<',
  133. "Place the given key in new certificate"},
  134. {"clrext", OPT_CLREXT, '-',
  135. "Do not take over any extensions from the source certificate or request"},
  136. {"extfile", OPT_EXTFILE, '<', "Config file with X509V3 extensions to add"},
  137. {"extensions", OPT_EXTENSIONS, 's',
  138. "Section of extfile to use - default: unnamed section"},
  139. {"sigopt", OPT_SIGOPT, 's', "Signature parameter, in n:v form"},
  140. {"badsig", OPT_BADSIG, '-',
  141. "Corrupt last byte of certificate signature (for test)"},
  142. {"", OPT_MD, '-', "Any supported digest, used for signing and printing"},
  143. OPT_SECTION("Micro-CA"),
  144. {"CA", OPT_CA, '<',
  145. "Use the given CA certificate, conflicts with -key"},
  146. {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"},
  147. {"CAkey", OPT_CAKEY, 's', "The corresponding CA key; default is -CA arg"},
  148. {"CAkeyform", OPT_CAKEYFORM, 'E',
  149. "CA key format (ENGINE, other values ignored)"},
  150. {"CAserial", OPT_CASERIAL, 's',
  151. "File that keeps track of CA-generated serial number"},
  152. {"CAcreateserial", OPT_CACREATESERIAL, '-',
  153. "Create CA serial number file if it does not exist"},
  154. OPT_SECTION("Certificate trust output"),
  155. {"trustout", OPT_TRUSTOUT, '-', "Mark certificate PEM output as trusted"},
  156. {"setalias", OPT_SETALIAS, 's', "Set certificate alias (nickname)"},
  157. {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"},
  158. {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"},
  159. {"clrreject", OPT_CLRREJECT, '-',
  160. "Clears all the prohibited or rejected uses of the certificate"},
  161. {"addreject", OPT_ADDREJECT, 's',
  162. "Reject certificate for a given purpose"},
  163. OPT_R_OPTIONS,
  164. #ifndef OPENSSL_NO_ENGINE
  165. {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
  166. #endif
  167. OPT_PROV_OPTIONS,
  168. {NULL}
  169. };
  170. static void warn_copying(ASN1_OBJECT *excluded, const char *names)
  171. {
  172. const char *sn = OBJ_nid2sn(OBJ_obj2nid(excluded));
  173. if (names != NULL && strstr(names, sn) != NULL)
  174. BIO_printf(bio_err,
  175. "Warning: -ext should not specify copying %s extension to CSR; ignoring this\n",
  176. sn);
  177. }
  178. static X509_REQ *x509_to_req(X509 *cert, int ext_copy, const char *names)
  179. {
  180. const STACK_OF(X509_EXTENSION) *cert_exts = X509_get0_extensions(cert);
  181. int i, n = sk_X509_EXTENSION_num(cert_exts /* may be NULL */);
  182. ASN1_OBJECT *skid = OBJ_nid2obj(NID_subject_key_identifier);
  183. ASN1_OBJECT *akid = OBJ_nid2obj(NID_authority_key_identifier);
  184. STACK_OF(X509_EXTENSION) *exts;
  185. X509_REQ *req = X509_to_X509_REQ(cert, NULL, NULL);
  186. if (req == NULL)
  187. return NULL;
  188. /*
  189. * Filter out SKID and AKID extensions, which make no sense in a CSR.
  190. * If names is not NULL, copy only those extensions listed there.
  191. */
  192. warn_copying(skid, names);
  193. warn_copying(akid, names);
  194. if ((exts = sk_X509_EXTENSION_new_reserve(NULL, n)) == NULL)
  195. goto err;
  196. for (i = 0; i < n; i++) {
  197. X509_EXTENSION *ex = sk_X509_EXTENSION_value(cert_exts, i);
  198. ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex);
  199. if (OBJ_cmp(obj, skid) != 0 && OBJ_cmp(obj, akid) != 0
  200. && !sk_X509_EXTENSION_push(exts, ex))
  201. goto err;
  202. }
  203. if (sk_X509_EXTENSION_num(exts) > 0) {
  204. if (ext_copy != EXT_COPY_UNSET && ext_copy != EXT_COPY_NONE
  205. && !X509_REQ_add_extensions(req, exts)) {
  206. BIO_printf(bio_err, "Error copying extensions from certificate\n");
  207. goto err;
  208. }
  209. }
  210. sk_X509_EXTENSION_free(exts);
  211. return req;
  212. err:
  213. sk_X509_EXTENSION_free(exts);
  214. X509_REQ_free(req);
  215. return NULL;
  216. }
  217. static int self_signed(X509_STORE *ctx, X509 *cert)
  218. {
  219. X509_STORE_CTX *xsc = X509_STORE_CTX_new();
  220. int ret = 0;
  221. if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, cert, NULL)) {
  222. BIO_printf(bio_err, "Error initialising X509 store\n");
  223. } else {
  224. X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
  225. ret = X509_verify_cert(xsc) > 0;
  226. }
  227. X509_STORE_CTX_free(xsc);
  228. return ret;
  229. }
  230. int x509_main(int argc, char **argv)
  231. {
  232. ASN1_INTEGER *sno = NULL;
  233. ASN1_OBJECT *objtmp = NULL;
  234. BIO *out = NULL;
  235. CONF *extconf = NULL;
  236. int ext_copy = EXT_COPY_UNSET;
  237. X509V3_CTX ext_ctx;
  238. EVP_PKEY *privkey = NULL, *CAkey = NULL, *pubkey = NULL;
  239. EVP_PKEY *pkey;
  240. int newcert = 0;
  241. char *subj = NULL, *digest = NULL;
  242. X509_NAME *fsubj = NULL;
  243. const unsigned long chtype = MBSTRING_ASC;
  244. const int multirdn = 1;
  245. STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
  246. STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
  247. X509 *x = NULL, *xca = NULL, *issuer_cert;
  248. X509_REQ *req = NULL, *rq = NULL;
  249. X509_STORE *ctx = NULL;
  250. char *CAkeyfile = NULL, *CAserial = NULL, *pubkeyfile = NULL, *alias = NULL;
  251. char *checkhost = NULL, *checkemail = NULL, *checkip = NULL;
  252. char *ext_names = NULL;
  253. char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL;
  254. char *infile = NULL, *outfile = NULL, *privkeyfile = NULL, *CAfile = NULL;
  255. char *prog;
  256. int days = UNSET_DAYS; /* not explicitly set */
  257. int x509toreq = 0, modulus = 0, print_pubkey = 0, pprint = 0;
  258. int CAformat = FORMAT_UNDEF, CAkeyformat = FORMAT_UNDEF;
  259. unsigned long dateopt = ASN1_DTFLGS_RFC822;
  260. int fingerprint = 0, reqfile = 0, checkend = 0;
  261. int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF;
  262. int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0;
  263. int noout = 0, CA_createserial = 0, email = 0;
  264. int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0;
  265. int ret = 1, i, j, num = 0, badsig = 0, clrext = 0, nocert = 0;
  266. int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0;
  267. int enddate = 0;
  268. time_t checkoffset = 0;
  269. unsigned long certflag = 0;
  270. int preserve_dates = 0;
  271. OPTION_CHOICE o;
  272. ENGINE *e = NULL;
  273. #ifndef OPENSSL_NO_MD5
  274. int subject_hash_old = 0, issuer_hash_old = 0;
  275. #endif
  276. ctx = X509_STORE_new();
  277. if (ctx == NULL)
  278. goto err;
  279. X509_STORE_set_verify_cb(ctx, callb);
  280. opt_set_unknown_name("digest");
  281. prog = opt_init(argc, argv, x509_options);
  282. while ((o = opt_next()) != OPT_EOF) {
  283. switch (o) {
  284. case OPT_EOF:
  285. case OPT_ERR:
  286. opthelp:
  287. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  288. goto err;
  289. case OPT_HELP:
  290. opt_help(x509_options);
  291. ret = 0;
  292. goto end;
  293. case OPT_INFORM:
  294. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
  295. goto opthelp;
  296. break;
  297. case OPT_IN:
  298. infile = opt_arg();
  299. break;
  300. case OPT_OUTFORM:
  301. if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
  302. goto opthelp;
  303. break;
  304. case OPT_KEYFORM:
  305. if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
  306. goto opthelp;
  307. break;
  308. case OPT_CAFORM:
  309. if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAformat))
  310. goto opthelp;
  311. break;
  312. case OPT_CAKEYFORM:
  313. if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat))
  314. goto opthelp;
  315. break;
  316. case OPT_OUT:
  317. outfile = opt_arg();
  318. break;
  319. case OPT_REQ:
  320. reqfile = 1;
  321. break;
  322. case OPT_DATEOPT:
  323. if (!set_dateopt(&dateopt, opt_arg())) {
  324. BIO_printf(bio_err,
  325. "Invalid date format: %s\n", opt_arg());
  326. goto err;
  327. }
  328. break;
  329. case OPT_COPY_EXTENSIONS:
  330. if (!set_ext_copy(&ext_copy, opt_arg())) {
  331. BIO_printf(bio_err,
  332. "Invalid extension copy option: %s\n", opt_arg());
  333. goto err;
  334. }
  335. break;
  336. case OPT_SIGOPT:
  337. if (!sigopts)
  338. sigopts = sk_OPENSSL_STRING_new_null();
  339. if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
  340. goto opthelp;
  341. break;
  342. case OPT_VFYOPT:
  343. if (!vfyopts)
  344. vfyopts = sk_OPENSSL_STRING_new_null();
  345. if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
  346. goto opthelp;
  347. break;
  348. case OPT_DAYS:
  349. days = atoi(opt_arg());
  350. if (days < -1) {
  351. BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
  352. prog);
  353. goto err;
  354. }
  355. break;
  356. case OPT_PASSIN:
  357. passinarg = opt_arg();
  358. break;
  359. case OPT_EXTFILE:
  360. extfile = opt_arg();
  361. break;
  362. case OPT_R_CASES:
  363. if (!opt_rand(o))
  364. goto end;
  365. break;
  366. case OPT_PROV_CASES:
  367. if (!opt_provider(o))
  368. goto end;
  369. break;
  370. case OPT_EXTENSIONS:
  371. extsect = opt_arg();
  372. break;
  373. case OPT_KEY:
  374. case OPT_SIGNKEY:
  375. privkeyfile = opt_arg();
  376. break;
  377. case OPT_CA:
  378. CAfile = opt_arg();
  379. break;
  380. case OPT_CAKEY:
  381. CAkeyfile = opt_arg();
  382. break;
  383. case OPT_CASERIAL:
  384. CAserial = opt_arg();
  385. break;
  386. case OPT_SET_SERIAL:
  387. if (sno != NULL) {
  388. BIO_printf(bio_err, "Serial number supplied twice\n");
  389. goto opthelp;
  390. }
  391. if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL)
  392. goto opthelp;
  393. break;
  394. case OPT_NEW:
  395. newcert = 1;
  396. break;
  397. case OPT_FORCE_PUBKEY:
  398. pubkeyfile = opt_arg();
  399. break;
  400. case OPT_SUBJ:
  401. subj = opt_arg();
  402. break;
  403. case OPT_ADDTRUST:
  404. if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL)
  405. goto end;
  406. if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
  407. BIO_printf(bio_err, "%s: Invalid trust object value %s\n",
  408. prog, opt_arg());
  409. goto opthelp;
  410. }
  411. sk_ASN1_OBJECT_push(trust, objtmp);
  412. trustout = 1;
  413. break;
  414. case OPT_ADDREJECT:
  415. if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
  416. goto end;
  417. if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
  418. BIO_printf(bio_err, "%s: Invalid reject object value %s\n",
  419. prog, opt_arg());
  420. goto opthelp;
  421. }
  422. sk_ASN1_OBJECT_push(reject, objtmp);
  423. trustout = 1;
  424. break;
  425. case OPT_SETALIAS:
  426. alias = opt_arg();
  427. trustout = 1;
  428. break;
  429. case OPT_CERTOPT:
  430. if (!set_cert_ex(&certflag, opt_arg()))
  431. goto opthelp;
  432. break;
  433. case OPT_NAMEOPT:
  434. if (!set_nameopt(opt_arg()))
  435. goto opthelp;
  436. break;
  437. case OPT_ENGINE:
  438. e = setup_engine(opt_arg(), 0);
  439. break;
  440. case OPT_EMAIL:
  441. email = ++num;
  442. break;
  443. case OPT_OCSP_URI:
  444. ocsp_uri = ++num;
  445. break;
  446. case OPT_SERIAL:
  447. serial = ++num;
  448. break;
  449. case OPT_NEXT_SERIAL:
  450. next_serial = ++num;
  451. break;
  452. case OPT_MODULUS:
  453. modulus = ++num;
  454. break;
  455. case OPT_PUBKEY:
  456. print_pubkey = ++num;
  457. break;
  458. case OPT_X509TOREQ:
  459. x509toreq = 1;
  460. break;
  461. case OPT_TEXT:
  462. text = ++num;
  463. break;
  464. case OPT_SUBJECT:
  465. subject = ++num;
  466. break;
  467. case OPT_ISSUER:
  468. issuer = ++num;
  469. break;
  470. case OPT_FINGERPRINT:
  471. fingerprint = ++num;
  472. break;
  473. case OPT_HASH:
  474. subject_hash = ++num;
  475. break;
  476. case OPT_ISSUER_HASH:
  477. issuer_hash = ++num;
  478. break;
  479. case OPT_PURPOSE:
  480. pprint = ++num;
  481. break;
  482. case OPT_STARTDATE:
  483. startdate = ++num;
  484. break;
  485. case OPT_ENDDATE:
  486. enddate = ++num;
  487. break;
  488. case OPT_NOOUT:
  489. noout = ++num;
  490. break;
  491. case OPT_EXT:
  492. ext = ++num;
  493. ext_names = opt_arg();
  494. break;
  495. case OPT_NOCERT:
  496. nocert = 1;
  497. break;
  498. case OPT_TRUSTOUT:
  499. trustout = 1;
  500. break;
  501. case OPT_CLRTRUST:
  502. clrtrust = ++num;
  503. break;
  504. case OPT_CLRREJECT:
  505. clrreject = ++num;
  506. break;
  507. case OPT_ALIAS:
  508. aliasout = ++num;
  509. break;
  510. case OPT_CACREATESERIAL:
  511. CA_createserial = 1;
  512. break;
  513. case OPT_CLREXT:
  514. clrext = 1;
  515. break;
  516. case OPT_OCSPID:
  517. ocspid = ++num;
  518. break;
  519. case OPT_BADSIG:
  520. badsig = 1;
  521. break;
  522. #ifndef OPENSSL_NO_MD5
  523. case OPT_SUBJECT_HASH_OLD:
  524. subject_hash_old = ++num;
  525. break;
  526. case OPT_ISSUER_HASH_OLD:
  527. issuer_hash_old = ++num;
  528. break;
  529. #else
  530. case OPT_SUBJECT_HASH_OLD:
  531. case OPT_ISSUER_HASH_OLD:
  532. break;
  533. #endif
  534. case OPT_DATES:
  535. startdate = ++num;
  536. enddate = ++num;
  537. break;
  538. case OPT_CHECKEND:
  539. checkend = 1;
  540. {
  541. ossl_intmax_t temp = 0;
  542. if (!opt_intmax(opt_arg(), &temp))
  543. goto opthelp;
  544. checkoffset = (time_t)temp;
  545. if ((ossl_intmax_t)checkoffset != temp) {
  546. BIO_printf(bio_err, "%s: Checkend time out of range %s\n",
  547. prog, opt_arg());
  548. goto opthelp;
  549. }
  550. }
  551. break;
  552. case OPT_CHECKHOST:
  553. checkhost = opt_arg();
  554. break;
  555. case OPT_CHECKEMAIL:
  556. checkemail = opt_arg();
  557. break;
  558. case OPT_CHECKIP:
  559. checkip = opt_arg();
  560. break;
  561. case OPT_PRESERVE_DATES:
  562. preserve_dates = 1;
  563. break;
  564. case OPT_MD:
  565. digest = opt_unknown();
  566. break;
  567. }
  568. }
  569. /* No extra arguments. */
  570. if (!opt_check_rest_arg(NULL))
  571. goto opthelp;
  572. if (!app_RAND_load())
  573. goto end;
  574. if (!opt_check_md(digest))
  575. goto opthelp;
  576. if (preserve_dates && days != UNSET_DAYS) {
  577. BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n");
  578. goto err;
  579. }
  580. if (days == UNSET_DAYS)
  581. days = DEFAULT_DAYS;
  582. if (!app_passwd(passinarg, NULL, &passin, NULL)) {
  583. BIO_printf(bio_err, "Error getting password\n");
  584. goto err;
  585. }
  586. if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(),
  587. app_get0_propq()))
  588. goto end;
  589. if (newcert && infile != NULL) {
  590. BIO_printf(bio_err, "The -in option cannot be used with -new\n");
  591. goto err;
  592. }
  593. if (newcert && reqfile) {
  594. BIO_printf(bio_err,
  595. "The -req option cannot be used with -new\n");
  596. goto err;
  597. }
  598. if (privkeyfile != NULL) {
  599. privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key");
  600. if (privkey == NULL)
  601. goto end;
  602. }
  603. if (pubkeyfile != NULL) {
  604. if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e,
  605. "explicitly set public key")) == NULL)
  606. goto end;
  607. }
  608. if (newcert) {
  609. if (subj == NULL) {
  610. BIO_printf(bio_err,
  611. "The -new option requires a subject to be set using -subj\n");
  612. goto err;
  613. }
  614. if (privkeyfile == NULL && pubkeyfile == NULL) {
  615. BIO_printf(bio_err,
  616. "The -new option requires using the -key or -force_pubkey option\n");
  617. goto err;
  618. }
  619. }
  620. if (subj != NULL
  621. && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
  622. goto end;
  623. if (CAkeyfile == NULL)
  624. CAkeyfile = CAfile;
  625. if (CAfile != NULL) {
  626. if (privkeyfile != NULL) {
  627. BIO_printf(bio_err, "Cannot use both -key/-signkey and -CA option\n");
  628. goto err;
  629. }
  630. } else {
  631. #define WARN_NO_CA(opt) BIO_printf(bio_err, \
  632. "Warning: ignoring " opt " option since -CA option is not given\n");
  633. if (CAkeyfile != NULL)
  634. WARN_NO_CA("-CAkey");
  635. if (CAkeyformat != FORMAT_UNDEF)
  636. WARN_NO_CA("-CAkeyform");
  637. if (CAformat != FORMAT_UNDEF)
  638. WARN_NO_CA("-CAform");
  639. if (CAserial != NULL)
  640. WARN_NO_CA("-CAserial");
  641. if (CA_createserial)
  642. WARN_NO_CA("-CAcreateserial");
  643. }
  644. if (extfile == NULL) {
  645. if (extsect != NULL)
  646. BIO_printf(bio_err,
  647. "Warning: ignoring -extensions option without -extfile\n");
  648. } else {
  649. X509V3_CTX ctx2;
  650. if ((extconf = app_load_config(extfile)) == NULL)
  651. goto end;
  652. if (extsect == NULL) {
  653. extsect = NCONF_get_string(extconf, "default", "extensions");
  654. if (extsect == NULL) {
  655. ERR_clear_error();
  656. extsect = "default";
  657. }
  658. }
  659. X509V3_set_ctx_test(&ctx2);
  660. X509V3_set_nconf(&ctx2, extconf);
  661. if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
  662. BIO_printf(bio_err,
  663. "Error checking extension section %s\n", extsect);
  664. goto err;
  665. }
  666. }
  667. if (reqfile) {
  668. if (infile == NULL)
  669. BIO_printf(bio_err,
  670. "Warning: Reading cert request from stdin since no -in option is given\n");
  671. req = load_csr_autofmt(infile, informat, "certificate request input");
  672. if (req == NULL)
  673. goto end;
  674. if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) {
  675. BIO_printf(bio_err, "Error unpacking public key from CSR\n");
  676. goto err;
  677. }
  678. i = do_X509_REQ_verify(req, pkey, vfyopts);
  679. if (i <= 0) {
  680. BIO_printf(bio_err, i < 0
  681. ? "Error while verifying certificate request self-signature\n"
  682. : "Certificate request self-signature did not match the contents\n");
  683. goto err;
  684. }
  685. BIO_printf(bio_err, "Certificate request self-signature ok\n");
  686. print_name(bio_err, "subject=", X509_REQ_get_subject_name(req));
  687. } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) {
  688. BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n");
  689. }
  690. if (reqfile || newcert) {
  691. if (preserve_dates)
  692. BIO_printf(bio_err,
  693. "Warning: ignoring -preserve_dates option with -req or -new\n");
  694. preserve_dates = 0;
  695. if (privkeyfile == NULL && CAkeyfile == NULL) {
  696. BIO_printf(bio_err,
  697. "We need a private key to sign with, use -key or -CAkey or -CA with private key\n");
  698. goto err;
  699. }
  700. if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
  701. goto end;
  702. if (CAfile == NULL && sno == NULL) {
  703. sno = ASN1_INTEGER_new();
  704. if (sno == NULL || !rand_serial(NULL, sno))
  705. goto end;
  706. }
  707. if (req != NULL && ext_copy != EXT_COPY_UNSET) {
  708. if (clrext && ext_copy != EXT_COPY_NONE) {
  709. BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
  710. goto err;
  711. } else if (!copy_extensions(x, req, ext_copy)) {
  712. BIO_printf(bio_err, "Error copying extensions from request\n");
  713. goto err;
  714. }
  715. }
  716. } else {
  717. if (infile == NULL)
  718. BIO_printf(bio_err,
  719. "Warning: Reading certificate from stdin since no -in option is given\n");
  720. x = load_cert_pass(infile, informat, 1, passin, "certificate");
  721. if (x == NULL)
  722. goto end;
  723. }
  724. if ((fsubj != NULL || req != NULL)
  725. && !X509_set_subject_name(x, fsubj != NULL ? fsubj :
  726. X509_REQ_get_subject_name(req)))
  727. goto end;
  728. if ((pubkey != NULL || privkey != NULL || req != NULL)
  729. && !X509_set_pubkey(x, pubkey != NULL ? pubkey :
  730. privkey != NULL ? privkey :
  731. X509_REQ_get0_pubkey(req)))
  732. goto end;
  733. if (CAfile != NULL) {
  734. xca = load_cert_pass(CAfile, CAformat, 1, passin, "CA certificate");
  735. if (xca == NULL)
  736. goto end;
  737. }
  738. out = bio_open_default(outfile, 'w', outformat);
  739. if (out == NULL)
  740. goto end;
  741. if (alias)
  742. X509_alias_set1(x, (unsigned char *)alias, -1);
  743. if (clrtrust)
  744. X509_trust_clear(x);
  745. if (clrreject)
  746. X509_reject_clear(x);
  747. if (trust != NULL) {
  748. for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++)
  749. X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i));
  750. }
  751. if (reject != NULL) {
  752. for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++)
  753. X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i));
  754. }
  755. if (clrext && ext_names != NULL)
  756. BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n");
  757. for (i = X509_get_ext_count(x) - 1; i >= 0; i--) {
  758. X509_EXTENSION *ex = X509_get_ext(x, i);
  759. const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex)));
  760. if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL))
  761. X509_EXTENSION_free(X509_delete_ext(x, i));
  762. }
  763. issuer_cert = x;
  764. if (CAfile != NULL) {
  765. issuer_cert = xca;
  766. if (sno == NULL)
  767. sno = x509_load_serial(CAfile, CAserial, CA_createserial);
  768. if (sno == NULL)
  769. goto end;
  770. if (!x509toreq && !reqfile && !newcert && !self_signed(ctx, x))
  771. goto end;
  772. } else {
  773. if (privkey != NULL && !cert_matches_key(x, privkey))
  774. BIO_printf(bio_err,
  775. "Warning: Signature key and public key of cert do not match\n");
  776. }
  777. if (sno != NULL && !X509_set_serialNumber(x, sno))
  778. goto end;
  779. if (reqfile || newcert || privkey != NULL || CAfile != NULL) {
  780. if (!preserve_dates && !set_cert_times(x, NULL, NULL, days))
  781. goto end;
  782. if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert)))
  783. goto end;
  784. }
  785. X509V3_set_ctx(&ext_ctx, issuer_cert, x, NULL, NULL, X509V3_CTX_REPLACE);
  786. /* prepare fallback for AKID, but only if issuer cert equals subject cert */
  787. if (CAfile == NULL) {
  788. if (!X509V3_set_issuer_pkey(&ext_ctx, privkey))
  789. goto end;
  790. }
  791. if (extconf != NULL && !x509toreq) {
  792. X509V3_set_nconf(&ext_ctx, extconf);
  793. if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) {
  794. BIO_printf(bio_err,
  795. "Error adding extensions from section %s\n", extsect);
  796. goto err;
  797. }
  798. }
  799. /* At this point the contents of the certificate x have been finished. */
  800. pkey = X509_get0_pubkey(x);
  801. if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) {
  802. BIO_printf(bio_err, "Error getting public key\n");
  803. goto err;
  804. }
  805. if (x509toreq) { /* also works in conjunction with -req */
  806. if (privkey == NULL) {
  807. BIO_printf(bio_err, "Must specify request signing key using -key\n");
  808. goto err;
  809. }
  810. if (clrext && ext_copy != EXT_COPY_NONE) {
  811. BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
  812. goto err;
  813. }
  814. if ((rq = x509_to_req(x, ext_copy, ext_names)) == NULL)
  815. goto end;
  816. if (extconf != NULL) {
  817. X509V3_set_nconf(&ext_ctx, extconf);
  818. if (!X509V3_EXT_REQ_add_nconf(extconf, &ext_ctx, extsect, rq)) {
  819. BIO_printf(bio_err,
  820. "Error adding request extensions from section %s\n", extsect);
  821. goto err;
  822. }
  823. }
  824. if (!do_X509_REQ_sign(rq, privkey, digest, sigopts))
  825. goto end;
  826. if (!noout) {
  827. if (outformat == FORMAT_ASN1) {
  828. X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT);
  829. i = i2d_X509_bio(out, x);
  830. } else {
  831. i = PEM_write_bio_X509_REQ(out, rq);
  832. }
  833. if (!i) {
  834. BIO_printf(bio_err,
  835. "Unable to write certificate request\n");
  836. goto err;
  837. }
  838. }
  839. noout = 1;
  840. } else if (privkey != NULL) {
  841. if (!do_X509_sign(x, privkey, digest, sigopts, &ext_ctx))
  842. goto end;
  843. } else if (CAfile != NULL) {
  844. if ((CAkey = load_key(CAkeyfile, CAkeyformat,
  845. 0, passin, e, "CA private key")) == NULL)
  846. goto end;
  847. if (!X509_check_private_key(xca, CAkey)) {
  848. BIO_printf(bio_err,
  849. "CA certificate and CA private key do not match\n");
  850. goto err;
  851. }
  852. if (!do_X509_sign(x, CAkey, digest, sigopts, &ext_ctx))
  853. goto end;
  854. }
  855. if (badsig) {
  856. const ASN1_BIT_STRING *signature;
  857. X509_get0_signature(&signature, NULL, x);
  858. corrupt_signature(signature);
  859. }
  860. /* Process print options in the given order, as indicated by index i */
  861. for (i = 1; i <= num; i++) {
  862. if (i == issuer) {
  863. print_name(out, "issuer=", X509_get_issuer_name(x));
  864. } else if (i == subject) {
  865. print_name(out, "subject=", X509_get_subject_name(x));
  866. } else if (i == serial) {
  867. BIO_printf(out, "serial=");
  868. i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x));
  869. BIO_printf(out, "\n");
  870. } else if (i == next_serial) {
  871. ASN1_INTEGER *ser;
  872. BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL);
  873. if (bnser == NULL)
  874. goto end;
  875. if (!BN_add_word(bnser, 1)
  876. || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) {
  877. BN_free(bnser);
  878. goto end;
  879. }
  880. BN_free(bnser);
  881. i2a_ASN1_INTEGER(out, ser);
  882. ASN1_INTEGER_free(ser);
  883. BIO_puts(out, "\n");
  884. } else if (i == email || i == ocsp_uri) {
  885. STACK_OF(OPENSSL_STRING) *emlst =
  886. i == email ? X509_get1_email(x) : X509_get1_ocsp(x);
  887. for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
  888. BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j));
  889. X509_email_free(emlst);
  890. } else if (i == aliasout) {
  891. unsigned char *alstr = X509_alias_get0(x, NULL);
  892. if (alstr)
  893. BIO_printf(out, "%s\n", alstr);
  894. else
  895. BIO_puts(out, "<No Alias>\n");
  896. } else if (i == subject_hash) {
  897. BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
  898. #ifndef OPENSSL_NO_MD5
  899. } else if (i == subject_hash_old) {
  900. BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
  901. #endif
  902. } else if (i == issuer_hash) {
  903. BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
  904. #ifndef OPENSSL_NO_MD5
  905. } else if (i == issuer_hash_old) {
  906. BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
  907. #endif
  908. } else if (i == pprint) {
  909. BIO_printf(out, "Certificate purposes:\n");
  910. for (j = 0; j < X509_PURPOSE_get_count(); j++)
  911. purpose_print(out, x, X509_PURPOSE_get0(j));
  912. } else if (i == modulus) {
  913. BIO_printf(out, "Modulus=");
  914. if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) {
  915. BIGNUM *n = NULL;
  916. /* Every RSA key has an 'n' */
  917. EVP_PKEY_get_bn_param(pkey, "n", &n);
  918. BN_print(out, n);
  919. BN_free(n);
  920. } else if (EVP_PKEY_is_a(pkey, "DSA")) {
  921. BIGNUM *dsapub = NULL;
  922. /* Every DSA key has a 'pub' */
  923. EVP_PKEY_get_bn_param(pkey, "pub", &dsapub);
  924. BN_print(out, dsapub);
  925. BN_free(dsapub);
  926. } else {
  927. BIO_printf(out, "No modulus for this public key type");
  928. }
  929. BIO_printf(out, "\n");
  930. } else if (i == print_pubkey) {
  931. PEM_write_bio_PUBKEY(out, pkey);
  932. } else if (i == text) {
  933. X509_print_ex(out, x, get_nameopt(), certflag);
  934. } else if (i == startdate) {
  935. BIO_puts(out, "notBefore=");
  936. ASN1_TIME_print_ex(out, X509_get0_notBefore(x), dateopt);
  937. BIO_puts(out, "\n");
  938. } else if (i == enddate) {
  939. BIO_puts(out, "notAfter=");
  940. ASN1_TIME_print_ex(out, X509_get0_notAfter(x), dateopt);
  941. BIO_puts(out, "\n");
  942. } else if (i == fingerprint) {
  943. unsigned int n;
  944. unsigned char md[EVP_MAX_MD_SIZE];
  945. const char *fdigname = digest;
  946. EVP_MD *fdig;
  947. int digres;
  948. if (fdigname == NULL)
  949. fdigname = "SHA1";
  950. if ((fdig = EVP_MD_fetch(app_get0_libctx(), fdigname,
  951. app_get0_propq())) == NULL) {
  952. BIO_printf(bio_err, "Unknown digest\n");
  953. goto err;
  954. }
  955. digres = X509_digest(x, fdig, md, &n);
  956. EVP_MD_free(fdig);
  957. if (!digres) {
  958. BIO_printf(bio_err, "Out of memory\n");
  959. goto err;
  960. }
  961. BIO_printf(out, "%s Fingerprint=", fdigname);
  962. for (j = 0; j < (int)n; j++)
  963. BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':');
  964. } else if (i == ocspid) {
  965. X509_ocspid_print(out, x);
  966. } else if (i == ext) {
  967. print_x509v3_exts(out, x, ext_names);
  968. }
  969. }
  970. if (checkend) {
  971. time_t tcheck = time(NULL) + checkoffset;
  972. ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0;
  973. if (ret)
  974. BIO_printf(out, "Certificate will expire\n");
  975. else
  976. BIO_printf(out, "Certificate will not expire\n");
  977. goto end;
  978. }
  979. if (!check_cert_attributes(out, x, checkhost, checkemail, checkip, 1))
  980. goto err;
  981. if (noout || nocert) {
  982. ret = 0;
  983. goto end;
  984. }
  985. if (outformat == FORMAT_ASN1) {
  986. i = i2d_X509_bio(out, x);
  987. } else if (outformat == FORMAT_PEM) {
  988. if (trustout)
  989. i = PEM_write_bio_X509_AUX(out, x);
  990. else
  991. i = PEM_write_bio_X509(out, x);
  992. } else {
  993. BIO_printf(bio_err, "Bad output format specified for outfile\n");
  994. goto err;
  995. }
  996. if (!i) {
  997. BIO_printf(bio_err, "Unable to write certificate\n");
  998. goto err;
  999. }
  1000. ret = 0;
  1001. goto end;
  1002. err:
  1003. ERR_print_errors(bio_err);
  1004. end:
  1005. NCONF_free(extconf);
  1006. BIO_free_all(out);
  1007. X509_STORE_free(ctx);
  1008. X509_NAME_free(fsubj);
  1009. X509_REQ_free(req);
  1010. X509_free(x);
  1011. X509_free(xca);
  1012. EVP_PKEY_free(privkey);
  1013. EVP_PKEY_free(CAkey);
  1014. EVP_PKEY_free(pubkey);
  1015. sk_OPENSSL_STRING_free(sigopts);
  1016. sk_OPENSSL_STRING_free(vfyopts);
  1017. X509_REQ_free(rq);
  1018. ASN1_INTEGER_free(sno);
  1019. sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
  1020. sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
  1021. release_engine(e);
  1022. clear_free(passin);
  1023. return ret;
  1024. }
  1025. static ASN1_INTEGER *x509_load_serial(const char *CAfile,
  1026. const char *serialfile, int create)
  1027. {
  1028. char *buf = NULL;
  1029. ASN1_INTEGER *bs = NULL;
  1030. BIGNUM *serial = NULL;
  1031. int defaultfile = 0, file_exists;
  1032. if (serialfile == NULL) {
  1033. const char *p = strrchr(CAfile, '.');
  1034. size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile);
  1035. buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer");
  1036. memcpy(buf, CAfile, len);
  1037. memcpy(buf + len, POSTFIX, sizeof(POSTFIX));
  1038. serialfile = buf;
  1039. defaultfile = 1;
  1040. }
  1041. serial = load_serial(serialfile, &file_exists, create || defaultfile, NULL);
  1042. if (serial == NULL)
  1043. goto end;
  1044. if (!BN_add_word(serial, 1)) {
  1045. BIO_printf(bio_err, "Serial number increment failure\n");
  1046. goto end;
  1047. }
  1048. if (file_exists || create)
  1049. save_serial(serialfile, NULL, serial, &bs);
  1050. else
  1051. bs = BN_to_ASN1_INTEGER(serial, NULL);
  1052. end:
  1053. OPENSSL_free(buf);
  1054. BN_free(serial);
  1055. return bs;
  1056. }
  1057. static int callb(int ok, X509_STORE_CTX *ctx)
  1058. {
  1059. int err;
  1060. X509 *err_cert;
  1061. /*
  1062. * It is ok to use a self-signed certificate. This case will catch both
  1063. * the initial ok == 0 and the final ok == 1 calls to this function.
  1064. */
  1065. err = X509_STORE_CTX_get_error(ctx);
  1066. if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
  1067. return 1;
  1068. /*
  1069. * BAD we should have gotten an error. Normally if everything worked
  1070. * X509_STORE_CTX_get_error(ctx) will still be set to
  1071. * DEPTH_ZERO_SELF_....
  1072. */
  1073. if (ok) {
  1074. BIO_printf(bio_err,
  1075. "Error with certificate to be certified - should be self-signed\n");
  1076. return 0;
  1077. } else {
  1078. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  1079. print_name(bio_err, "subject=", X509_get_subject_name(err_cert));
  1080. BIO_printf(bio_err,
  1081. "Error with certificate - error %d at depth %d\n%s\n", err,
  1082. X509_STORE_CTX_get_error_depth(ctx),
  1083. X509_verify_cert_error_string(err));
  1084. return 1;
  1085. }
  1086. }
  1087. static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
  1088. {
  1089. int id, i, idret;
  1090. const char *pname;
  1091. id = X509_PURPOSE_get_id(pt);
  1092. pname = X509_PURPOSE_get0_name(pt);
  1093. for (i = 0; i < 2; i++) {
  1094. idret = X509_check_purpose(cert, id, i);
  1095. BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
  1096. if (idret == 1)
  1097. BIO_printf(bio, "Yes\n");
  1098. else if (idret == 0)
  1099. BIO_printf(bio, "No\n");
  1100. else
  1101. BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
  1102. }
  1103. return 1;
  1104. }
  1105. static int parse_ext_names(char *names, const char **result)
  1106. {
  1107. char *p, *q;
  1108. int cnt = 0, len = 0;
  1109. p = q = names;
  1110. len = strlen(names);
  1111. while (q - names <= len) {
  1112. if (*q != ',' && *q != '\0') {
  1113. q++;
  1114. continue;
  1115. }
  1116. if (p != q) {
  1117. /* found */
  1118. if (result != NULL) {
  1119. result[cnt] = p;
  1120. *q = '\0';
  1121. }
  1122. cnt++;
  1123. }
  1124. p = ++q;
  1125. }
  1126. return cnt;
  1127. }
  1128. static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names)
  1129. {
  1130. const STACK_OF(X509_EXTENSION) *exts = NULL;
  1131. STACK_OF(X509_EXTENSION) *exts2 = NULL;
  1132. X509_EXTENSION *ext = NULL;
  1133. ASN1_OBJECT *obj;
  1134. int i, j, ret = 0, num, nn = 0;
  1135. const char *sn, **names = NULL;
  1136. char *tmp_ext_names = NULL;
  1137. exts = X509_get0_extensions(x);
  1138. if ((num = sk_X509_EXTENSION_num(exts)) <= 0) {
  1139. BIO_printf(bio_err, "No extensions in certificate\n");
  1140. ret = 1;
  1141. goto end;
  1142. }
  1143. /* parse comma separated ext name string */
  1144. if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL)
  1145. goto end;
  1146. if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) {
  1147. BIO_printf(bio, "Invalid extension names: %s\n", ext_names);
  1148. goto end;
  1149. }
  1150. if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL)
  1151. goto end;
  1152. parse_ext_names(tmp_ext_names, names);
  1153. for (i = 0; i < num; i++) {
  1154. ext = sk_X509_EXTENSION_value(exts, i);
  1155. /* check if this ext is what we want */
  1156. obj = X509_EXTENSION_get_object(ext);
  1157. sn = OBJ_nid2sn(OBJ_obj2nid(obj));
  1158. if (sn == NULL || strcmp(sn, "UNDEF") == 0)
  1159. continue;
  1160. for (j = 0; j < nn; j++) {
  1161. if (strcmp(sn, names[j]) == 0) {
  1162. /* push the extension into a new stack */
  1163. if (exts2 == NULL
  1164. && (exts2 = sk_X509_EXTENSION_new_null()) == NULL)
  1165. goto end;
  1166. if (!sk_X509_EXTENSION_push(exts2, ext))
  1167. goto end;
  1168. }
  1169. }
  1170. }
  1171. if (!sk_X509_EXTENSION_num(exts2)) {
  1172. BIO_printf(bio, "No extensions matched with %s\n", ext_names);
  1173. ret = 1;
  1174. goto end;
  1175. }
  1176. ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0);
  1177. end:
  1178. sk_X509_EXTENSION_free(exts2);
  1179. OPENSSL_free(names);
  1180. OPENSSL_free(tmp_ext_names);
  1181. return ret;
  1182. }