xref: /minix3/external/bsd/bind/dist/bin/dnssec/dnssec-keygen.c (revision 00b67f09dd46474d133c95011a48590a8e8f94c7)
1 /*	$NetBSD: dnssec-keygen.c,v 1.16 2015/07/08 17:28:55 christos Exp $	*/
2 
3 /*
4  * Portions Copyright (C) 2004-2015  Internet Systems Consortium, Inc. ("ISC")
5  * Portions Copyright (C) 1999-2003  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NETWORK ASSOCIATES DISCLAIMS
12  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
13  * WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE
14  * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
17  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  * Portions Copyright (C) 1995-2000 by Network Associates, Inc.
20  *
21  * Permission to use, copy, modify, and/or distribute this software for any
22  * purpose with or without fee is hereby granted, provided that the above
23  * copyright notice and this permission notice appear in all copies.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NETWORK ASSOCIATES DISCLAIMS
26  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
27  * WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE
28  * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
29  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
30  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
31  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
32  */
33 
34 /*! \file */
35 
36 #include <config.h>
37 
38 #include <ctype.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 
42 #include <isc/buffer.h>
43 #include <isc/commandline.h>
44 #include <isc/entropy.h>
45 #include <isc/mem.h>
46 #include <isc/region.h>
47 #include <isc/string.h>
48 #include <isc/util.h>
49 
50 #include <dns/dnssec.h>
51 #include <dns/fixedname.h>
52 #include <dns/keyvalues.h>
53 #include <dns/log.h>
54 #include <dns/name.h>
55 #include <dns/rdataclass.h>
56 #include <dns/result.h>
57 #include <dns/secalg.h>
58 
59 #include <dst/dst.h>
60 
61 #ifdef PKCS11CRYPTO
62 #include <pk11/result.h>
63 #endif
64 
65 #include "dnssectool.h"
66 
67 #define MAX_RSA 4096 /* should be long enough... */
68 
69 const char *program = "dnssec-keygen";
70 int verbose;
71 
72 #define DEFAULT_ALGORITHM "RSASHA1"
73 #define DEFAULT_NSEC3_ALGORITHM "NSEC3RSASHA1"
74 
75 ISC_PLATFORM_NORETURN_PRE static void
76 usage(void) ISC_PLATFORM_NORETURN_POST;
77 
78 static void progress(int p);
79 
80 static void
usage(void)81 usage(void) {
82 	fprintf(stderr, "Usage:\n");
83 	fprintf(stderr, "    %s [options] name\n\n", program);
84 	fprintf(stderr, "Version: %s\n", VERSION);
85 	fprintf(stderr, "    name: owner of the key\n");
86 	fprintf(stderr, "Options:\n");
87 	fprintf(stderr, "    -K <directory>: write keys into directory\n");
88 	fprintf(stderr, "    -a <algorithm>:\n");
89 	fprintf(stderr, "        RSA | RSAMD5 | DSA | RSASHA1 | NSEC3RSASHA1"
90 				" | NSEC3DSA |\n");
91 	fprintf(stderr, "        RSASHA256 | RSASHA512 | ECCGOST |\n");
92 	fprintf(stderr, "        ECDSAP256SHA256 | ECDSAP384SHA384 |\n");
93 	fprintf(stderr, "        DH | HMAC-MD5 | HMAC-SHA1 | HMAC-SHA224 | "
94 				"HMAC-SHA256 | \n");
95 	fprintf(stderr, "        HMAC-SHA384 | HMAC-SHA512\n");
96 	fprintf(stderr, "       (default: RSASHA1, or "
97 			       "NSEC3RSASHA1 if using -3)\n");
98 	fprintf(stderr, "    -3: use NSEC3-capable algorithm\n");
99 	fprintf(stderr, "    -b <key size in bits>:\n");
100 	fprintf(stderr, "        RSAMD5:\t[512..%d]\n", MAX_RSA);
101 	fprintf(stderr, "        RSASHA1:\t[512..%d]\n", MAX_RSA);
102 	fprintf(stderr, "        NSEC3RSASHA1:\t[512..%d]\n", MAX_RSA);
103 	fprintf(stderr, "        RSASHA256:\t[512..%d]\n", MAX_RSA);
104 	fprintf(stderr, "        RSASHA512:\t[1024..%d]\n", MAX_RSA);
105 	fprintf(stderr, "        DH:\t\t[128..4096]\n");
106 	fprintf(stderr, "        DSA:\t\t[512..1024] and divisible by 64\n");
107 	fprintf(stderr, "        NSEC3DSA:\t[512..1024] and divisible "
108 				"by 64\n");
109 	fprintf(stderr, "        ECCGOST:\tignored\n");
110 	fprintf(stderr, "        ECDSAP256SHA256:\tignored\n");
111 	fprintf(stderr, "        ECDSAP384SHA384:\tignored\n");
112 	fprintf(stderr, "        HMAC-MD5:\t[1..512]\n");
113 	fprintf(stderr, "        HMAC-SHA1:\t[1..160]\n");
114 	fprintf(stderr, "        HMAC-SHA224:\t[1..224]\n");
115 	fprintf(stderr, "        HMAC-SHA256:\t[1..256]\n");
116 	fprintf(stderr, "        HMAC-SHA384:\t[1..384]\n");
117 	fprintf(stderr, "        HMAC-SHA512:\t[1..512]\n");
118 	fprintf(stderr, "        (if using the default algorithm, key size\n"
119 			"        defaults to 2048 for KSK, or 1024 for all "
120 			"others)\n");
121 	fprintf(stderr, "    -n <nametype>: ZONE | HOST | ENTITY | "
122 					    "USER | OTHER\n");
123 	fprintf(stderr, "        (DNSKEY generation defaults to ZONE)\n");
124 	fprintf(stderr, "    -c <class>: (default: IN)\n");
125 	fprintf(stderr, "    -d <digest bits> (0 => max, default)\n");
126 	fprintf(stderr, "    -E <engine>:\n");
127 #if defined(PKCS11CRYPTO)
128 	fprintf(stderr, "        path to PKCS#11 provider library "
129 				"(default is %s)\n", PK11_LIB_LOCATION);
130 #elif defined(USE_PKCS11)
131 	fprintf(stderr, "        name of an OpenSSL engine to use "
132 				"(default is \"pkcs11\")\n");
133 #else
134 	fprintf(stderr, "        name of an OpenSSL engine to use\n");
135 #endif
136 	fprintf(stderr, "    -f <keyflag>: KSK | REVOKE\n");
137 	fprintf(stderr, "    -g <generator>: use specified generator "
138 			"(DH only)\n");
139 	fprintf(stderr, "    -L <ttl>: default key TTL\n");
140 	fprintf(stderr, "    -p <protocol>: (default: 3 [dnssec])\n");
141 	fprintf(stderr, "    -r <randomdev>: a file containing random data\n");
142 	fprintf(stderr, "    -s <strength>: strength value this key signs DNS "
143 			"records with (default: 0)\n");
144 	fprintf(stderr, "    -T <rrtype>: DNSKEY | KEY (default: DNSKEY; "
145 			"use KEY for SIG(0))\n");
146 	fprintf(stderr, "    -t <type>: "
147 			"AUTHCONF | NOAUTHCONF | NOAUTH | NOCONF "
148 			"(default: AUTHCONF)\n");
149 	fprintf(stderr, "    -h: print usage and exit\n");
150 	fprintf(stderr, "    -m <memory debugging mode>:\n");
151 	fprintf(stderr, "       usage | trace | record | size | mctx\n");
152 	fprintf(stderr, "    -v <level>: set verbosity level (0 - 10)\n");
153 	fprintf(stderr, "    -V: print version information\n");
154 	fprintf(stderr, "Timing options:\n");
155 	fprintf(stderr, "    -P date/[+-]offset/none: set key publication date "
156 						"(default: now)\n");
157 	fprintf(stderr, "    -A date/[+-]offset/none: set key activation date "
158 						"(default: now)\n");
159 	fprintf(stderr, "    -R date/[+-]offset/none: set key "
160 						     "revocation date\n");
161 	fprintf(stderr, "    -I date/[+-]offset/none: set key "
162 						     "inactivation date\n");
163 	fprintf(stderr, "    -D date/[+-]offset/none: set key deletion date\n");
164 	fprintf(stderr, "    -G: generate key only; do not set -P or -A\n");
165 	fprintf(stderr, "    -C: generate a backward-compatible key, omitting "
166 			"all dates\n");
167 	fprintf(stderr, "    -S <key>: generate a successor to an existing "
168 				      "key\n");
169 	fprintf(stderr, "    -i <interval>: prepublication interval for "
170 					   "successor key "
171 					   "(default: 30 days)\n");
172 	fprintf(stderr, "Output:\n");
173 	fprintf(stderr, "     K<name>+<alg>+<id>.key, "
174 			"K<name>+<alg>+<id>.private\n");
175 
176 	exit (-1);
177 }
178 
179 static isc_boolean_t
dsa_size_ok(int size)180 dsa_size_ok(int size) {
181 	return (ISC_TF(size >= 512 && size <= 1024 && size % 64 == 0));
182 }
183 
184 static void
progress(int p)185 progress(int p)
186 {
187 	char c = '*';
188 
189 	switch (p) {
190 	case 0:
191 		c = '.';
192 		break;
193 	case 1:
194 		c = '+';
195 		break;
196 	case 2:
197 		c = '*';
198 		break;
199 	case 3:
200 		c = ' ';
201 		break;
202 	default:
203 		break;
204 	}
205 	(void) putc(c, stderr);
206 	(void) fflush(stderr);
207 }
208 
209 int
main(int argc,char ** argv)210 main(int argc, char **argv) {
211 	char		*algname = NULL, *freeit = NULL;
212 	char		*nametype = NULL, *type = NULL;
213 	char		*classname = NULL;
214 	char		*endp;
215 	dst_key_t	*key = NULL;
216 	dns_fixedname_t	fname;
217 	dns_name_t	*name;
218 	isc_uint16_t	flags = 0, kskflag = 0, revflag = 0;
219 	dns_secalg_t	alg;
220 	isc_boolean_t	conflict = ISC_FALSE, null_key = ISC_FALSE;
221 	isc_boolean_t	oldstyle = ISC_FALSE;
222 	isc_mem_t	*mctx = NULL;
223 	int		ch, generator = 0, param = 0;
224 	int		protocol = -1, size = -1, signatory = 0;
225 	isc_result_t	ret;
226 	isc_textregion_t r;
227 	char		filename[255];
228 	const char	*directory = NULL;
229 	const char	*predecessor = NULL;
230 	dst_key_t	*prevkey = NULL;
231 	isc_buffer_t	buf;
232 	isc_log_t	*log = NULL;
233 	isc_entropy_t	*ectx = NULL;
234 #ifdef USE_PKCS11
235 	const char	*engine = PKCS11_ENGINE;
236 #else
237 	const char	*engine = NULL;
238 #endif
239 	dns_rdataclass_t rdclass;
240 	int		options = DST_TYPE_PRIVATE | DST_TYPE_PUBLIC;
241 	int		dbits = 0;
242 	dns_ttl_t	ttl = 0;
243 	isc_boolean_t	use_default = ISC_FALSE, use_nsec3 = ISC_FALSE;
244 	isc_stdtime_t	publish = 0, activate = 0, revoke = 0;
245 	isc_stdtime_t	inactive = 0, delete = 0;
246 	isc_stdtime_t	now;
247 	int		prepub = -1;
248 	isc_boolean_t	setpub = ISC_FALSE, setact = ISC_FALSE;
249 	isc_boolean_t	setrev = ISC_FALSE, setinact = ISC_FALSE;
250 	isc_boolean_t	setdel = ISC_FALSE, setttl = ISC_FALSE;
251 	isc_boolean_t	unsetpub = ISC_FALSE, unsetact = ISC_FALSE;
252 	isc_boolean_t	unsetrev = ISC_FALSE, unsetinact = ISC_FALSE;
253 	isc_boolean_t	unsetdel = ISC_FALSE;
254 	isc_boolean_t	genonly = ISC_FALSE;
255 	isc_boolean_t	quiet = ISC_FALSE;
256 	isc_boolean_t	show_progress = ISC_FALSE;
257 	unsigned char	c;
258 
259 	if (argc == 1)
260 		usage();
261 
262 #ifdef PKCS11CRYPTO
263 	pk11_result_register();
264 #endif
265 	dns_result_register();
266 
267 	isc_commandline_errprint = ISC_FALSE;
268 
269 	/*
270 	 * Process memory debugging argument first.
271 	 */
272 #define CMDLINE_FLAGS "3A:a:b:Cc:D:d:E:eFf:Gg:hI:i:K:kL:m:n:P:p:qR:r:S:s:T:t:" \
273 		      "v:V"
274 	while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
275 		switch (ch) {
276 		case 'm':
277 			if (strcasecmp(isc_commandline_argument, "record") == 0)
278 				isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
279 			if (strcasecmp(isc_commandline_argument, "trace") == 0)
280 				isc_mem_debugging |= ISC_MEM_DEBUGTRACE;
281 			if (strcasecmp(isc_commandline_argument, "usage") == 0)
282 				isc_mem_debugging |= ISC_MEM_DEBUGUSAGE;
283 			if (strcasecmp(isc_commandline_argument, "size") == 0)
284 				isc_mem_debugging |= ISC_MEM_DEBUGSIZE;
285 			if (strcasecmp(isc_commandline_argument, "mctx") == 0)
286 				isc_mem_debugging |= ISC_MEM_DEBUGCTX;
287 			break;
288 		default:
289 			break;
290 		}
291 	}
292 	isc_commandline_reset = ISC_TRUE;
293 
294 	RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);
295 
296 	isc_stdtime_get(&now);
297 
298 	while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
299 	    switch (ch) {
300 		case '3':
301 			use_nsec3 = ISC_TRUE;
302 			break;
303 		case 'a':
304 			algname = isc_commandline_argument;
305 			break;
306 		case 'b':
307 			size = strtol(isc_commandline_argument, &endp, 10);
308 			if (*endp != '\0' || size < 0)
309 				fatal("-b requires a non-negative number");
310 			break;
311 		case 'C':
312 			oldstyle = ISC_TRUE;
313 			break;
314 		case 'c':
315 			classname = isc_commandline_argument;
316 			break;
317 		case 'd':
318 			dbits = strtol(isc_commandline_argument, &endp, 10);
319 			if (*endp != '\0' || dbits < 0)
320 				fatal("-d requires a non-negative number");
321 			break;
322 		case 'E':
323 			engine = isc_commandline_argument;
324 			break;
325 		case 'e':
326 			fprintf(stderr,
327 				"phased-out option -e "
328 				"(was 'use (RSA) large exponent)\n");
329 			break;
330 		case 'f':
331 			c = (unsigned char)(isc_commandline_argument[0]);
332 			if (toupper(c) == 'K')
333 				kskflag = DNS_KEYFLAG_KSK;
334 			else if (toupper(c) == 'R')
335 				revflag = DNS_KEYFLAG_REVOKE;
336 			else
337 				fatal("unknown flag '%s'",
338 				      isc_commandline_argument);
339 			break;
340 		case 'g':
341 			generator = strtol(isc_commandline_argument,
342 					   &endp, 10);
343 			if (*endp != '\0' || generator <= 0)
344 				fatal("-g requires a positive number");
345 			break;
346 		case 'K':
347 			directory = isc_commandline_argument;
348 			ret = try_dir(directory);
349 			if (ret != ISC_R_SUCCESS)
350 				fatal("cannot open directory %s: %s",
351 				      directory, isc_result_totext(ret));
352 			break;
353 		case 'k':
354 			fatal("The -k option has been deprecated.\n"
355 			      "To generate a key-signing key, use -f KSK.\n"
356 			      "To generate a key with TYPE=KEY, use -T KEY.\n");
357 			break;
358 		case 'L':
359 			ttl = strtottl(isc_commandline_argument);
360 			setttl = ISC_TRUE;
361 			break;
362 		case 'n':
363 			nametype = isc_commandline_argument;
364 			break;
365 		case 'm':
366 			break;
367 		case 'p':
368 			protocol = strtol(isc_commandline_argument, &endp, 10);
369 			if (*endp != '\0' || protocol < 0 || protocol > 255)
370 				fatal("-p must be followed by a number "
371 				      "[0..255]");
372 			break;
373 		case 'q':
374 			quiet = ISC_TRUE;
375 			break;
376 		case 'r':
377 			setup_entropy(mctx, isc_commandline_argument, &ectx);
378 			break;
379 		case 's':
380 			signatory = strtol(isc_commandline_argument,
381 					   &endp, 10);
382 			if (*endp != '\0' || signatory < 0 || signatory > 15)
383 				fatal("-s must be followed by a number "
384 				      "[0..15]");
385 			break;
386 		case 'T':
387 			if (strcasecmp(isc_commandline_argument, "KEY") == 0)
388 				options |= DST_TYPE_KEY;
389 			else if (strcasecmp(isc_commandline_argument,
390 				 "DNSKEY") == 0)
391 				/* default behavior */
392 				;
393 			else
394 				fatal("unknown type '%s'",
395 				      isc_commandline_argument);
396 			break;
397 		case 't':
398 			type = isc_commandline_argument;
399 			break;
400 		case 'v':
401 			endp = NULL;
402 			verbose = strtol(isc_commandline_argument, &endp, 0);
403 			if (*endp != '\0')
404 				fatal("-v must be followed by a number");
405 			break;
406 		case 'z':
407 			/* already the default */
408 			break;
409 		case 'G':
410 			genonly = ISC_TRUE;
411 			break;
412 		case 'P':
413 			if (setpub || unsetpub)
414 				fatal("-P specified more than once");
415 
416 			publish = strtotime(isc_commandline_argument,
417 					    now, now, &setpub);
418 			unsetpub = !setpub;
419 			break;
420 		case 'A':
421 			if (setact || unsetact)
422 				fatal("-A specified more than once");
423 
424 			activate = strtotime(isc_commandline_argument,
425 					     now, now, &setact);
426 			unsetact = !setact;
427 			break;
428 		case 'R':
429 			if (setrev || unsetrev)
430 				fatal("-R specified more than once");
431 
432 			revoke = strtotime(isc_commandline_argument,
433 					   now, now, &setrev);
434 			unsetrev = !setrev;
435 			break;
436 		case 'I':
437 			if (setinact || unsetinact)
438 				fatal("-I specified more than once");
439 
440 			inactive = strtotime(isc_commandline_argument,
441 					     now, now, &setinact);
442 			unsetinact = !setinact;
443 			break;
444 		case 'D':
445 			if (setdel || unsetdel)
446 				fatal("-D specified more than once");
447 
448 			delete = strtotime(isc_commandline_argument,
449 					   now, now, &setdel);
450 			unsetdel = !setdel;
451 			break;
452 		case 'S':
453 			predecessor = isc_commandline_argument;
454 			break;
455 		case 'i':
456 			prepub = strtottl(isc_commandline_argument);
457 			break;
458 		case 'F':
459 			/* Reserved for FIPS mode */
460 			/* FALLTHROUGH */
461 		case '?':
462 			if (isc_commandline_option != '?')
463 				fprintf(stderr, "%s: invalid argument -%c\n",
464 					program, isc_commandline_option);
465 			/* FALLTHROUGH */
466 		case 'h':
467 			/* Does not return. */
468 			usage();
469 
470 		case 'V':
471 			/* Does not return. */
472 			version(program);
473 
474 		default:
475 			fprintf(stderr, "%s: unhandled option -%c\n",
476 				program, isc_commandline_option);
477 			exit(1);
478 		}
479 	}
480 
481 	if (!isatty(0))
482 		quiet = ISC_TRUE;
483 
484 	if (ectx == NULL)
485 		setup_entropy(mctx, NULL, &ectx);
486 	ret = dst_lib_init2(mctx, ectx, engine,
487 			    ISC_ENTROPY_BLOCKING | ISC_ENTROPY_GOODONLY);
488 	if (ret != ISC_R_SUCCESS)
489 		fatal("could not initialize dst: %s",
490 		      isc_result_totext(ret));
491 
492 	setup_logging(mctx, &log);
493 
494 	if (predecessor == NULL) {
495 		if (prepub == -1)
496 			prepub = 0;
497 
498 		if (argc < isc_commandline_index + 1)
499 			fatal("the key name was not specified");
500 		if (argc > isc_commandline_index + 1)
501 			fatal("extraneous arguments");
502 
503 		dns_fixedname_init(&fname);
504 		name = dns_fixedname_name(&fname);
505 		isc_buffer_init(&buf, argv[isc_commandline_index],
506 				strlen(argv[isc_commandline_index]));
507 		isc_buffer_add(&buf, strlen(argv[isc_commandline_index]));
508 		ret = dns_name_fromtext(name, &buf, dns_rootname, 0, NULL);
509 		if (ret != ISC_R_SUCCESS)
510 			fatal("invalid key name %s: %s",
511 			      argv[isc_commandline_index],
512 			      isc_result_totext(ret));
513 
514 		if (algname == NULL) {
515 			use_default = ISC_TRUE;
516 			if (use_nsec3)
517 				algname = strdup(DEFAULT_NSEC3_ALGORITHM);
518 			else
519 				algname = strdup(DEFAULT_ALGORITHM);
520 			if (algname == NULL)
521 				fatal("strdup failed");
522 			freeit = algname;
523 			if (verbose > 0)
524 				fprintf(stderr, "no algorithm specified; "
525 						"defaulting to %s\n", algname);
526 		}
527 
528 		if (strcasecmp(algname, "RSA") == 0) {
529 			fprintf(stderr, "The use of RSA (RSAMD5) is not "
530 					"recommended.\nIf you still wish to "
531 					"use RSA (RSAMD5) please specify "
532 					"\"-a RSAMD5\"\n");
533 			INSIST(freeit == NULL);
534 			return (1);
535 		} else if (strcasecmp(algname, "HMAC-MD5") == 0)
536 			alg = DST_ALG_HMACMD5;
537 		else if (strcasecmp(algname, "HMAC-SHA1") == 0)
538 			alg = DST_ALG_HMACSHA1;
539 		else if (strcasecmp(algname, "HMAC-SHA224") == 0)
540 			alg = DST_ALG_HMACSHA224;
541 		else if (strcasecmp(algname, "HMAC-SHA256") == 0)
542 			alg = DST_ALG_HMACSHA256;
543 		else if (strcasecmp(algname, "HMAC-SHA384") == 0)
544 			alg = DST_ALG_HMACSHA384;
545 		else if (strcasecmp(algname, "HMAC-SHA512") == 0)
546 			alg = DST_ALG_HMACSHA512;
547 		else {
548 			r.base = algname;
549 			r.length = strlen(algname);
550 			ret = dns_secalg_fromtext(&alg, &r);
551 			if (ret != ISC_R_SUCCESS)
552 				fatal("unknown algorithm %s", algname);
553 			if (alg == DST_ALG_DH)
554 				options |= DST_TYPE_KEY;
555 		}
556 
557 		if (!dst_algorithm_supported(alg))
558 			fatal("unsupported algorithm: %d", alg);
559 
560 		if (use_nsec3 &&
561 		    alg != DST_ALG_NSEC3DSA && alg != DST_ALG_NSEC3RSASHA1 &&
562 		    alg != DST_ALG_RSASHA256 && alg!= DST_ALG_RSASHA512 &&
563 		    alg != DST_ALG_ECCGOST &&
564 		    alg != DST_ALG_ECDSA256 && alg != DST_ALG_ECDSA384) {
565 			fatal("%s is incompatible with NSEC3; "
566 			      "do not use the -3 option", algname);
567 		}
568 
569 		if (type != NULL && (options & DST_TYPE_KEY) != 0) {
570 			if (strcasecmp(type, "NOAUTH") == 0)
571 				flags |= DNS_KEYTYPE_NOAUTH;
572 			else if (strcasecmp(type, "NOCONF") == 0)
573 				flags |= DNS_KEYTYPE_NOCONF;
574 			else if (strcasecmp(type, "NOAUTHCONF") == 0) {
575 				flags |= (DNS_KEYTYPE_NOAUTH |
576 					  DNS_KEYTYPE_NOCONF);
577 				if (size < 0)
578 					size = 0;
579 			}
580 			else if (strcasecmp(type, "AUTHCONF") == 0)
581 				/* nothing */;
582 			else
583 				fatal("invalid type %s", type);
584 		}
585 
586 		if (size < 0) {
587 			if (use_default) {
588 				if ((kskflag & DNS_KEYFLAG_KSK) != 0)
589 					size = 2048;
590 				else
591 					size = 1024;
592 				if (verbose > 0)
593 					fprintf(stderr, "key size not "
594 							"specified; defaulting"
595 							" to %d\n", size);
596 			} else if (alg != DST_ALG_ECCGOST &&
597 				   alg != DST_ALG_ECDSA256 &&
598 				   alg != DST_ALG_ECDSA384)
599 				fatal("key size not specified (-b option)");
600 		}
601 
602 		if (!oldstyle && prepub > 0) {
603 			if (setpub && setact && (activate - prepub) < publish)
604 				fatal("Activation and publication dates "
605 				      "are closer together than the\n\t"
606 				      "prepublication interval.");
607 
608 			if (!setpub && !setact) {
609 				setpub = setact = ISC_TRUE;
610 				publish = now;
611 				activate = now + prepub;
612 			} else if (setpub && !setact) {
613 				setact = ISC_TRUE;
614 				activate = publish + prepub;
615 			} else if (setact && !setpub) {
616 				setpub = ISC_TRUE;
617 				publish = activate - prepub;
618 			}
619 
620 			if ((activate - prepub) < now)
621 				fatal("Time until activation is shorter "
622 				      "than the\n\tprepublication interval.");
623 		}
624 	} else {
625 		char keystr[DST_KEY_FORMATSIZE];
626 		isc_stdtime_t when;
627 		int major, minor;
628 
629 		if (prepub == -1)
630 			prepub = (30 * 86400);
631 
632 		if (algname != NULL)
633 			fatal("-S and -a cannot be used together");
634 		if (size >= 0)
635 			fatal("-S and -b cannot be used together");
636 		if (nametype != NULL)
637 			fatal("-S and -n cannot be used together");
638 		if (type != NULL)
639 			fatal("-S and -t cannot be used together");
640 		if (setpub || unsetpub)
641 			fatal("-S and -P cannot be used together");
642 		if (setact || unsetact)
643 			fatal("-S and -A cannot be used together");
644 		if (use_nsec3)
645 			fatal("-S and -3 cannot be used together");
646 		if (oldstyle)
647 			fatal("-S and -C cannot be used together");
648 		if (genonly)
649 			fatal("-S and -G cannot be used together");
650 
651 		ret = dst_key_fromnamedfile(predecessor, directory,
652 					    DST_TYPE_PUBLIC | DST_TYPE_PRIVATE,
653 					    mctx, &prevkey);
654 		if (ret != ISC_R_SUCCESS)
655 			fatal("Invalid keyfile %s: %s",
656 			      predecessor, isc_result_totext(ret));
657 		if (!dst_key_isprivate(prevkey))
658 			fatal("%s is not a private key", predecessor);
659 
660 		name = dst_key_name(prevkey);
661 		alg = dst_key_alg(prevkey);
662 		size = dst_key_size(prevkey);
663 		flags = dst_key_flags(prevkey);
664 
665 		dst_key_format(prevkey, keystr, sizeof(keystr));
666 		dst_key_getprivateformat(prevkey, &major, &minor);
667 		if (major != DST_MAJOR_VERSION || minor < DST_MINOR_VERSION)
668 			fatal("Key %s has incompatible format version %d.%d\n\t"
669 			      "It is not possible to generate a successor key.",
670 			      keystr, major, minor);
671 
672 		ret = dst_key_gettime(prevkey, DST_TIME_ACTIVATE, &when);
673 		if (ret != ISC_R_SUCCESS)
674 			fatal("Key %s has no activation date.\n\t"
675 			      "You must use dnssec-settime -A to set one "
676 			      "before generating a successor.", keystr);
677 
678 		ret = dst_key_gettime(prevkey, DST_TIME_INACTIVE, &activate);
679 		if (ret != ISC_R_SUCCESS)
680 			fatal("Key %s has no inactivation date.\n\t"
681 			      "You must use dnssec-settime -I to set one "
682 			      "before generating a successor.", keystr);
683 
684 		publish = activate - prepub;
685 		if (publish < now)
686 			fatal("Key %s becomes inactive\n\t"
687 			      "sooner than the prepublication period "
688 			      "for the new key ends.\n\t"
689 			      "Either change the inactivation date with "
690 			      "dnssec-settime -I,\n\t"
691 			      "or use the -i option to set a shorter "
692 			      "prepublication interval.", keystr);
693 
694 		ret = dst_key_gettime(prevkey, DST_TIME_DELETE, &when);
695 		if (ret != ISC_R_SUCCESS)
696 			fprintf(stderr, "%s: WARNING: Key %s has no removal "
697 					"date;\n\t it will remain in the zone "
698 					"indefinitely after rollover.\n\t "
699 					"You can use dnssec-settime -D to "
700 					"change this.\n", program, keystr);
701 
702 		setpub = setact = ISC_TRUE;
703 	}
704 
705 	switch (alg) {
706 	case DNS_KEYALG_RSAMD5:
707 	case DNS_KEYALG_RSASHA1:
708 	case DNS_KEYALG_NSEC3RSASHA1:
709 	case DNS_KEYALG_RSASHA256:
710 		if (size != 0 && (size < 512 || size > MAX_RSA))
711 			fatal("RSA key size %d out of range", size);
712 		break;
713 	case DNS_KEYALG_RSASHA512:
714 		if (size != 0 && (size < 1024 || size > MAX_RSA))
715 			fatal("RSA key size %d out of range", size);
716 		break;
717 	case DNS_KEYALG_DH:
718 		if (size != 0 && (size < 128 || size > 4096))
719 			fatal("DH key size %d out of range", size);
720 		break;
721 	case DNS_KEYALG_DSA:
722 	case DNS_KEYALG_NSEC3DSA:
723 		if (size != 0 && !dsa_size_ok(size))
724 			fatal("invalid DSS key size: %d", size);
725 		break;
726 	case DST_ALG_ECCGOST:
727 		size = 256;
728 		break;
729 	case DST_ALG_ECDSA256:
730 		size = 256;
731 		break;
732 	case DST_ALG_ECDSA384:
733 		size = 384;
734 		break;
735 	case DST_ALG_HMACMD5:
736 		options |= DST_TYPE_KEY;
737 		if (size < 1 || size > 512)
738 			fatal("HMAC-MD5 key size %d out of range", size);
739 		if (dbits != 0 && (dbits < 80 || dbits > 128))
740 			fatal("HMAC-MD5 digest bits %d out of range", dbits);
741 		if ((dbits % 8) != 0)
742 			fatal("HMAC-MD5 digest bits %d not divisible by 8",
743 			      dbits);
744 		break;
745 	case DST_ALG_HMACSHA1:
746 		options |= DST_TYPE_KEY;
747 		if (size < 1 || size > 160)
748 			fatal("HMAC-SHA1 key size %d out of range", size);
749 		if (dbits != 0 && (dbits < 80 || dbits > 160))
750 			fatal("HMAC-SHA1 digest bits %d out of range", dbits);
751 		if ((dbits % 8) != 0)
752 			fatal("HMAC-SHA1 digest bits %d not divisible by 8",
753 			      dbits);
754 		break;
755 	case DST_ALG_HMACSHA224:
756 		options |= DST_TYPE_KEY;
757 		if (size < 1 || size > 224)
758 			fatal("HMAC-SHA224 key size %d out of range", size);
759 		if (dbits != 0 && (dbits < 112 || dbits > 224))
760 			fatal("HMAC-SHA224 digest bits %d out of range", dbits);
761 		if ((dbits % 8) != 0)
762 			fatal("HMAC-SHA224 digest bits %d not divisible by 8",
763 			      dbits);
764 		break;
765 	case DST_ALG_HMACSHA256:
766 		options |= DST_TYPE_KEY;
767 		if (size < 1 || size > 256)
768 			fatal("HMAC-SHA256 key size %d out of range", size);
769 		if (dbits != 0 && (dbits < 128 || dbits > 256))
770 			fatal("HMAC-SHA256 digest bits %d out of range", dbits);
771 		if ((dbits % 8) != 0)
772 			fatal("HMAC-SHA256 digest bits %d not divisible by 8",
773 			      dbits);
774 		break;
775 	case DST_ALG_HMACSHA384:
776 		options |= DST_TYPE_KEY;
777 		if (size < 1 || size > 384)
778 			fatal("HMAC-384 key size %d out of range", size);
779 		if (dbits != 0 && (dbits < 192 || dbits > 384))
780 			fatal("HMAC-SHA384 digest bits %d out of range", dbits);
781 		if ((dbits % 8) != 0)
782 			fatal("HMAC-SHA384 digest bits %d not divisible by 8",
783 			      dbits);
784 		break;
785 	case DST_ALG_HMACSHA512:
786 		options |= DST_TYPE_KEY;
787 		if (size < 1 || size > 512)
788 			fatal("HMAC-SHA512 key size %d out of range", size);
789 		if (dbits != 0 && (dbits < 256 || dbits > 512))
790 			fatal("HMAC-SHA512 digest bits %d out of range", dbits);
791 		if ((dbits % 8) != 0)
792 			fatal("HMAC-SHA512 digest bits %d not divisible by 8",
793 			      dbits);
794 		break;
795 	}
796 
797 	if (alg != DNS_KEYALG_DH && generator != 0)
798 		fatal("specified DH generator for a non-DH key");
799 
800 	if (nametype == NULL) {
801 		if ((options & DST_TYPE_KEY) != 0) /* KEY / HMAC */
802 			fatal("no nametype specified");
803 		flags |= DNS_KEYOWNER_ZONE;	/* DNSKEY */
804 	} else if (strcasecmp(nametype, "zone") == 0)
805 		flags |= DNS_KEYOWNER_ZONE;
806 	else if ((options & DST_TYPE_KEY) != 0)	{ /* KEY / HMAC */
807 		if (strcasecmp(nametype, "host") == 0 ||
808 			 strcasecmp(nametype, "entity") == 0)
809 			flags |= DNS_KEYOWNER_ENTITY;
810 		else if (strcasecmp(nametype, "user") == 0)
811 			flags |= DNS_KEYOWNER_USER;
812 		else
813 			fatal("invalid KEY nametype %s", nametype);
814 	} else if (strcasecmp(nametype, "other") != 0) /* DNSKEY */
815 		fatal("invalid DNSKEY nametype %s", nametype);
816 
817 	rdclass = strtoclass(classname);
818 
819 	if (directory == NULL)
820 		directory = ".";
821 
822 	if ((options & DST_TYPE_KEY) != 0)  /* KEY / HMAC */
823 		flags |= signatory;
824 	else if ((flags & DNS_KEYOWNER_ZONE) != 0) { /* DNSKEY */
825 		flags |= kskflag;
826 		flags |= revflag;
827 	}
828 
829 	if (protocol == -1)
830 		protocol = DNS_KEYPROTO_DNSSEC;
831 	else if ((options & DST_TYPE_KEY) == 0 &&
832 		 protocol != DNS_KEYPROTO_DNSSEC)
833 		fatal("invalid DNSKEY protocol: %d", protocol);
834 
835 	if ((flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY) {
836 		if (size > 0)
837 			fatal("specified null key with non-zero size");
838 		if ((flags & DNS_KEYFLAG_SIGNATORYMASK) != 0)
839 			fatal("specified null key with signing authority");
840 	}
841 
842 	if ((flags & DNS_KEYFLAG_OWNERMASK) == DNS_KEYOWNER_ZONE &&
843 	    (alg == DNS_KEYALG_DH || alg == DST_ALG_HMACMD5 ||
844 	     alg == DST_ALG_HMACSHA1 || alg == DST_ALG_HMACSHA224 ||
845 	     alg == DST_ALG_HMACSHA256 || alg == DST_ALG_HMACSHA384 ||
846 	     alg == DST_ALG_HMACSHA512))
847 		fatal("a key with algorithm '%s' cannot be a zone key",
848 		      algname);
849 
850 	switch(alg) {
851 	case DNS_KEYALG_RSAMD5:
852 	case DNS_KEYALG_RSASHA1:
853 	case DNS_KEYALG_NSEC3RSASHA1:
854 	case DNS_KEYALG_RSASHA256:
855 	case DNS_KEYALG_RSASHA512:
856 		show_progress = ISC_TRUE;
857 		break;
858 
859 	case DNS_KEYALG_DH:
860 		param = generator;
861 		break;
862 
863 	case DNS_KEYALG_DSA:
864 	case DNS_KEYALG_NSEC3DSA:
865 	case DST_ALG_ECCGOST:
866 	case DST_ALG_ECDSA256:
867 	case DST_ALG_ECDSA384:
868 		show_progress = ISC_TRUE;
869 		/* fall through */
870 
871 	case DST_ALG_HMACMD5:
872 	case DST_ALG_HMACSHA1:
873 	case DST_ALG_HMACSHA224:
874 	case DST_ALG_HMACSHA256:
875 	case DST_ALG_HMACSHA384:
876 	case DST_ALG_HMACSHA512:
877 		param = 0;
878 		break;
879 	}
880 
881 	if ((flags & DNS_KEYFLAG_TYPEMASK) == DNS_KEYTYPE_NOKEY)
882 		null_key = ISC_TRUE;
883 
884 	isc_buffer_init(&buf, filename, sizeof(filename) - 1);
885 
886 	do {
887 		conflict = ISC_FALSE;
888 
889 		if (!quiet && show_progress) {
890 			fprintf(stderr, "Generating key pair.");
891 			ret = dst_key_generate2(name, alg, size, param, flags,
892 						protocol, rdclass, mctx, &key,
893 						&progress);
894 			putc('\n', stderr);
895 			fflush(stderr);
896 		} else {
897 			ret = dst_key_generate2(name, alg, size, param, flags,
898 						protocol, rdclass, mctx, &key,
899 						NULL);
900 		}
901 
902 		isc_entropy_stopcallbacksources(ectx);
903 
904 		if (ret != ISC_R_SUCCESS) {
905 			char namestr[DNS_NAME_FORMATSIZE];
906 			char algstr[DNS_SECALG_FORMATSIZE];
907 			dns_name_format(name, namestr, sizeof(namestr));
908 			dns_secalg_format(alg, algstr, sizeof(algstr));
909 			fatal("failed to generate key %s/%s: %s\n",
910 			      namestr, algstr, isc_result_totext(ret));
911 			/* NOTREACHED */
912 			exit(-1);
913 		}
914 
915 		dst_key_setbits(key, dbits);
916 
917 		/*
918 		 * Set key timing metadata (unless using -C)
919 		 *
920 		 * Creation date is always set to "now".
921 		 *
922 		 * For a new key without an explicit predecessor, publish
923 		 * and activation dates are set to "now" by default, but
924 		 * can both be overridden.
925 		 *
926 		 * For a successor key, activation is set to match the
927 		 * predecessor's inactivation date.  Publish is set to 30
928 		 * days earlier than that (XXX: this should be configurable).
929 		 * If either of the resulting dates are in the past, that's
930 		 * an error; the inactivation date of the predecessor key
931 		 * must be updated before a successor key can be created.
932 		 */
933 		if (!oldstyle) {
934 			dst_key_settime(key, DST_TIME_CREATED, now);
935 
936 			if (genonly && (setpub || setact))
937 				fatal("cannot use -G together with "
938 				      "-P or -A options");
939 
940 			if (setpub)
941 				dst_key_settime(key, DST_TIME_PUBLISH, publish);
942 			else if (setact && !unsetpub)
943 				dst_key_settime(key, DST_TIME_PUBLISH,
944 						activate - prepub);
945 			else if (!genonly && !unsetpub)
946 				dst_key_settime(key, DST_TIME_PUBLISH, now);
947 
948 			if (setact)
949 				dst_key_settime(key, DST_TIME_ACTIVATE,
950 						activate);
951 			else if (!genonly && !unsetact)
952 				dst_key_settime(key, DST_TIME_ACTIVATE, now);
953 
954 			if (setrev) {
955 				if (kskflag == 0)
956 					fprintf(stderr, "%s: warning: Key is "
957 						"not flagged as a KSK, but -R "
958 						"was used. Revoking a ZSK is "
959 						"legal, but undefined.\n",
960 						program);
961 				dst_key_settime(key, DST_TIME_REVOKE, revoke);
962 			}
963 
964 			if (setinact)
965 				dst_key_settime(key, DST_TIME_INACTIVE,
966 						inactive);
967 
968 			if (setdel) {
969 				if (setinact && delete < inactive)
970 					fprintf(stderr, "%s: warning: Key is "
971 						"scheduled to be deleted "
972 						"before it is scheduled to be "
973 						"made inactive.\n",
974 						program);
975 				dst_key_settime(key, DST_TIME_DELETE, delete);
976 			}
977 		} else {
978 			if (setpub || setact || setrev || setinact ||
979 			    setdel || unsetpub || unsetact ||
980 			    unsetrev || unsetinact || unsetdel || genonly)
981 				fatal("cannot use -C together with "
982 				      "-P, -A, -R, -I, -D, or -G options");
983 			/*
984 			 * Compatibility mode: Private-key-format
985 			 * should be set to 1.2.
986 			 */
987 			dst_key_setprivateformat(key, 1, 2);
988 		}
989 
990 		/* Set the default key TTL */
991 		if (setttl)
992 			dst_key_setttl(key, ttl);
993 
994 		/*
995 		 * Do not overwrite an existing key, or create a key
996 		 * if there is a risk of ID collision due to this key
997 		 * or another key being revoked.
998 		 */
999 		if (key_collision(key, name, directory, mctx, NULL)) {
1000 			conflict = ISC_TRUE;
1001 			if (null_key) {
1002 				dst_key_free(&key);
1003 				break;
1004 			}
1005 
1006 			if (verbose > 0) {
1007 				isc_buffer_clear(&buf);
1008 				ret = dst_key_buildfilename(key, 0,
1009 							    directory, &buf);
1010 				if (ret == ISC_R_SUCCESS)
1011 					fprintf(stderr,
1012 						"%s: %s already exists, or "
1013 						"might collide with another "
1014 						"key upon revokation.  "
1015 						"Generating a new key\n",
1016 						program, filename);
1017 			}
1018 
1019 			dst_key_free(&key);
1020 		}
1021 	} while (conflict == ISC_TRUE);
1022 
1023 	if (conflict)
1024 		fatal("cannot generate a null key due to possible key ID "
1025 		      "collision");
1026 
1027 	ret = dst_key_tofile(key, options, directory);
1028 	if (ret != ISC_R_SUCCESS) {
1029 		char keystr[DST_KEY_FORMATSIZE];
1030 		dst_key_format(key, keystr, sizeof(keystr));
1031 		fatal("failed to write key %s: %s\n", keystr,
1032 		      isc_result_totext(ret));
1033 	}
1034 
1035 	isc_buffer_clear(&buf);
1036 	ret = dst_key_buildfilename(key, 0, NULL, &buf);
1037 	if (ret != ISC_R_SUCCESS)
1038 		fatal("dst_key_buildfilename returned: %s\n",
1039 		      isc_result_totext(ret));
1040 	printf("%s\n", filename);
1041 	dst_key_free(&key);
1042 	if (prevkey != NULL)
1043 		dst_key_free(&prevkey);
1044 
1045 	cleanup_logging(&log);
1046 	cleanup_entropy(&ectx);
1047 	dst_lib_destroy();
1048 	dns_name_destroy();
1049 	if (verbose > 10)
1050 		isc_mem_stats(mctx, stdout);
1051 	isc_mem_destroy(&mctx);
1052 
1053 	if (freeit != NULL)
1054 		free(freeit);
1055 
1056 	return (0);
1057 }
1058