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