req.c 54 KB

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