2
0

req.c 53 KB

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