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