req.c 53 KB

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