2
0

req.c 53 KB

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