req.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. /*
  2. * Copyright 1995-2024 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 <time.h>
  12. #include <string.h>
  13. #include <ctype.h>
  14. #include "apps.h"
  15. #include "progs.h"
  16. #include <openssl/core_names.h>
  17. #include <openssl/bio.h>
  18. #include <openssl/evp.h>
  19. #include <openssl/conf.h>
  20. #include <openssl/err.h>
  21. #include <openssl/asn1.h>
  22. #include <openssl/x509.h>
  23. #include <openssl/x509v3.h>
  24. #include <openssl/objects.h>
  25. #include <openssl/pem.h>
  26. #include <openssl/bn.h>
  27. #include <openssl/lhash.h>
  28. #include <openssl/rsa.h>
  29. #ifndef OPENSSL_NO_DSA
  30. # include <openssl/dsa.h>
  31. #endif
  32. #define BITS "default_bits"
  33. #define KEYFILE "default_keyfile"
  34. #define PROMPT "prompt"
  35. #define DISTINGUISHED_NAME "distinguished_name"
  36. #define ATTRIBUTES "attributes"
  37. #define V3_EXTENSIONS "x509_extensions"
  38. #define REQ_EXTENSIONS "req_extensions"
  39. #define STRING_MASK "string_mask"
  40. #define UTF8_IN "utf8"
  41. #define DEFAULT_KEY_LENGTH 2048
  42. #define MIN_KEY_LENGTH 512
  43. #define DEFAULT_DAYS 30 /* default cert validity period in days */
  44. #define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */
  45. #define EXT_COPY_UNSET -1
  46. static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
  47. int mutlirdn, int attribs, unsigned long chtype);
  48. static int prompt_info(X509_REQ *req,
  49. STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
  50. STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
  51. int attribs, unsigned long chtype);
  52. static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
  53. STACK_OF(CONF_VALUE) *attr, int attribs,
  54. unsigned long chtype);
  55. static int add_attribute_object(X509_REQ *req, char *text, const char *def,
  56. char *value, int nid, int n_min, int n_max,
  57. unsigned long chtype);
  58. static int add_DN_object(X509_NAME *n, char *text, const char *def,
  59. char *value, int nid, int n_min, int n_max,
  60. unsigned long chtype, int mval);
  61. static int build_data(char *text, const char *def, char *value,
  62. int n_min, int n_max, char *buf, const int buf_size,
  63. const char *desc1, const char *desc2);
  64. static int req_check_len(int len, int n_min, int n_max);
  65. static int check_end(const char *str, const char *end);
  66. static int join(char buf[], size_t buf_size, const char *name,
  67. const char *tail, const char *desc);
  68. static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
  69. char **pkeytype, long *pkeylen,
  70. ENGINE *keygen_engine);
  71. static const char *section = "req";
  72. static CONF *req_conf = NULL;
  73. static CONF *addext_conf = NULL;
  74. static int batch = 0;
  75. typedef enum OPTION_choice {
  76. OPT_COMMON,
  77. OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
  78. OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
  79. OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
  80. OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
  81. OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
  82. OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT,
  83. OPT_X509, OPT_X509V1, OPT_CA, OPT_CAKEY,
  84. OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
  85. OPT_COPY_EXTENSIONS, OPT_EXTENSIONS, OPT_REQEXTS, OPT_ADDEXT,
  86. OPT_PRECERT, OPT_MD,
  87. OPT_SECTION, OPT_QUIET,
  88. OPT_R_ENUM, OPT_PROV_ENUM
  89. } OPTION_CHOICE;
  90. const OPTIONS req_options[] = {
  91. OPT_SECTION("General"),
  92. {"help", OPT_HELP, '-', "Display this summary"},
  93. #ifndef OPENSSL_NO_ENGINE
  94. {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
  95. {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
  96. "Specify engine to be used for key generation operations"},
  97. #endif
  98. {"in", OPT_IN, '<', "X.509 request input file (default stdin)"},
  99. {"inform", OPT_INFORM, 'F',
  100. "CSR input format to use (PEM or DER; by default try PEM first)"},
  101. {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
  102. OPT_SECTION("Certificate"),
  103. {"new", OPT_NEW, '-', "New request"},
  104. {"config", OPT_CONFIG, '<', "Request template file"},
  105. {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
  106. {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
  107. {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
  108. {"reqopt", OPT_REQOPT, 's', "Various request text options"},
  109. {"text", OPT_TEXT, '-', "Text form of request"},
  110. {"x509", OPT_X509, '-',
  111. "Output an X.509 certificate structure instead of a cert request"},
  112. {"x509v1", OPT_X509V1, '-', "Request cert generation with X.509 version 1"},
  113. {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"},
  114. {"CAkey", OPT_CAKEY, 's',
  115. "Issuer private key to use with -CA; default is -CA arg"},
  116. {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
  117. {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
  118. {"subject", OPT_SUBJECT, '-',
  119. "Print the subject of the output request or cert"},
  120. {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
  121. "Deprecated; multi-valued RDNs support is always on."},
  122. {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
  123. {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
  124. {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
  125. "copy extensions from request when using -x509"},
  126. {"extensions", OPT_EXTENSIONS, 's',
  127. "Cert or request extension section (override value in config file)"},
  128. {"reqexts", OPT_REQEXTS, 's', "An alias for -extensions"},
  129. {"addext", OPT_ADDEXT, 's',
  130. "Additional cert extension key=value pair (may be given more than once)"},
  131. {"precert", OPT_PRECERT, '-', "Add a poison extension to generated cert (implies -new)"},
  132. OPT_SECTION("Keys and Signing"),
  133. {"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"},
  134. {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
  135. {"pubkey", OPT_PUBKEY, '-', "Output public key"},
  136. {"keyout", OPT_KEYOUT, '>', "File to write private key to"},
  137. {"passin", OPT_PASSIN, 's', "Private key and certificate password source"},
  138. {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
  139. {"newkey", OPT_NEWKEY, 's',
  140. "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"},
  141. {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
  142. {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
  143. {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
  144. {"", OPT_MD, '-', "Any supported digest"},
  145. OPT_SECTION("Output"),
  146. {"out", OPT_OUT, '>', "Output file"},
  147. {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
  148. {"batch", OPT_BATCH, '-',
  149. "Do not ask anything during request generation"},
  150. {"verbose", OPT_VERBOSE, '-', "Verbose output"},
  151. {"quiet", OPT_QUIET, '-', "Terse output"},
  152. {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
  153. {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
  154. {"noout", OPT_NOOUT, '-', "Do not output REQ"},
  155. {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
  156. {"modulus", OPT_MODULUS, '-', "RSA modulus"},
  157. OPT_R_OPTIONS,
  158. OPT_PROV_OPTIONS,
  159. {NULL}
  160. };
  161. /*
  162. * An LHASH of strings, where each string is an extension name.
  163. */
  164. static unsigned long ext_name_hash(const OPENSSL_STRING *a)
  165. {
  166. return OPENSSL_LH_strhash((const char *)a);
  167. }
  168. static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
  169. {
  170. return strcmp((const char *)a, (const char *)b);
  171. }
  172. static void exts_cleanup(OPENSSL_STRING *x)
  173. {
  174. OPENSSL_free((char *)x);
  175. }
  176. /*
  177. * Is the |kv| key already duplicated?
  178. * Return 0 if unique, -1 on runtime error, -2 on syntax error; 1 if found.
  179. */
  180. static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
  181. {
  182. char *p;
  183. size_t off;
  184. /* Check syntax. */
  185. /* Skip leading whitespace, make a copy. */
  186. while (isspace(_UC(*kv)))
  187. kv++;
  188. if ((p = strchr(kv, '=')) == NULL) {
  189. BIO_printf(bio_err, "Parse error on -addext: missing '='\n");
  190. return -2;
  191. }
  192. off = p - kv;
  193. if ((kv = OPENSSL_strdup(kv)) == NULL)
  194. return -1;
  195. /* Skip trailing space before the equal sign. */
  196. for (p = kv + off; p > kv; --p)
  197. if (!isspace(_UC(p[-1])))
  198. break;
  199. if (p == kv) {
  200. BIO_printf(bio_err, "Parse error on -addext: missing key\n");
  201. OPENSSL_free(kv);
  202. return -2;
  203. }
  204. *p = '\0';
  205. /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
  206. p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
  207. if (p != NULL) {
  208. BIO_printf(bio_err, "Duplicate extension name: %s\n", kv);
  209. OPENSSL_free(p);
  210. return 1;
  211. } else if (lh_OPENSSL_STRING_error(addexts)) {
  212. OPENSSL_free(kv);
  213. return -1;
  214. }
  215. return 0;
  216. }
  217. int req_main(int argc, char **argv)
  218. {
  219. ASN1_INTEGER *serial = NULL;
  220. BIO *out = NULL;
  221. ENGINE *e = NULL, *gen_eng = NULL;
  222. EVP_PKEY *pkey = NULL, *CAkey = NULL;
  223. EVP_PKEY_CTX *genctx = NULL;
  224. STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
  225. LHASH_OF(OPENSSL_STRING) *addexts = NULL;
  226. X509 *new_x509 = NULL, *CAcert = NULL;
  227. X509_REQ *req = NULL;
  228. EVP_CIPHER *cipher = NULL;
  229. int ext_copy = EXT_COPY_UNSET;
  230. BIO *addext_bio = NULL;
  231. char *extsect = NULL;
  232. const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
  233. char *outfile = NULL, *keyfile = NULL, *digest = NULL;
  234. char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
  235. char *passin = NULL, *passout = NULL;
  236. char *nofree_passin = NULL, *nofree_passout = NULL;
  237. char *subj = NULL;
  238. X509_NAME *fsubj = NULL;
  239. char *template = default_config_file, *keyout = NULL;
  240. const char *keyalg = NULL;
  241. OPTION_CHOICE o;
  242. int days = UNSET_DAYS;
  243. int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0, progress = 1;
  244. int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF;
  245. int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
  246. int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0, x509v1 = 0;
  247. long newkey_len = -1;
  248. unsigned long chtype = MBSTRING_ASC, reqflag = 0;
  249. #ifndef OPENSSL_NO_DES
  250. cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
  251. #endif
  252. opt_set_unknown_name("digest");
  253. prog = opt_init(argc, argv, req_options);
  254. while ((o = opt_next()) != OPT_EOF) {
  255. switch (o) {
  256. case OPT_EOF:
  257. case OPT_ERR:
  258. opthelp:
  259. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  260. goto end;
  261. case OPT_HELP:
  262. opt_help(req_options);
  263. ret = 0;
  264. goto end;
  265. case OPT_INFORM:
  266. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
  267. goto opthelp;
  268. break;
  269. case OPT_OUTFORM:
  270. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
  271. goto opthelp;
  272. break;
  273. case OPT_ENGINE:
  274. e = setup_engine(opt_arg(), 0);
  275. break;
  276. case OPT_KEYGEN_ENGINE:
  277. #ifndef OPENSSL_NO_ENGINE
  278. gen_eng = setup_engine(opt_arg(), 0);
  279. if (gen_eng == NULL) {
  280. BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
  281. goto opthelp;
  282. }
  283. #endif
  284. break;
  285. case OPT_KEY:
  286. keyfile = opt_arg();
  287. break;
  288. case OPT_PUBKEY:
  289. pubkey = 1;
  290. break;
  291. case OPT_NEW:
  292. newreq = 1;
  293. break;
  294. case OPT_CONFIG:
  295. template = opt_arg();
  296. break;
  297. case OPT_SECTION:
  298. section = opt_arg();
  299. break;
  300. case OPT_KEYFORM:
  301. if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
  302. goto opthelp;
  303. break;
  304. case OPT_IN:
  305. infile = opt_arg();
  306. break;
  307. case OPT_OUT:
  308. outfile = opt_arg();
  309. break;
  310. case OPT_KEYOUT:
  311. keyout = opt_arg();
  312. break;
  313. case OPT_PASSIN:
  314. passargin = opt_arg();
  315. break;
  316. case OPT_PASSOUT:
  317. passargout = opt_arg();
  318. break;
  319. case OPT_R_CASES:
  320. if (!opt_rand(o))
  321. goto end;
  322. break;
  323. case OPT_PROV_CASES:
  324. if (!opt_provider(o))
  325. goto end;
  326. break;
  327. case OPT_NEWKEY:
  328. keyalg = opt_arg();
  329. newreq = 1;
  330. break;
  331. case OPT_PKEYOPT:
  332. if (pkeyopts == NULL)
  333. pkeyopts = sk_OPENSSL_STRING_new_null();
  334. if (pkeyopts == NULL
  335. || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
  336. goto opthelp;
  337. break;
  338. case OPT_SIGOPT:
  339. if (!sigopts)
  340. sigopts = sk_OPENSSL_STRING_new_null();
  341. if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
  342. goto opthelp;
  343. break;
  344. case OPT_VFYOPT:
  345. if (!vfyopts)
  346. vfyopts = sk_OPENSSL_STRING_new_null();
  347. if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
  348. goto opthelp;
  349. break;
  350. case OPT_BATCH:
  351. batch = 1;
  352. break;
  353. case OPT_NEWHDR:
  354. newhdr = 1;
  355. break;
  356. case OPT_MODULUS:
  357. modulus = 1;
  358. break;
  359. case OPT_VERIFY:
  360. verify = 1;
  361. break;
  362. case OPT_NODES:
  363. case OPT_NOENC:
  364. noenc = 1;
  365. break;
  366. case OPT_NOOUT:
  367. noout = 1;
  368. break;
  369. case OPT_VERBOSE:
  370. verbose = 1;
  371. progress = 1;
  372. break;
  373. case OPT_QUIET:
  374. verbose = 0;
  375. progress = 0;
  376. break;
  377. case OPT_UTF8:
  378. chtype = MBSTRING_UTF8;
  379. break;
  380. case OPT_NAMEOPT:
  381. if (!set_nameopt(opt_arg()))
  382. goto opthelp;
  383. break;
  384. case OPT_REQOPT:
  385. if (!set_cert_ex(&reqflag, opt_arg()))
  386. goto opthelp;
  387. break;
  388. case OPT_TEXT:
  389. text = 1;
  390. break;
  391. case OPT_X509V1:
  392. x509v1 = 1;
  393. /* fall thru */
  394. case OPT_X509:
  395. gen_x509 = 1;
  396. break;
  397. case OPT_CA:
  398. CAfile = opt_arg();
  399. gen_x509 = 1;
  400. break;
  401. case OPT_CAKEY:
  402. CAkeyfile = opt_arg();
  403. break;
  404. case OPT_DAYS:
  405. days = atoi(opt_arg());
  406. if (days < -1) {
  407. BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
  408. prog);
  409. goto end;
  410. }
  411. break;
  412. case OPT_SET_SERIAL:
  413. if (serial != NULL) {
  414. BIO_printf(bio_err, "Serial number supplied twice\n");
  415. goto opthelp;
  416. }
  417. serial = s2i_ASN1_INTEGER(NULL, opt_arg());
  418. if (serial == NULL)
  419. goto opthelp;
  420. break;
  421. case OPT_SUBJECT:
  422. subject = 1;
  423. break;
  424. case OPT_SUBJ:
  425. subj = opt_arg();
  426. break;
  427. case OPT_MULTIVALUE_RDN:
  428. /* obsolete */
  429. break;
  430. case OPT_COPY_EXTENSIONS:
  431. if (!set_ext_copy(&ext_copy, opt_arg())) {
  432. BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
  433. opt_arg());
  434. goto end;
  435. }
  436. break;
  437. case OPT_EXTENSIONS:
  438. case OPT_REQEXTS:
  439. extsect = opt_arg();
  440. break;
  441. case OPT_ADDEXT:
  442. p = opt_arg();
  443. if (addexts == NULL) {
  444. addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
  445. addext_bio = BIO_new(BIO_s_mem());
  446. if (addexts == NULL || addext_bio == NULL)
  447. goto end;
  448. }
  449. i = duplicated(addexts, p);
  450. if (i == 1)
  451. goto opthelp;
  452. if (i == -1)
  453. BIO_printf(bio_err, "Internal error handling -addext %s\n", p);
  454. if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
  455. goto end;
  456. break;
  457. case OPT_PRECERT:
  458. newreq = precert = 1;
  459. break;
  460. case OPT_MD:
  461. digest = opt_unknown();
  462. break;
  463. }
  464. }
  465. /* No extra arguments. */
  466. if (!opt_check_rest_arg(NULL))
  467. goto opthelp;
  468. if (!app_RAND_load())
  469. goto end;
  470. if (!gen_x509) {
  471. if (days != UNSET_DAYS)
  472. BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
  473. if (ext_copy == EXT_COPY_NONE)
  474. BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
  475. }
  476. if (infile == NULL) {
  477. if (gen_x509)
  478. newreq = 1;
  479. else if (!newreq)
  480. BIO_printf(bio_err,
  481. "Warning: Will read cert request from stdin since no -in option is given\n");
  482. }
  483. if (!app_passwd(passargin, passargout, &passin, &passout)) {
  484. BIO_printf(bio_err, "Error getting passwords\n");
  485. goto end;
  486. }
  487. if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
  488. goto end;
  489. if (addext_bio != NULL) {
  490. if (verbose)
  491. BIO_printf(bio_err,
  492. "Using additional configuration from -addext options\n");
  493. if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
  494. goto end;
  495. }
  496. if (template != default_config_file && !app_load_modules(req_conf))
  497. goto end;
  498. if (req_conf != NULL) {
  499. p = app_conf_try_string(req_conf, NULL, "oid_file");
  500. if (p != NULL) {
  501. BIO *oid_bio = BIO_new_file(p, "r");
  502. if (oid_bio == NULL) {
  503. if (verbose)
  504. BIO_printf(bio_err,
  505. "Problems opening '%s' for extra OIDs\n", p);
  506. } else {
  507. OBJ_create_objects(oid_bio);
  508. BIO_free(oid_bio);
  509. }
  510. }
  511. }
  512. if (!add_oid_section(req_conf))
  513. goto end;
  514. /* Check that any specified digest is fetchable */
  515. if (digest != NULL) {
  516. if (!opt_check_md(digest))
  517. goto opthelp;
  518. } else {
  519. /* No digest specified, default to configuration */
  520. p = app_conf_try_string(req_conf, section, "default_md");
  521. if (p != NULL)
  522. digest = p;
  523. }
  524. if (extsect == NULL)
  525. extsect = app_conf_try_string(req_conf, section,
  526. gen_x509 ? V3_EXTENSIONS : REQ_EXTENSIONS);
  527. if (extsect != NULL) {
  528. /* Check syntax of extension section in config file */
  529. X509V3_CTX ctx;
  530. X509V3_set_ctx_test(&ctx);
  531. X509V3_set_nconf(&ctx, req_conf);
  532. if (!X509V3_EXT_add_nconf(req_conf, &ctx, extsect, NULL)) {
  533. BIO_printf(bio_err,
  534. "Error checking %s extension section %s\n",
  535. gen_x509 ? "x509" : "request", extsect);
  536. goto end;
  537. }
  538. }
  539. if (addext_conf != NULL) {
  540. /* Check syntax of command line extensions */
  541. X509V3_CTX ctx;
  542. X509V3_set_ctx_test(&ctx);
  543. X509V3_set_nconf(&ctx, req_conf);
  544. if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
  545. BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
  546. goto end;
  547. }
  548. }
  549. if (passin == NULL)
  550. passin = nofree_passin =
  551. app_conf_try_string(req_conf, section, "input_password");
  552. if (passout == NULL)
  553. passout = nofree_passout =
  554. app_conf_try_string(req_conf, section, "output_password");
  555. p = app_conf_try_string(req_conf, section, STRING_MASK);
  556. if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
  557. BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
  558. goto end;
  559. }
  560. if (chtype != MBSTRING_UTF8) {
  561. p = app_conf_try_string(req_conf, section, UTF8_IN);
  562. if (p != NULL && strcmp(p, "yes") == 0)
  563. chtype = MBSTRING_UTF8;
  564. }
  565. if (keyfile != NULL) {
  566. pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
  567. if (pkey == NULL)
  568. goto end;
  569. app_RAND_load_conf(req_conf, section);
  570. }
  571. if (keyalg != NULL && pkey != NULL) {
  572. BIO_printf(bio_err,
  573. "Warning: Not generating key via given -newkey option since -key is given\n");
  574. /* Better throw an error in this case */
  575. }
  576. if (newreq && pkey == NULL) {
  577. app_RAND_load_conf(req_conf, section);
  578. if (!app_conf_try_number(req_conf, section, BITS, &newkey_len))
  579. newkey_len = DEFAULT_KEY_LENGTH;
  580. genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
  581. if (genctx == NULL)
  582. goto end;
  583. if (newkey_len < MIN_KEY_LENGTH
  584. && (EVP_PKEY_CTX_is_a(genctx, "RSA")
  585. || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
  586. || EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
  587. BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
  588. MIN_KEY_LENGTH, newkey_len);
  589. goto end;
  590. }
  591. if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
  592. && (EVP_PKEY_CTX_is_a(genctx, "RSA")
  593. || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
  594. BIO_printf(bio_err,
  595. "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
  596. " Your key size is %ld! Larger key size may behave not as expected.\n",
  597. OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
  598. #ifndef OPENSSL_NO_DSA
  599. if (EVP_PKEY_CTX_is_a(genctx, "DSA")
  600. && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
  601. BIO_printf(bio_err,
  602. "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
  603. " Your key size is %ld! Larger key size may behave not as expected.\n",
  604. OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
  605. #endif
  606. if (pkeyopts != NULL) {
  607. char *genopt;
  608. for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
  609. genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
  610. if (pkey_ctrl_string(genctx, genopt) <= 0) {
  611. BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
  612. goto end;
  613. }
  614. }
  615. }
  616. EVP_PKEY_CTX_set_app_data(genctx, bio_err);
  617. if (progress)
  618. EVP_PKEY_CTX_set_cb(genctx, progress_cb);
  619. pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
  620. if (pkey == NULL)
  621. goto end;
  622. EVP_PKEY_CTX_free(genctx);
  623. genctx = NULL;
  624. }
  625. if (keyout == NULL && keyfile == NULL)
  626. keyout = app_conf_try_string(req_conf, section, KEYFILE);
  627. if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
  628. if (verbose) {
  629. BIO_printf(bio_err, "Writing private key to ");
  630. if (keyout == NULL)
  631. BIO_printf(bio_err, "stdout\n");
  632. else
  633. BIO_printf(bio_err, "'%s'\n", keyout);
  634. }
  635. out = bio_open_owner(keyout, outformat, newreq);
  636. if (out == NULL)
  637. goto end;
  638. p = app_conf_try_string(req_conf, section, "encrypt_rsa_key");
  639. if (p == NULL)
  640. p = app_conf_try_string(req_conf, section, "encrypt_key");
  641. if (p != NULL && strcmp(p, "no") == 0)
  642. cipher = NULL;
  643. if (noenc)
  644. cipher = NULL;
  645. i = 0;
  646. loop:
  647. if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
  648. NULL, 0, NULL, passout)) {
  649. if ((ERR_GET_REASON(ERR_peek_error()) ==
  650. PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
  651. ERR_clear_error();
  652. i++;
  653. goto loop;
  654. }
  655. goto end;
  656. }
  657. BIO_free_all(out);
  658. out = NULL;
  659. BIO_printf(bio_err, "-----\n");
  660. }
  661. /*
  662. * subj is expected to be in the format /type0=value0/type1=value1/type2=...
  663. * where characters may be escaped by \
  664. */
  665. if (subj != NULL
  666. && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
  667. goto end;
  668. if (!newreq) {
  669. if (keyfile != NULL)
  670. BIO_printf(bio_err,
  671. "Warning: Not placing -key in cert or request since request is used\n");
  672. req = load_csr_autofmt(infile /* if NULL, reads from stdin */,
  673. informat, vfyopts, "X509 request");
  674. if (req == NULL)
  675. goto end;
  676. } else if (infile != NULL) {
  677. BIO_printf(bio_err,
  678. "Warning: Ignoring -in option since -new or -newkey or -precert is given\n");
  679. /* Better throw an error in this case, as done in the x509 app */
  680. }
  681. if (CAkeyfile == NULL)
  682. CAkeyfile = CAfile;
  683. if (CAkeyfile != NULL) {
  684. if (CAfile == NULL) {
  685. BIO_printf(bio_err,
  686. "Warning: Ignoring -CAkey option since no -CA option is given\n");
  687. } else {
  688. if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
  689. 0, passin, e,
  690. CAkeyfile != CAfile
  691. ? "issuer private key from -CAkey arg"
  692. : "issuer private key from -CA arg")) == NULL)
  693. goto end;
  694. }
  695. }
  696. if (CAfile != NULL) {
  697. if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
  698. "issuer cert from -CA arg")) == NULL)
  699. goto end;
  700. if (!X509_check_private_key(CAcert, CAkey)) {
  701. BIO_printf(bio_err,
  702. "Issuer CA certificate and key do not match\n");
  703. goto end;
  704. }
  705. }
  706. if (newreq || gen_x509) {
  707. if (CAcert == NULL && pkey == NULL) {
  708. BIO_printf(bio_err, "Must provide a signature key using -key or"
  709. " provide -CA / -CAkey\n");
  710. goto end;
  711. }
  712. if (req == NULL) {
  713. req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
  714. if (req == NULL) {
  715. goto end;
  716. }
  717. if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)) {
  718. BIO_printf(bio_err, "Error making certificate request\n");
  719. goto end;
  720. }
  721. /* Note that -x509 can take over -key and -subj option values. */
  722. }
  723. if (gen_x509) {
  724. EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
  725. EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
  726. X509V3_CTX ext_ctx;
  727. X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
  728. X509_REQ_get_subject_name(req);
  729. X509_NAME *n_subj = fsubj != NULL ? fsubj :
  730. X509_REQ_get_subject_name(req);
  731. if (CAcert != NULL && keyfile != NULL)
  732. BIO_printf(bio_err,
  733. "Warning: Not using -key or -newkey for signing since -CA option is given\n");
  734. if ((new_x509 = X509_new_ex(app_get0_libctx(),
  735. app_get0_propq())) == NULL)
  736. goto end;
  737. if (serial != NULL) {
  738. if (!X509_set_serialNumber(new_x509, serial))
  739. goto end;
  740. } else {
  741. if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
  742. goto end;
  743. }
  744. if (!X509_set_issuer_name(new_x509, issuer))
  745. goto end;
  746. if (days == UNSET_DAYS) {
  747. days = DEFAULT_DAYS;
  748. }
  749. if (!set_cert_times(new_x509, NULL, NULL, days))
  750. goto end;
  751. if (!X509_set_subject_name(new_x509, n_subj))
  752. goto end;
  753. if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
  754. goto end;
  755. if (ext_copy == EXT_COPY_UNSET) {
  756. if (infile != NULL)
  757. BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
  758. } else if (!copy_extensions(new_x509, req, ext_copy)) {
  759. BIO_printf(bio_err, "Error copying extensions from request\n");
  760. goto end;
  761. }
  762. /* Set up V3 context struct */
  763. X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
  764. new_x509, NULL, NULL, X509V3_CTX_REPLACE);
  765. /* prepare fallback for AKID, but only if issuer cert == new_x509 */
  766. if (CAcert == NULL) {
  767. if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
  768. goto end;
  769. if (!cert_matches_key(new_x509, issuer_key))
  770. BIO_printf(bio_err,
  771. "Warning: Signature key and public key of cert do not match\n");
  772. }
  773. X509V3_set_nconf(&ext_ctx, req_conf);
  774. /* Add extensions */
  775. if (extsect != NULL
  776. && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extsect, new_x509)) {
  777. BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
  778. extsect);
  779. goto end;
  780. }
  781. if (addext_conf != NULL
  782. && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
  783. new_x509)) {
  784. BIO_printf(bio_err, "Error adding x509 extensions defined via -addext\n");
  785. goto end;
  786. }
  787. /* If a pre-cert was requested, we need to add a poison extension */
  788. if (precert) {
  789. if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
  790. NULL, 1, 0) != 1) {
  791. BIO_printf(bio_err, "Error adding poison extension\n");
  792. goto end;
  793. }
  794. }
  795. i = do_X509_sign(new_x509, x509v1, issuer_key, digest, sigopts,
  796. &ext_ctx);
  797. if (!i)
  798. goto end;
  799. } else {
  800. X509V3_CTX ext_ctx;
  801. if (precert) {
  802. BIO_printf(bio_err,
  803. "Warning: Ignoring -precert flag since no cert is produced\n");
  804. }
  805. /* Set up V3 context struct */
  806. X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, X509V3_CTX_REPLACE);
  807. X509V3_set_nconf(&ext_ctx, req_conf);
  808. /* Add extensions */
  809. if (extsect != NULL
  810. && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, extsect, req)) {
  811. BIO_printf(bio_err, "Error adding request extensions from section %s\n",
  812. extsect);
  813. goto end;
  814. }
  815. if (addext_conf != NULL
  816. && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
  817. req)) {
  818. BIO_printf(bio_err, "Error adding request extensions defined via -addext\n");
  819. goto end;
  820. }
  821. i = do_X509_REQ_sign(req, pkey, digest, sigopts);
  822. if (!i)
  823. goto end;
  824. }
  825. }
  826. if (subj != NULL && !newreq && !gen_x509) {
  827. if (verbose) {
  828. BIO_printf(out, "Modifying subject of certificate request\n");
  829. print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
  830. }
  831. if (!X509_REQ_set_subject_name(req, fsubj)) {
  832. BIO_printf(bio_err, "Error modifying subject of certificate request\n");
  833. goto end;
  834. }
  835. if (verbose) {
  836. print_name(out, "New subject=", X509_REQ_get_subject_name(req));
  837. }
  838. }
  839. if (verify) {
  840. EVP_PKEY *tpubkey = pkey;
  841. if (tpubkey == NULL) {
  842. tpubkey = X509_REQ_get0_pubkey(req);
  843. if (tpubkey == NULL)
  844. goto end;
  845. }
  846. i = do_X509_REQ_verify(req, tpubkey, vfyopts);
  847. if (i < 0)
  848. goto end;
  849. if (i == 0)
  850. BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
  851. else /* i > 0 */
  852. BIO_printf(bio_out, "Certificate request self-signature verify OK\n");
  853. }
  854. if (noout && !text && !modulus && !subject && !pubkey) {
  855. ret = 0;
  856. goto end;
  857. }
  858. out = bio_open_default(outfile,
  859. keyout != NULL && outfile != NULL &&
  860. strcmp(keyout, outfile) == 0 ? 'a' : 'w',
  861. outformat);
  862. if (out == NULL)
  863. goto end;
  864. if (pubkey) {
  865. EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
  866. if (tpubkey == NULL) {
  867. BIO_printf(bio_err, "Error getting public key\n");
  868. goto end;
  869. }
  870. PEM_write_bio_PUBKEY(out, tpubkey);
  871. }
  872. if (text) {
  873. if (gen_x509)
  874. ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
  875. else
  876. ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
  877. if (ret == 0) {
  878. if (gen_x509)
  879. BIO_printf(bio_err, "Error printing certificate\n");
  880. else
  881. BIO_printf(bio_err, "Error printing certificate request\n");
  882. goto end;
  883. }
  884. }
  885. if (subject) {
  886. print_name(out, "subject=", gen_x509
  887. ? X509_get_subject_name(new_x509)
  888. : X509_REQ_get_subject_name(req));
  889. }
  890. if (modulus) {
  891. EVP_PKEY *tpubkey;
  892. if (gen_x509)
  893. tpubkey = X509_get0_pubkey(new_x509);
  894. else
  895. tpubkey = X509_REQ_get0_pubkey(req);
  896. if (tpubkey == NULL) {
  897. BIO_puts(bio_err, "Modulus is unavailable\n");
  898. goto end;
  899. }
  900. BIO_puts(out, "Modulus=");
  901. if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) {
  902. BIGNUM *n = NULL;
  903. if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
  904. goto end;
  905. BN_print(out, n);
  906. BN_free(n);
  907. } else {
  908. BIO_puts(out, "Wrong Algorithm type");
  909. }
  910. BIO_puts(out, "\n");
  911. }
  912. if (!noout && !gen_x509) {
  913. if (outformat == FORMAT_ASN1)
  914. i = i2d_X509_REQ_bio(out, req);
  915. else if (newhdr)
  916. i = PEM_write_bio_X509_REQ_NEW(out, req);
  917. else
  918. i = PEM_write_bio_X509_REQ(out, req);
  919. if (!i) {
  920. BIO_printf(bio_err, "Unable to write certificate request\n");
  921. goto end;
  922. }
  923. }
  924. if (!noout && gen_x509 && new_x509 != NULL) {
  925. if (outformat == FORMAT_ASN1)
  926. i = i2d_X509_bio(out, new_x509);
  927. else
  928. i = PEM_write_bio_X509(out, new_x509);
  929. if (!i) {
  930. BIO_printf(bio_err, "Unable to write X509 certificate\n");
  931. goto end;
  932. }
  933. }
  934. ret = 0;
  935. end:
  936. if (ret) {
  937. ERR_print_errors(bio_err);
  938. }
  939. NCONF_free(req_conf);
  940. NCONF_free(addext_conf);
  941. BIO_free(addext_bio);
  942. BIO_free_all(out);
  943. EVP_PKEY_free(pkey);
  944. EVP_PKEY_CTX_free(genctx);
  945. sk_OPENSSL_STRING_free(pkeyopts);
  946. sk_OPENSSL_STRING_free(sigopts);
  947. sk_OPENSSL_STRING_free(vfyopts);
  948. lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
  949. lh_OPENSSL_STRING_free(addexts);
  950. #ifndef OPENSSL_NO_ENGINE
  951. release_engine(gen_eng);
  952. #endif
  953. OPENSSL_free(keyalgstr);
  954. X509_REQ_free(req);
  955. X509_NAME_free(fsubj);
  956. X509_free(new_x509);
  957. X509_free(CAcert);
  958. EVP_PKEY_free(CAkey);
  959. ASN1_INTEGER_free(serial);
  960. release_engine(e);
  961. if (passin != nofree_passin)
  962. OPENSSL_free(passin);
  963. if (passout != nofree_passout)
  964. OPENSSL_free(passout);
  965. return ret;
  966. }
  967. static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
  968. int multirdn, int attribs, unsigned long chtype)
  969. {
  970. int ret = 0, i;
  971. char no_prompt = 0;
  972. STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
  973. char *tmp, *dn_sect, *attr_sect;
  974. tmp = app_conf_try_string(req_conf, section, PROMPT);
  975. if (tmp != NULL && strcmp(tmp, "no") == 0)
  976. no_prompt = 1;
  977. dn_sect = app_conf_try_string(req_conf, section, DISTINGUISHED_NAME);
  978. if (dn_sect != NULL) {
  979. dn_sk = NCONF_get_section(req_conf, dn_sect);
  980. if (dn_sk == NULL) {
  981. BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
  982. goto err;
  983. }
  984. }
  985. attr_sect = app_conf_try_string(req_conf, section, ATTRIBUTES);
  986. if (attr_sect != NULL) {
  987. attr_sk = NCONF_get_section(req_conf, attr_sect);
  988. if (attr_sk == NULL) {
  989. BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
  990. goto err;
  991. }
  992. }
  993. /* so far there is only version 1 */
  994. if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
  995. goto err;
  996. if (fsubj != NULL)
  997. i = X509_REQ_set_subject_name(req, fsubj);
  998. else if (no_prompt)
  999. i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
  1000. else
  1001. i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
  1002. chtype);
  1003. if (!i)
  1004. goto err;
  1005. if (!X509_REQ_set_pubkey(req, pkey))
  1006. goto err;
  1007. ret = 1;
  1008. err:
  1009. return ret;
  1010. }
  1011. static int prompt_info(X509_REQ *req,
  1012. STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
  1013. STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
  1014. int attribs, unsigned long chtype)
  1015. {
  1016. int i;
  1017. char *p, *q;
  1018. char buf[100];
  1019. int nid, mval;
  1020. long n_min, n_max;
  1021. char *type, *value;
  1022. const char *def;
  1023. CONF_VALUE *v;
  1024. X509_NAME *subj = X509_REQ_get_subject_name(req);
  1025. if (!batch) {
  1026. BIO_printf(bio_err,
  1027. "You are about to be asked to enter information that will be incorporated\n");
  1028. BIO_printf(bio_err, "into your certificate request.\n");
  1029. BIO_printf(bio_err,
  1030. "What you are about to enter is what is called a Distinguished Name or a DN.\n");
  1031. BIO_printf(bio_err,
  1032. "There are quite a few fields but you can leave some blank\n");
  1033. BIO_printf(bio_err,
  1034. "For some fields there will be a default value,\n");
  1035. BIO_printf(bio_err,
  1036. "If you enter '.', the field will be left blank.\n");
  1037. BIO_printf(bio_err, "-----\n");
  1038. }
  1039. if (sk_CONF_VALUE_num(dn_sk)) {
  1040. i = -1;
  1041. start:
  1042. for (;;) {
  1043. i++;
  1044. if (sk_CONF_VALUE_num(dn_sk) <= i)
  1045. break;
  1046. v = sk_CONF_VALUE_value(dn_sk, i);
  1047. p = q = NULL;
  1048. type = v->name;
  1049. if (!check_end(type, "_min") || !check_end(type, "_max") ||
  1050. !check_end(type, "_default") || !check_end(type, "_value"))
  1051. continue;
  1052. /*
  1053. * Skip past any leading X. X: X, etc to allow for multiple
  1054. * instances
  1055. */
  1056. for (p = v->name; *p; p++)
  1057. if ((*p == ':') || (*p == ',') || (*p == '.')) {
  1058. p++;
  1059. if (*p)
  1060. type = p;
  1061. break;
  1062. }
  1063. if (*type == '+') {
  1064. mval = -1;
  1065. type++;
  1066. } else {
  1067. mval = 0;
  1068. }
  1069. /* If OBJ not recognised ignore it */
  1070. if ((nid = OBJ_txt2nid(type)) == NID_undef)
  1071. goto start;
  1072. if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
  1073. return 0;
  1074. if ((def = app_conf_try_string(req_conf, dn_sect, buf)) == NULL)
  1075. def = "";
  1076. if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
  1077. return 0;
  1078. if ((value = app_conf_try_string(req_conf, dn_sect, buf)) == NULL)
  1079. value = NULL;
  1080. if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
  1081. return 0;
  1082. if (!app_conf_try_number(req_conf, dn_sect, buf, &n_min))
  1083. n_min = -1;
  1084. if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
  1085. return 0;
  1086. if (!app_conf_try_number(req_conf, dn_sect, buf, &n_max))
  1087. n_max = -1;
  1088. if (!add_DN_object(subj, v->value, def, value, nid,
  1089. n_min, n_max, chtype, mval))
  1090. return 0;
  1091. }
  1092. if (X509_NAME_entry_count(subj) == 0) {
  1093. BIO_printf(bio_err, "Error: No objects specified in config file\n");
  1094. return 0;
  1095. }
  1096. if (attribs) {
  1097. if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
  1098. && (!batch)) {
  1099. BIO_printf(bio_err,
  1100. "\nPlease enter the following 'extra' attributes\n");
  1101. BIO_printf(bio_err,
  1102. "to be sent with your certificate request\n");
  1103. }
  1104. i = -1;
  1105. start2:
  1106. for (;;) {
  1107. i++;
  1108. if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
  1109. break;
  1110. v = sk_CONF_VALUE_value(attr_sk, i);
  1111. type = v->name;
  1112. if ((nid = OBJ_txt2nid(type)) == NID_undef)
  1113. goto start2;
  1114. if (!join(buf, sizeof(buf), type, "_default", "Name"))
  1115. return 0;
  1116. def = app_conf_try_string(req_conf, attr_sect, buf);
  1117. if (def == NULL)
  1118. def = "";
  1119. if (!join(buf, sizeof(buf), type, "_value", "Name"))
  1120. return 0;
  1121. value = app_conf_try_string(req_conf, attr_sect, buf);
  1122. if (!join(buf, sizeof(buf), type, "_min", "Name"))
  1123. return 0;
  1124. if (!app_conf_try_number(req_conf, attr_sect, buf, &n_min))
  1125. n_min = -1;
  1126. if (!join(buf, sizeof(buf), type, "_max", "Name"))
  1127. return 0;
  1128. if (!app_conf_try_number(req_conf, attr_sect, buf, &n_max))
  1129. n_max = -1;
  1130. if (!add_attribute_object(req,
  1131. v->value, def, value, nid, n_min,
  1132. n_max, chtype))
  1133. return 0;
  1134. }
  1135. }
  1136. } else {
  1137. BIO_printf(bio_err, "No template, please set one up.\n");
  1138. return 0;
  1139. }
  1140. return 1;
  1141. }
  1142. static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
  1143. STACK_OF(CONF_VALUE) *attr_sk, int attribs,
  1144. unsigned long chtype)
  1145. {
  1146. int i, spec_char, plus_char;
  1147. char *p, *q;
  1148. char *type;
  1149. CONF_VALUE *v;
  1150. X509_NAME *subj;
  1151. subj = X509_REQ_get_subject_name(req);
  1152. for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
  1153. int mval;
  1154. v = sk_CONF_VALUE_value(dn_sk, i);
  1155. p = q = NULL;
  1156. type = v->name;
  1157. /*
  1158. * Skip past any leading X. X: X, etc to allow for multiple instances
  1159. */
  1160. for (p = v->name; *p; p++) {
  1161. #ifndef CHARSET_EBCDIC
  1162. spec_char = (*p == ':' || *p == ',' || *p == '.');
  1163. #else
  1164. spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
  1165. || *p == os_toascii['.']);
  1166. #endif
  1167. if (spec_char) {
  1168. p++;
  1169. if (*p)
  1170. type = p;
  1171. break;
  1172. }
  1173. }
  1174. #ifndef CHARSET_EBCDIC
  1175. plus_char = (*type == '+');
  1176. #else
  1177. plus_char = (*type == os_toascii['+']);
  1178. #endif
  1179. if (plus_char) {
  1180. type++;
  1181. mval = -1;
  1182. } else {
  1183. mval = 0;
  1184. }
  1185. if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
  1186. (unsigned char *)v->value, -1, -1,
  1187. mval))
  1188. return 0;
  1189. }
  1190. if (!X509_NAME_entry_count(subj)) {
  1191. BIO_printf(bio_err, "Error: No objects specified in config file\n");
  1192. return 0;
  1193. }
  1194. if (attribs) {
  1195. for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
  1196. v = sk_CONF_VALUE_value(attr_sk, i);
  1197. if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
  1198. (unsigned char *)v->value, -1))
  1199. return 0;
  1200. }
  1201. }
  1202. return 1;
  1203. }
  1204. static int add_DN_object(X509_NAME *n, char *text, const char *def,
  1205. char *value, int nid, int n_min, int n_max,
  1206. unsigned long chtype, int mval)
  1207. {
  1208. int ret = 0;
  1209. char buf[1024];
  1210. ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
  1211. "DN value", "DN default");
  1212. if ((ret == 0) || (ret == 1))
  1213. return ret;
  1214. ret = 1;
  1215. if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
  1216. (unsigned char *)buf, -1, -1, mval))
  1217. ret = 0;
  1218. return ret;
  1219. }
  1220. static int add_attribute_object(X509_REQ *req, char *text, const char *def,
  1221. char *value, int nid, int n_min,
  1222. int n_max, unsigned long chtype)
  1223. {
  1224. int ret = 0;
  1225. char buf[1024];
  1226. ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
  1227. "Attribute value", "Attribute default");
  1228. if ((ret == 0) || (ret == 1))
  1229. return ret;
  1230. ret = 1;
  1231. if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
  1232. (unsigned char *)buf, -1)) {
  1233. BIO_printf(bio_err, "Error adding attribute\n");
  1234. ret = 0;
  1235. }
  1236. return ret;
  1237. }
  1238. static int build_data(char *text, const char *def, char *value,
  1239. int n_min, int n_max, char *buf, const int buf_size,
  1240. const char *desc1, const char *desc2)
  1241. {
  1242. int i;
  1243. start:
  1244. if (!batch)
  1245. BIO_printf(bio_err, "%s [%s]:", text, def);
  1246. (void)BIO_flush(bio_err);
  1247. if (value != NULL) {
  1248. if (!join(buf, buf_size, value, "\n", desc1))
  1249. return 0;
  1250. BIO_printf(bio_err, "%s\n", value);
  1251. } else {
  1252. buf[0] = '\0';
  1253. if (!batch) {
  1254. if (!fgets(buf, buf_size, stdin))
  1255. return 0;
  1256. } else {
  1257. buf[0] = '\n';
  1258. buf[1] = '\0';
  1259. }
  1260. }
  1261. if (buf[0] == '\0')
  1262. return 0;
  1263. if (buf[0] == '\n') {
  1264. if ((def == NULL) || (def[0] == '\0'))
  1265. return 1;
  1266. if (!join(buf, buf_size, def, "\n", desc2))
  1267. return 0;
  1268. } else if ((buf[0] == '.') && (buf[1] == '\n')) {
  1269. return 1;
  1270. }
  1271. i = strlen(buf);
  1272. if (buf[i - 1] != '\n') {
  1273. BIO_printf(bio_err, "Missing newline at end of input\n");
  1274. return 0;
  1275. }
  1276. buf[--i] = '\0';
  1277. #ifdef CHARSET_EBCDIC
  1278. ebcdic2ascii(buf, buf, i);
  1279. #endif
  1280. if (!req_check_len(i, n_min, n_max)) {
  1281. if (batch || value)
  1282. return 0;
  1283. goto start;
  1284. }
  1285. return 2;
  1286. }
  1287. static int req_check_len(int len, int n_min, int n_max)
  1288. {
  1289. if (n_min > 0 && len < n_min) {
  1290. BIO_printf(bio_err,
  1291. "String too short, must be at least %d bytes long\n", n_min);
  1292. return 0;
  1293. }
  1294. if (n_max >= 0 && len > n_max) {
  1295. BIO_printf(bio_err,
  1296. "String too long, must be at most %d bytes long\n", n_max);
  1297. return 0;
  1298. }
  1299. return 1;
  1300. }
  1301. /* Check if the end of a string matches 'end' */
  1302. static int check_end(const char *str, const char *end)
  1303. {
  1304. size_t elen, slen;
  1305. const char *tmp;
  1306. elen = strlen(end);
  1307. slen = strlen(str);
  1308. if (elen > slen)
  1309. return 1;
  1310. tmp = str + slen - elen;
  1311. return strcmp(tmp, end);
  1312. }
  1313. /*
  1314. * Merge the two strings together into the result buffer checking for
  1315. * overflow and producing an error message if there is.
  1316. */
  1317. static int join(char buf[], size_t buf_size, const char *name,
  1318. const char *tail, const char *desc)
  1319. {
  1320. const size_t name_len = strlen(name), tail_len = strlen(tail);
  1321. if (name_len + tail_len + 1 > buf_size) {
  1322. BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
  1323. return 0;
  1324. }
  1325. memcpy(buf, name, name_len);
  1326. memcpy(buf + name_len, tail, tail_len + 1);
  1327. return 1;
  1328. }
  1329. static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
  1330. char **pkeytype, long *pkeylen,
  1331. ENGINE *keygen_engine)
  1332. {
  1333. EVP_PKEY_CTX *gctx = NULL;
  1334. EVP_PKEY *param = NULL;
  1335. long keylen = -1;
  1336. BIO *pbio = NULL;
  1337. const char *keytype = NULL;
  1338. size_t keytypelen = 0;
  1339. int expect_paramfile = 0;
  1340. const char *paramfile = NULL;
  1341. /* Treat the first part of gstr, and only that */
  1342. if (gstr == NULL) {
  1343. /*
  1344. * Special case: when no string given, default to RSA and the
  1345. * key length given by |*pkeylen|.
  1346. */
  1347. keytype = "RSA";
  1348. keylen = *pkeylen;
  1349. } else if (gstr[0] >= '0' && gstr[0] <= '9') {
  1350. /* Special case: only keylength given from string, so default to RSA */
  1351. keytype = "RSA";
  1352. /* The second part treatment will do the rest */
  1353. } else {
  1354. const char *p = strchr(gstr, ':');
  1355. int len;
  1356. if (p != NULL)
  1357. len = p - gstr;
  1358. else
  1359. len = strlen(gstr);
  1360. if (strncmp(gstr, "param", len) == 0) {
  1361. expect_paramfile = 1;
  1362. if (p == NULL) {
  1363. BIO_printf(bio_err,
  1364. "Parameter file requested but no path given: %s\n",
  1365. gstr);
  1366. return NULL;
  1367. }
  1368. } else {
  1369. keytype = gstr;
  1370. keytypelen = len;
  1371. }
  1372. if (p != NULL)
  1373. gstr = gstr + len + 1;
  1374. else
  1375. gstr = NULL;
  1376. }
  1377. /* Treat the second part of gstr, if there is one */
  1378. if (gstr != NULL) {
  1379. /* If the second part starts with a digit, we assume it's a size */
  1380. if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
  1381. keylen = atol(gstr);
  1382. else
  1383. paramfile = gstr;
  1384. }
  1385. if (paramfile != NULL) {
  1386. pbio = BIO_new_file(paramfile, "r");
  1387. if (pbio == NULL) {
  1388. BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
  1389. return NULL;
  1390. }
  1391. param = PEM_read_bio_Parameters(pbio, NULL);
  1392. if (param == NULL) {
  1393. X509 *x;
  1394. (void)BIO_reset(pbio);
  1395. x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
  1396. if (x != NULL) {
  1397. param = X509_get_pubkey(x);
  1398. X509_free(x);
  1399. }
  1400. }
  1401. BIO_free(pbio);
  1402. if (param == NULL) {
  1403. BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
  1404. return NULL;
  1405. }
  1406. if (keytype == NULL) {
  1407. keytype = EVP_PKEY_get0_type_name(param);
  1408. if (keytype == NULL) {
  1409. EVP_PKEY_free(param);
  1410. BIO_puts(bio_err, "Unable to determine key type\n");
  1411. return NULL;
  1412. }
  1413. }
  1414. }
  1415. if (keytypelen > 0)
  1416. *pkeytype = OPENSSL_strndup(keytype, keytypelen);
  1417. else
  1418. *pkeytype = OPENSSL_strdup(keytype);
  1419. if (*pkeytype == NULL) {
  1420. BIO_printf(bio_err, "Out of memory\n");
  1421. EVP_PKEY_free(param);
  1422. return NULL;
  1423. }
  1424. if (keylen >= 0)
  1425. *pkeylen = keylen;
  1426. if (param != NULL) {
  1427. if (!EVP_PKEY_is_a(param, *pkeytype)) {
  1428. BIO_printf(bio_err, "Key type does not match parameters\n");
  1429. EVP_PKEY_free(param);
  1430. return NULL;
  1431. }
  1432. if (keygen_engine != NULL)
  1433. gctx = EVP_PKEY_CTX_new(param, keygen_engine);
  1434. else
  1435. gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
  1436. param, app_get0_propq());
  1437. *pkeylen = EVP_PKEY_get_bits(param);
  1438. EVP_PKEY_free(param);
  1439. } else {
  1440. if (keygen_engine != NULL) {
  1441. int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
  1442. keygen_engine);
  1443. if (pkey_id != NID_undef)
  1444. gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
  1445. } else {
  1446. gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
  1447. *pkeytype, app_get0_propq());
  1448. }
  1449. }
  1450. if (gctx == NULL) {
  1451. BIO_puts(bio_err, "Error allocating keygen context\n");
  1452. return NULL;
  1453. }
  1454. if (EVP_PKEY_keygen_init(gctx) <= 0) {
  1455. BIO_puts(bio_err, "Error initializing keygen context\n");
  1456. EVP_PKEY_CTX_free(gctx);
  1457. return NULL;
  1458. }
  1459. if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
  1460. || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
  1461. keylen = *pkeylen;
  1462. if (keylen != -1) {
  1463. OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
  1464. size_t bits = keylen;
  1465. params[0] =
  1466. OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
  1467. if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
  1468. BIO_puts(bio_err, "Error setting keysize\n");
  1469. EVP_PKEY_CTX_free(gctx);
  1470. return NULL;
  1471. }
  1472. }
  1473. return gctx;
  1474. }