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