2
0

req.c 54 KB

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