req.c 54 KB

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