]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/bin/dnssec/dnssec-signzone.c
Merge tnftp-20100108 from the vendor branch into head.
[FreeBSD/FreeBSD.git] / contrib / bind9 / bin / dnssec / dnssec-signzone.c
1 /*
2  * Portions Copyright (C) 2004-2010  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-signzone.c,v 1.209.12.20 2010-06-03 23:47:48 tbox Exp $ */
33
34 /*! \file */
35
36 #include <config.h>
37
38 #include <stdlib.h>
39 #include <time.h>
40
41 #include <isc/app.h>
42 #include <isc/base32.h>
43 #include <isc/commandline.h>
44 #include <isc/entropy.h>
45 #include <isc/event.h>
46 #include <isc/file.h>
47 #include <isc/hash.h>
48 #include <isc/hex.h>
49 #include <isc/mem.h>
50 #include <isc/mutex.h>
51 #include <isc/os.h>
52 #include <isc/print.h>
53 #include <isc/random.h>
54 #include <isc/rwlock.h>
55 #include <isc/serial.h>
56 #include <isc/stdio.h>
57 #include <isc/stdlib.h>
58 #include <isc/string.h>
59 #include <isc/task.h>
60 #include <isc/time.h>
61 #include <isc/util.h>
62
63 #include <dns/db.h>
64 #include <dns/dbiterator.h>
65 #include <dns/diff.h>
66 #include <dns/dnssec.h>
67 #include <dns/ds.h>
68 #include <dns/fixedname.h>
69 #include <dns/keyvalues.h>
70 #include <dns/log.h>
71 #include <dns/master.h>
72 #include <dns/masterdump.h>
73 #include <dns/nsec.h>
74 #include <dns/nsec3.h>
75 #include <dns/rdata.h>
76 #include <dns/rdatalist.h>
77 #include <dns/rdataset.h>
78 #include <dns/rdataclass.h>
79 #include <dns/rdatasetiter.h>
80 #include <dns/rdatastruct.h>
81 #include <dns/rdatatype.h>
82 #include <dns/result.h>
83 #include <dns/soa.h>
84 #include <dns/time.h>
85
86 #include <dst/dst.h>
87
88 #include "dnssectool.h"
89
90 const char *program = "dnssec-signzone";
91 int verbose;
92
93 typedef struct hashlist hashlist_t;
94
95 static int nsec_datatype = dns_rdatatype_nsec;
96
97 #define IS_NSEC3        (nsec_datatype == dns_rdatatype_nsec3)
98 #define OPTOUT(x)       (((x) & DNS_NSEC3FLAG_OPTOUT) != 0)
99
100 #define BUFSIZE 2048
101 #define MAXDSKEYS 8
102
103 typedef struct signer_key_struct signer_key_t;
104
105 struct signer_key_struct {
106         dst_key_t *key;
107         isc_boolean_t issigningkey;
108         isc_boolean_t isdsk;
109         isc_boolean_t isksk;
110         isc_boolean_t wasused;
111         isc_boolean_t commandline;
112         unsigned int position;
113         ISC_LINK(signer_key_t) link;
114 };
115
116 #define SIGNER_EVENTCLASS       ISC_EVENTCLASS(0x4453)
117 #define SIGNER_EVENT_WRITE      (SIGNER_EVENTCLASS + 0)
118 #define SIGNER_EVENT_WORK       (SIGNER_EVENTCLASS + 1)
119
120 #define SOA_SERIAL_KEEP         0
121 #define SOA_SERIAL_INCREMENT    1
122 #define SOA_SERIAL_UNIXTIME     2
123
124 typedef struct signer_event sevent_t;
125 struct signer_event {
126         ISC_EVENT_COMMON(sevent_t);
127         dns_fixedname_t *fname;
128         dns_dbnode_t *node;
129 };
130
131 static ISC_LIST(signer_key_t) keylist;
132 static unsigned int keycount = 0;
133 isc_rwlock_t keylist_lock;
134 static isc_stdtime_t starttime = 0, endtime = 0, now;
135 static int cycle = -1;
136 static int jitter = 0;
137 static isc_boolean_t tryverify = ISC_FALSE;
138 static isc_boolean_t printstats = ISC_FALSE;
139 static isc_mem_t *mctx = NULL;
140 static isc_entropy_t *ectx = NULL;
141 static dns_ttl_t zonettl;
142 static FILE *fp;
143 static char *tempfile = NULL;
144 static const dns_master_style_t *masterstyle;
145 static dns_masterformat_t inputformat = dns_masterformat_text;
146 static dns_masterformat_t outputformat = dns_masterformat_text;
147 static unsigned int nsigned = 0, nretained = 0, ndropped = 0;
148 static unsigned int nverified = 0, nverifyfailed = 0;
149 static const char *directory;
150 static isc_mutex_t namelock, statslock;
151 static isc_taskmgr_t *taskmgr = NULL;
152 static dns_db_t *gdb;                   /* The database */
153 static dns_dbversion_t *gversion;       /* The database version */
154 static dns_dbiterator_t *gdbiter;       /* The database iterator */
155 static dns_rdataclass_t gclass;         /* The class */
156 static dns_name_t *gorigin;             /* The database origin */
157 static int nsec3flags = 0;
158 static isc_task_t *master = NULL;
159 static unsigned int ntasks = 0;
160 static isc_boolean_t shuttingdown = ISC_FALSE, finished = ISC_FALSE;
161 static isc_boolean_t nokeys = ISC_FALSE;
162 static isc_boolean_t removefile = ISC_FALSE;
163 static isc_boolean_t generateds = ISC_FALSE;
164 static isc_boolean_t ignoreksk = ISC_FALSE;
165 static dns_name_t *dlv = NULL;
166 static dns_fixedname_t dlv_fixed;
167 static dns_master_style_t *dsstyle = NULL;
168 static unsigned int serialformat = SOA_SERIAL_KEEP;
169 static unsigned int hash_length = 0;
170 static isc_boolean_t unknownalg = ISC_FALSE;
171 static isc_boolean_t disable_zone_check = ISC_FALSE;
172
173 #define INCSTAT(counter)                \
174         if (printstats) {               \
175                 LOCK(&statslock);       \
176                 counter++;              \
177                 UNLOCK(&statslock);     \
178         }
179
180 static void
181 sign(isc_task_t *task, isc_event_t *event);
182
183 #define check_dns_dbiterator_current(result) \
184         check_result((result == DNS_R_NEWORIGIN) ? ISC_R_SUCCESS : result, \
185                      "dns_dbiterator_current()")
186
187 static void
188 dumpnode(dns_name_t *name, dns_dbnode_t *node) {
189         isc_result_t result;
190
191         if (outputformat != dns_masterformat_text)
192                 return;
193         result = dns_master_dumpnodetostream(mctx, gdb, gversion, node, name,
194                                              masterstyle, fp);
195         check_result(result, "dns_master_dumpnodetostream");
196 }
197
198 static signer_key_t *
199 newkeystruct(dst_key_t *dstkey, isc_boolean_t signwithkey) {
200         signer_key_t *key;
201
202         key = isc_mem_get(mctx, sizeof(signer_key_t));
203         if (key == NULL)
204                 fatal("out of memory");
205         key->key = dstkey;
206         if ((dst_key_flags(dstkey) & DNS_KEYFLAG_KSK) != 0) {
207                 key->issigningkey = signwithkey;
208                 key->isksk = ISC_TRUE;
209                 key->isdsk = ISC_FALSE;
210         } else {
211                 key->issigningkey = signwithkey;
212                 key->isksk = ISC_FALSE;
213                 key->isdsk = ISC_TRUE;
214         }
215         key->wasused = ISC_FALSE;
216         key->commandline = ISC_FALSE;
217         key->position = keycount++;
218         ISC_LINK_INIT(key, link);
219         return (key);
220 }
221
222 /*%
223  * Sign the given RRset with given key, and add the signature record to the
224  * given tuple.
225  */
226
227 static void
228 signwithkey(dns_name_t *name, dns_rdataset_t *rdataset, dst_key_t *key,
229             dns_ttl_t ttl, dns_diff_t *add, const char *logmsg)
230 {
231         isc_result_t result;
232         isc_stdtime_t jendtime;
233         char keystr[KEY_FORMATSIZE];
234         dns_rdata_t trdata = DNS_RDATA_INIT;
235         unsigned char array[BUFSIZE];
236         isc_buffer_t b;
237         dns_difftuple_t *tuple;
238
239         key_format(key, keystr, sizeof(keystr));
240         vbprintf(1, "\t%s %s\n", logmsg, keystr);
241
242         jendtime = (jitter != 0) ? isc_random_jitter(endtime, jitter) : endtime;
243         isc_buffer_init(&b, array, sizeof(array));
244         result = dns_dnssec_sign(name, rdataset, key, &starttime, &jendtime,
245                                  mctx, &b, &trdata);
246         isc_entropy_stopcallbacksources(ectx);
247         if (result != ISC_R_SUCCESS) {
248                 char keystr[KEY_FORMATSIZE];
249                 key_format(key, keystr, sizeof(keystr));
250                 fatal("dnskey '%s' failed to sign data: %s",
251                       keystr, isc_result_totext(result));
252         }
253         INCSTAT(nsigned);
254
255         if (tryverify) {
256                 result = dns_dnssec_verify(name, rdataset, key,
257                                            ISC_TRUE, mctx, &trdata);
258                 if (result == ISC_R_SUCCESS) {
259                         vbprintf(3, "\tsignature verified\n");
260                         INCSTAT(nverified);
261                 } else {
262                         vbprintf(3, "\tsignature failed to verify\n");
263                         INCSTAT(nverifyfailed);
264                 }
265         }
266
267         tuple = NULL;
268         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD, name, ttl, &trdata,
269                                       &tuple);
270         check_result(result, "dns_difftuple_create");
271         dns_diff_append(add, &tuple);
272 }
273
274 static inline isc_boolean_t
275 issigningkey(signer_key_t *key) {
276         return (key->issigningkey);
277 }
278
279 static inline isc_boolean_t
280 iszonekey(signer_key_t *key) {
281         return (ISC_TF(dns_name_equal(dst_key_name(key->key), gorigin) &&
282                        dst_key_iszonekey(key->key)));
283 }
284
285 /*%
286  * Find the key if it is in our list.  If it is, return it, otherwise null.
287  * No locking is performed here, this must be done by the caller.
288  */
289 static signer_key_t *
290 keythatsigned_unlocked(dns_rdata_rrsig_t *rrsig) {
291         signer_key_t *key;
292
293         key = ISC_LIST_HEAD(keylist);
294         while (key != NULL) {
295                 if (rrsig->keyid == dst_key_id(key->key) &&
296                     rrsig->algorithm == dst_key_alg(key->key) &&
297                     dns_name_equal(&rrsig->signer, dst_key_name(key->key)))
298                         return (key);
299                 key = ISC_LIST_NEXT(key, link);
300         }
301         return (NULL);
302 }
303
304 /*%
305  * Finds the key that generated a RRSIG, if possible.  First look at the keys
306  * that we've loaded already, and then see if there's a key on disk.
307  */
308 static signer_key_t *
309 keythatsigned(dns_rdata_rrsig_t *rrsig) {
310         isc_result_t result;
311         dst_key_t *pubkey = NULL, *privkey = NULL;
312         signer_key_t *key;
313
314         isc_rwlock_lock(&keylist_lock, isc_rwlocktype_read);
315         key = keythatsigned_unlocked(rrsig);
316         isc_rwlock_unlock(&keylist_lock, isc_rwlocktype_read);
317         if (key != NULL)
318                 return (key);
319
320         /*
321          * We did not find the key in our list.  Get a write lock now, since
322          * we may be modifying the bits.  We could do the tryupgrade() dance,
323          * but instead just get a write lock and check once again to see if
324          * it is on our list.  It's possible someone else may have added it
325          * after all.
326          */
327         isc_rwlock_lock(&keylist_lock, isc_rwlocktype_write);
328
329         key = keythatsigned_unlocked(rrsig);
330         if (key != NULL) {
331                 isc_rwlock_unlock(&keylist_lock, isc_rwlocktype_write);
332                 return (key);
333         }
334
335         result = dst_key_fromfile(&rrsig->signer, rrsig->keyid,
336                                   rrsig->algorithm, DST_TYPE_PUBLIC,
337                                   NULL, mctx, &pubkey);
338         if (result != ISC_R_SUCCESS) {
339                 isc_rwlock_unlock(&keylist_lock, isc_rwlocktype_write);
340                 return (NULL);
341         }
342
343         result = dst_key_fromfile(&rrsig->signer, rrsig->keyid,
344                                   rrsig->algorithm,
345                                   DST_TYPE_PUBLIC | DST_TYPE_PRIVATE,
346                                   NULL, mctx, &privkey);
347         if (result == ISC_R_SUCCESS) {
348                 dst_key_free(&pubkey);
349                 key = newkeystruct(privkey, ISC_FALSE);
350         } else
351                 key = newkeystruct(pubkey, ISC_FALSE);
352         ISC_LIST_APPEND(keylist, key, link);
353
354         isc_rwlock_unlock(&keylist_lock, isc_rwlocktype_write);
355         return (key);
356 }
357
358 /*%
359  * Check to see if we expect to find a key at this name.  If we see a RRSIG
360  * and can't find the signing key that we expect to find, we drop the rrsig.
361  * I'm not sure if this is completely correct, but it seems to work.
362  */
363 static isc_boolean_t
364 expecttofindkey(dns_name_t *name) {
365         unsigned int options = DNS_DBFIND_NOWILD;
366         dns_fixedname_t fname;
367         isc_result_t result;
368         char namestr[DNS_NAME_FORMATSIZE];
369
370         dns_fixedname_init(&fname);
371         result = dns_db_find(gdb, name, gversion, dns_rdatatype_dnskey, options,
372                              0, NULL, dns_fixedname_name(&fname), NULL, NULL);
373         switch (result) {
374         case ISC_R_SUCCESS:
375         case DNS_R_NXDOMAIN:
376         case DNS_R_NXRRSET:
377                 return (ISC_TRUE);
378         case DNS_R_DELEGATION:
379         case DNS_R_CNAME:
380         case DNS_R_DNAME:
381                 return (ISC_FALSE);
382         }
383         dns_name_format(name, namestr, sizeof(namestr));
384         fatal("failure looking for '%s DNSKEY' in database: %s",
385               namestr, isc_result_totext(result));
386         return (ISC_FALSE); /* removes a warning */
387 }
388
389 static inline isc_boolean_t
390 setverifies(dns_name_t *name, dns_rdataset_t *set, signer_key_t *key,
391             dns_rdata_t *rrsig)
392 {
393         isc_result_t result;
394         result = dns_dnssec_verify(name, set, key->key, ISC_FALSE, mctx, rrsig);
395         if (result == ISC_R_SUCCESS) {
396                 INCSTAT(nverified);
397                 return (ISC_TRUE);
398         } else {
399                 INCSTAT(nverifyfailed);
400                 return (ISC_FALSE);
401         }
402 }
403
404 /*%
405  * Signs a set.  Goes through contortions to decide if each RRSIG should
406  * be dropped or retained, and then determines if any new SIGs need to
407  * be generated.
408  */
409 static void
410 signset(dns_diff_t *del, dns_diff_t *add, dns_dbnode_t *node, dns_name_t *name,
411         dns_rdataset_t *set)
412 {
413         dns_rdataset_t sigset;
414         dns_rdata_t sigrdata = DNS_RDATA_INIT;
415         dns_rdata_rrsig_t rrsig;
416         signer_key_t *key;
417         isc_result_t result;
418         isc_boolean_t nosigs = ISC_FALSE;
419         isc_boolean_t *wassignedby, *nowsignedby;
420         int arraysize;
421         dns_difftuple_t *tuple;
422         dns_ttl_t ttl;
423         int i;
424         char namestr[DNS_NAME_FORMATSIZE];
425         char typestr[TYPE_FORMATSIZE];
426         char sigstr[SIG_FORMATSIZE];
427
428         dns_name_format(name, namestr, sizeof(namestr));
429         type_format(set->type, typestr, sizeof(typestr));
430
431         ttl = ISC_MIN(set->ttl, endtime - starttime);
432
433         dns_rdataset_init(&sigset);
434         result = dns_db_findrdataset(gdb, node, gversion, dns_rdatatype_rrsig,
435                                      set->type, 0, &sigset, NULL);
436         if (result == ISC_R_NOTFOUND) {
437                 result = ISC_R_SUCCESS;
438                 nosigs = ISC_TRUE;
439         }
440         if (result != ISC_R_SUCCESS)
441                 fatal("failed while looking for '%s RRSIG %s': %s",
442                       namestr, typestr, isc_result_totext(result));
443
444         vbprintf(1, "%s/%s:\n", namestr, typestr);
445
446         arraysize = keycount;
447         if (!nosigs)
448                 arraysize += dns_rdataset_count(&sigset);
449         wassignedby = isc_mem_get(mctx, arraysize * sizeof(isc_boolean_t));
450         nowsignedby = isc_mem_get(mctx, arraysize * sizeof(isc_boolean_t));
451         if (wassignedby == NULL || nowsignedby == NULL)
452                 fatal("out of memory");
453
454         for (i = 0; i < arraysize; i++)
455                 wassignedby[i] = nowsignedby[i] = ISC_FALSE;
456
457         if (nosigs)
458                 result = ISC_R_NOMORE;
459         else
460                 result = dns_rdataset_first(&sigset);
461
462         while (result == ISC_R_SUCCESS) {
463                 isc_boolean_t expired, future;
464                 isc_boolean_t keep = ISC_FALSE, resign = ISC_FALSE;
465
466                 dns_rdataset_current(&sigset, &sigrdata);
467
468                 result = dns_rdata_tostruct(&sigrdata, &rrsig, NULL);
469                 check_result(result, "dns_rdata_tostruct");
470
471                 future = isc_serial_lt(now, rrsig.timesigned);
472
473                 key = keythatsigned(&rrsig);
474                 sig_format(&rrsig, sigstr, sizeof(sigstr));
475                 if (key != NULL && issigningkey(key))
476                         expired = isc_serial_gt(now + cycle, rrsig.timeexpire);
477                 else
478                         expired = isc_serial_gt(now, rrsig.timeexpire);
479
480                 if (isc_serial_gt(rrsig.timesigned, rrsig.timeexpire)) {
481                         /* rrsig is dropped and not replaced */
482                         vbprintf(2, "\trrsig by %s dropped - "
483                                  "invalid validity period\n",
484                                  sigstr);
485                 } else if (key == NULL && !future &&
486                          expecttofindkey(&rrsig.signer))
487                 {
488                         /* rrsig is dropped and not replaced */
489                         vbprintf(2, "\trrsig by %s dropped - "
490                                  "private dnskey not found\n",
491                                  sigstr);
492                 } else if (key == NULL || future) {
493                         vbprintf(2, "\trrsig by %s %s - dnskey not found\n",
494                                  expired ? "retained" : "dropped", sigstr);
495                         if (!expired)
496                                 keep = ISC_TRUE;
497                 } else if (issigningkey(key)) {
498                         if (!expired && setverifies(name, set, key, &sigrdata))
499                         {
500                                 vbprintf(2, "\trrsig by %s retained\n", sigstr);
501                                 keep = ISC_TRUE;
502                                 wassignedby[key->position] = ISC_TRUE;
503                                 nowsignedby[key->position] = ISC_TRUE;
504                                 key->wasused = ISC_TRUE;
505                         } else {
506                                 vbprintf(2, "\trrsig by %s dropped - %s\n",
507                                          sigstr,
508                                          expired ? "expired" :
509                                                    "failed to verify");
510                                 wassignedby[key->position] = ISC_TRUE;
511                                 resign = ISC_TRUE;
512                         }
513                 } else if (iszonekey(key)) {
514                         if (!expired && setverifies(name, set, key, &sigrdata))
515                         {
516                                 vbprintf(2, "\trrsig by %s retained\n", sigstr);
517                                 keep = ISC_TRUE;
518                                 wassignedby[key->position] = ISC_TRUE;
519                                 nowsignedby[key->position] = ISC_TRUE;
520                                 key->wasused = ISC_TRUE;
521                         } else {
522                                 vbprintf(2, "\trrsig by %s dropped - %s\n",
523                                          sigstr,
524                                          expired ? "expired" :
525                                                    "failed to verify");
526                                 wassignedby[key->position] = ISC_TRUE;
527                         }
528                 } else if (!expired) {
529                         vbprintf(2, "\trrsig by %s retained\n", sigstr);
530                         keep = ISC_TRUE;
531                 } else {
532                         vbprintf(2, "\trrsig by %s expired\n", sigstr);
533                 }
534
535                 if (keep) {
536                         nowsignedby[key->position] = ISC_TRUE;
537                         INCSTAT(nretained);
538                         if (sigset.ttl != ttl) {
539                                 vbprintf(2, "\tfixing ttl %s\n", sigstr);
540                                 tuple = NULL;
541                                 result = dns_difftuple_create(mctx,
542                                                               DNS_DIFFOP_DEL,
543                                                               name, sigset.ttl,
544                                                               &sigrdata,
545                                                               &tuple);
546                                 check_result(result, "dns_difftuple_create");
547                                 dns_diff_append(del, &tuple);
548                                 result = dns_difftuple_create(mctx,
549                                                               DNS_DIFFOP_ADD,
550                                                               name, ttl,
551                                                               &sigrdata,
552                                                               &tuple);
553                                 check_result(result, "dns_difftuple_create");
554                                 dns_diff_append(add, &tuple);
555                         }
556                 } else {
557                         tuple = NULL;
558                         result = dns_difftuple_create(mctx, DNS_DIFFOP_DEL,
559                                                       name, sigset.ttl,
560                                                       &sigrdata, &tuple);
561                         check_result(result, "dns_difftuple_create");
562                         dns_diff_append(del, &tuple);
563                         INCSTAT(ndropped);
564                 }
565
566                 if (resign) {
567                         INSIST(!keep);
568
569                         signwithkey(name, set, key->key, ttl, add,
570                                     "resigning with dnskey");
571                         nowsignedby[key->position] = ISC_TRUE;
572                         key->wasused = ISC_TRUE;
573                 }
574
575                 dns_rdata_reset(&sigrdata);
576                 dns_rdata_freestruct(&rrsig);
577                 result = dns_rdataset_next(&sigset);
578         }
579         if (result == ISC_R_NOMORE)
580                 result = ISC_R_SUCCESS;
581
582         check_result(result, "dns_rdataset_first/next");
583         if (dns_rdataset_isassociated(&sigset))
584                 dns_rdataset_disassociate(&sigset);
585
586         for (key = ISC_LIST_HEAD(keylist);
587              key != NULL;
588              key = ISC_LIST_NEXT(key, link))
589         {
590                 if (nowsignedby[key->position])
591                         continue;
592
593                 if (!key->issigningkey)
594                         continue;
595                 if (!(ignoreksk || key->isdsk ||
596                       (key->isksk &&
597                        set->type == dns_rdatatype_dnskey &&
598                        dns_name_equal(name, gorigin))))
599                         continue;
600
601                 signwithkey(name, set, key->key, ttl, add,
602                             "signing with dnskey");
603                 key->wasused = ISC_TRUE;
604         }
605
606         isc_mem_put(mctx, wassignedby, arraysize * sizeof(isc_boolean_t));
607         isc_mem_put(mctx, nowsignedby, arraysize * sizeof(isc_boolean_t));
608 }
609
610 struct hashlist {
611         unsigned char *hashbuf;
612         size_t entries;
613         size_t size;
614         size_t length;
615 };
616
617 static void
618 hashlist_init(hashlist_t *l, unsigned int nodes, unsigned int length) {
619
620         l->entries = 0;
621         l->length = length + 1;
622
623         if (nodes != 0) {
624                 l->size = nodes;
625                 l->hashbuf = malloc(l->size * l->length);
626                 if (l->hashbuf == NULL)
627                         l->size = 0;
628         } else {
629                 l->size = 0;
630                 l->hashbuf = NULL;
631         }
632 }
633
634 static void
635 hashlist_add(hashlist_t *l, const unsigned char *hash, size_t len)
636 {
637
638         REQUIRE(len <= l->length);
639
640         if (l->entries == l->size) {
641                 l->size = l->size * 2 + 100;
642                 l->hashbuf = realloc(l->hashbuf, l->size * l->length);
643         }
644         memset(l->hashbuf + l->entries * l->length, 0, l->length);
645         memcpy(l->hashbuf + l->entries * l->length, hash, len);
646         l->entries++;
647 }
648
649 static void
650 hashlist_add_dns_name(hashlist_t *l, /*const*/ dns_name_t *name,
651                       unsigned int hashalg, unsigned int iterations,
652                       const unsigned char *salt, size_t salt_length,
653                       isc_boolean_t speculative)
654 {
655         char nametext[DNS_NAME_FORMATSIZE];
656         unsigned char hash[NSEC3_MAX_HASH_LENGTH + 1];
657         unsigned int len;
658         size_t i;
659
660         len = isc_iterated_hash(hash, hashalg, iterations, salt, salt_length,
661                                 name->ndata, name->length);
662         if (verbose) {
663                 dns_name_format(name, nametext, sizeof nametext);
664                 for (i = 0 ; i < len; i++)
665                         fprintf(stderr, "%02x", hash[i]);
666                 fprintf(stderr, " %s\n", nametext);
667         }
668         hash[len++] = speculative ? 1 : 0;
669         hashlist_add(l, hash, len);
670 }
671
672 static int
673 hashlist_comp(const void *a, const void *b) {
674         return (memcmp(a, b, hash_length + 1));
675 }
676
677 static void
678 hashlist_sort(hashlist_t *l) {
679         qsort(l->hashbuf, l->entries, l->length, hashlist_comp);
680 }
681
682 static isc_boolean_t
683 hashlist_hasdup(hashlist_t *l) {
684         unsigned char *current;
685         unsigned char *next = l->hashbuf;
686         size_t entries = l->entries;
687
688         /*
689          * Skip initial speculative wild card hashs.
690          */
691         while (entries > 0U && next[l->length-1] != 0U) {
692                 next += l->length;
693                 entries--;
694         }
695
696         current = next;
697         while (entries-- > 1U) {
698                 next += l->length;
699                 if (next[l->length-1] != 0)
700                         continue;
701                 if (memcmp(current, next, l->length - 1) == 0)
702                         return (ISC_TRUE);
703                 current = next;
704         }
705         return (ISC_FALSE);
706 }
707
708 static const unsigned char *
709 hashlist_findnext(const hashlist_t *l,
710                   const unsigned char hash[NSEC3_MAX_HASH_LENGTH])
711 {
712         unsigned int entries = l->entries;
713         const unsigned char *next = bsearch(hash, l->hashbuf, l->entries,
714                                             l->length, hashlist_comp);
715         INSIST(next != NULL);
716
717         do {
718                 if (next < l->hashbuf + (l->entries - 1) * l->length)
719                         next += l->length;
720                 else
721                         next = l->hashbuf;
722                 if (next[l->length - 1] == 0)
723                         break;
724         } while (entries-- > 1);
725         INSIST(entries != 0);
726         return (next);
727 }
728
729 static isc_boolean_t
730 hashlist_exists(const hashlist_t *l,
731                 const unsigned char hash[NSEC3_MAX_HASH_LENGTH])
732 {
733         if (bsearch(hash, l->hashbuf, l->entries, l->length, hashlist_comp))
734                 return (ISC_TRUE);
735         else
736                 return (ISC_FALSE);
737 }
738
739 static void
740 addnowildcardhash(hashlist_t *l, /*const*/ dns_name_t *name,
741                   unsigned int hashalg, unsigned int iterations,
742                   const unsigned char *salt, size_t salt_length)
743 {
744         dns_fixedname_t fixed;
745         dns_name_t *wild;
746         dns_dbnode_t *node = NULL;
747         isc_result_t result;
748         char namestr[DNS_NAME_FORMATSIZE];
749
750         dns_fixedname_init(&fixed);
751         wild = dns_fixedname_name(&fixed);
752
753         result = dns_name_concatenate(dns_wildcardname, name, wild, NULL);
754         if (result == ISC_R_NOSPACE)
755                 return;
756         check_result(result,"addnowildcardhash: dns_name_concatenate()");
757
758         result = dns_db_findnode(gdb, wild, ISC_FALSE, &node);
759         if (result == ISC_R_SUCCESS) {
760                 dns_db_detachnode(gdb, &node);
761                 return;
762         }
763
764         if (verbose) {
765                 dns_name_format(wild, namestr, sizeof(namestr));
766                 fprintf(stderr, "adding no-wildcardhash for %s\n", namestr);
767         }
768
769         hashlist_add_dns_name(l, wild, hashalg, iterations, salt, salt_length,
770                               ISC_TRUE);
771 }
772
773 static void
774 opendb(const char *prefix, dns_name_t *name, dns_rdataclass_t rdclass,
775        dns_db_t **dbp)
776 {
777         char filename[256];
778         isc_buffer_t b;
779         isc_result_t result;
780
781         isc_buffer_init(&b, filename, sizeof(filename));
782         if (directory != NULL) {
783                 isc_buffer_putstr(&b, directory);
784                 if (directory[strlen(directory) - 1] != '/')
785                         isc_buffer_putstr(&b, "/");
786         }
787         isc_buffer_putstr(&b, prefix);
788         result = dns_name_tofilenametext(name, ISC_FALSE, &b);
789         check_result(result, "dns_name_tofilenametext()");
790         if (isc_buffer_availablelength(&b) == 0) {
791                 char namestr[DNS_NAME_FORMATSIZE];
792                 dns_name_format(name, namestr, sizeof(namestr));
793                 fatal("name '%s' is too long", namestr);
794         }
795         isc_buffer_putuint8(&b, 0);
796
797         result = dns_db_create(mctx, "rbt", dns_rootname, dns_dbtype_zone,
798                                rdclass, 0, NULL, dbp);
799         check_result(result, "dns_db_create()");
800
801         result = dns_db_load(*dbp, filename);
802         if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE)
803                 dns_db_detach(dbp);
804 }
805
806 /*%
807  * Loads the key set for a child zone, if there is one, and builds DS records.
808  */
809 static isc_result_t
810 loadds(dns_name_t *name, isc_uint32_t ttl, dns_rdataset_t *dsset) {
811         dns_db_t *db = NULL;
812         dns_dbversion_t *ver = NULL;
813         dns_dbnode_t *node = NULL;
814         isc_result_t result;
815         dns_rdataset_t keyset;
816         dns_rdata_t key, ds;
817         unsigned char dsbuf[DNS_DS_BUFFERSIZE];
818         dns_diff_t diff;
819         dns_difftuple_t *tuple = NULL;
820
821         opendb("keyset-", name, gclass, &db);
822         if (db == NULL)
823                 return (ISC_R_NOTFOUND);
824
825         result = dns_db_findnode(db, name, ISC_FALSE, &node);
826         if (result != ISC_R_SUCCESS) {
827                 dns_db_detach(&db);
828                 return (DNS_R_BADDB);
829         }
830         dns_rdataset_init(&keyset);
831         result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_dnskey, 0,
832                                      0, &keyset, NULL);
833         if (result != ISC_R_SUCCESS) {
834                 dns_db_detachnode(db, &node);
835                 dns_db_detach(&db);
836                 return (result);
837         }
838
839         vbprintf(2, "found DNSKEY records\n");
840
841         result = dns_db_newversion(db, &ver);
842         check_result(result, "dns_db_newversion");
843
844         dns_diff_init(mctx, &diff);
845
846         for (result = dns_rdataset_first(&keyset);
847              result == ISC_R_SUCCESS;
848              result = dns_rdataset_next(&keyset))
849         {
850                 dns_rdata_init(&key);
851                 dns_rdata_init(&ds);
852                 dns_rdataset_current(&keyset, &key);
853                 result = dns_ds_buildrdata(name, &key, DNS_DSDIGEST_SHA1,
854                                            dsbuf, &ds);
855                 check_result(result, "dns_ds_buildrdata");
856
857                 result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD, name,
858                                               ttl, &ds, &tuple);
859                 check_result(result, "dns_difftuple_create");
860                 dns_diff_append(&diff, &tuple);
861
862                 dns_rdata_reset(&ds);
863                 result = dns_ds_buildrdata(name, &key, DNS_DSDIGEST_SHA256,
864                                            dsbuf, &ds);
865                 check_result(result, "dns_ds_buildrdata");
866
867                 result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD, name,
868                                               ttl, &ds, &tuple);
869                 check_result(result, "dns_difftuple_create");
870                 dns_diff_append(&diff, &tuple);
871         }
872         result = dns_diff_apply(&diff, db, ver);
873         check_result(result, "dns_diff_apply");
874         dns_diff_clear(&diff);
875
876         dns_db_closeversion(db, &ver, ISC_TRUE);
877
878         result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_ds, 0, 0,
879                                      dsset, NULL);
880         check_result(result, "dns_db_findrdataset");
881
882         dns_rdataset_disassociate(&keyset);
883         dns_db_detachnode(db, &node);
884         dns_db_detach(&db);
885         return (result);
886 }
887
888 static isc_boolean_t
889 delegation(dns_name_t *name, dns_dbnode_t *node, isc_uint32_t *ttlp) {
890         dns_rdataset_t nsset;
891         isc_result_t result;
892
893         if (dns_name_equal(name, gorigin))
894                 return (ISC_FALSE);
895
896         dns_rdataset_init(&nsset);
897         result = dns_db_findrdataset(gdb, node, gversion, dns_rdatatype_ns,
898                                      0, 0, &nsset, NULL);
899         if (dns_rdataset_isassociated(&nsset)) {
900                 if (ttlp != NULL)
901                         *ttlp = nsset.ttl;
902                 dns_rdataset_disassociate(&nsset);
903         }
904
905         return (ISC_TF(result == ISC_R_SUCCESS));
906 }
907
908 static isc_boolean_t
909 secure(dns_name_t *name, dns_dbnode_t *node) {
910         dns_rdataset_t dsset;
911         isc_result_t result;
912
913         if (dns_name_equal(name, gorigin))
914                 return (ISC_FALSE);
915
916         dns_rdataset_init(&dsset);
917         result = dns_db_findrdataset(gdb, node, gversion, dns_rdatatype_ds,
918                                      0, 0, &dsset, NULL);
919         if (dns_rdataset_isassociated(&dsset))
920                 dns_rdataset_disassociate(&dsset);
921
922         return (ISC_TF(result == ISC_R_SUCCESS));
923 }
924
925 /*%
926  * Signs all records at a name.
927  */
928 static void
929 signname(dns_dbnode_t *node, dns_name_t *name) {
930         isc_result_t result;
931         dns_rdataset_t rdataset;
932         dns_rdatasetiter_t *rdsiter;
933         isc_boolean_t isdelegation = ISC_FALSE;
934         dns_diff_t del, add;
935         char namestr[DNS_NAME_FORMATSIZE];
936
937         dns_rdataset_init(&rdataset);
938         dns_name_format(name, namestr, sizeof(namestr));
939
940         /*
941          * Determine if this is a delegation point.
942          */
943         if (delegation(name, node, NULL))
944                 isdelegation = ISC_TRUE;
945
946         /*
947          * Now iterate through the rdatasets.
948          */
949         dns_diff_init(mctx, &del);
950         dns_diff_init(mctx, &add);
951         rdsiter = NULL;
952         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
953         check_result(result, "dns_db_allrdatasets()");
954         result = dns_rdatasetiter_first(rdsiter);
955         while (result == ISC_R_SUCCESS) {
956                 dns_rdatasetiter_current(rdsiter, &rdataset);
957
958                 /* If this is a RRSIG set, skip it. */
959                 if (rdataset.type == dns_rdatatype_rrsig)
960                         goto skip;
961
962                 /*
963                  * If this name is a delegation point, skip all records
964                  * except NSEC and DS sets.  Otherwise check that there
965                  * isn't a DS record.
966                  */
967                 if (isdelegation) {
968                         if (rdataset.type != nsec_datatype &&
969                             rdataset.type != dns_rdatatype_ds)
970                                 goto skip;
971                 } else if (rdataset.type == dns_rdatatype_ds) {
972                         char namebuf[DNS_NAME_FORMATSIZE];
973                         dns_name_format(name, namebuf, sizeof(namebuf));
974                         fatal("'%s': found DS RRset without NS RRset\n",
975                               namebuf);
976                 }
977
978                 signset(&del, &add, node, name, &rdataset);
979
980  skip:
981                 dns_rdataset_disassociate(&rdataset);
982                 result = dns_rdatasetiter_next(rdsiter);
983         }
984         if (result != ISC_R_NOMORE)
985                 fatal("rdataset iteration for name '%s' failed: %s",
986                       namestr, isc_result_totext(result));
987
988         dns_rdatasetiter_destroy(&rdsiter);
989
990         result = dns_diff_applysilently(&del, gdb, gversion);
991         if (result != ISC_R_SUCCESS)
992                 fatal("failed to delete SIGs at node '%s': %s",
993                       namestr, isc_result_totext(result));
994
995         result = dns_diff_applysilently(&add, gdb, gversion);
996         if (result != ISC_R_SUCCESS)
997                 fatal("failed to add SIGs at node '%s': %s",
998                       namestr, isc_result_totext(result));
999
1000         dns_diff_clear(&del);
1001         dns_diff_clear(&add);
1002 }
1003
1004 static inline isc_boolean_t
1005 active_node(dns_dbnode_t *node) {
1006         dns_rdatasetiter_t *rdsiter = NULL;
1007         dns_rdatasetiter_t *rdsiter2 = NULL;
1008         isc_boolean_t active = ISC_FALSE;
1009         isc_result_t result;
1010         dns_rdataset_t rdataset;
1011         dns_rdatatype_t type;
1012         dns_rdatatype_t covers;
1013         isc_boolean_t found;
1014
1015         dns_rdataset_init(&rdataset);
1016         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1017         check_result(result, "dns_db_allrdatasets()");
1018         result = dns_rdatasetiter_first(rdsiter);
1019         while (result == ISC_R_SUCCESS) {
1020                 dns_rdatasetiter_current(rdsiter, &rdataset);
1021                 if (rdataset.type != dns_rdatatype_nsec &&
1022                     rdataset.type != dns_rdatatype_nsec3 &&
1023                     rdataset.type != dns_rdatatype_rrsig)
1024                         active = ISC_TRUE;
1025                 dns_rdataset_disassociate(&rdataset);
1026                 if (!active)
1027                         result = dns_rdatasetiter_next(rdsiter);
1028                 else
1029                         result = ISC_R_NOMORE;
1030         }
1031         if (result != ISC_R_NOMORE)
1032                 fatal("rdataset iteration failed: %s",
1033                       isc_result_totext(result));
1034
1035         if (!active && nsec_datatype == dns_rdatatype_nsec) {
1036                 /*%
1037                  * The node is empty of everything but NSEC / RRSIG records.
1038                  */
1039                 for (result = dns_rdatasetiter_first(rdsiter);
1040                      result == ISC_R_SUCCESS;
1041                      result = dns_rdatasetiter_next(rdsiter)) {
1042                         dns_rdatasetiter_current(rdsiter, &rdataset);
1043                         result = dns_db_deleterdataset(gdb, node, gversion,
1044                                                        rdataset.type,
1045                                                        rdataset.covers);
1046                         check_result(result, "dns_db_deleterdataset()");
1047                         dns_rdataset_disassociate(&rdataset);
1048                 }
1049                 if (result != ISC_R_NOMORE)
1050                         fatal("rdataset iteration failed: %s",
1051                               isc_result_totext(result));
1052         } else {
1053                 /*
1054                  * Delete RRSIGs for types that no longer exist.
1055                  */
1056                 result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter2);
1057                 check_result(result, "dns_db_allrdatasets()");
1058                 for (result = dns_rdatasetiter_first(rdsiter);
1059                      result == ISC_R_SUCCESS;
1060                      result = dns_rdatasetiter_next(rdsiter)) {
1061                         dns_rdatasetiter_current(rdsiter, &rdataset);
1062                         type = rdataset.type;
1063                         covers = rdataset.covers;
1064                         dns_rdataset_disassociate(&rdataset);
1065                         /*
1066                          * Delete the NSEC chain if we are signing with
1067                          * NSEC3.
1068                          */
1069                         if (nsec_datatype == dns_rdatatype_nsec3 &&
1070                             (type == dns_rdatatype_nsec ||
1071                              covers == dns_rdatatype_nsec)) {
1072                                 result = dns_db_deleterdataset(gdb, node,
1073                                                                gversion, type,
1074                                                                covers);
1075                                 check_result(result,
1076                                            "dns_db_deleterdataset(nsec/rrsig)");
1077                                 continue;
1078                         }
1079                         if (type != dns_rdatatype_rrsig)
1080                                 continue;
1081                         found = ISC_FALSE;
1082                         for (result = dns_rdatasetiter_first(rdsiter2);
1083                              !found && result == ISC_R_SUCCESS;
1084                              result = dns_rdatasetiter_next(rdsiter2)) {
1085                                 dns_rdatasetiter_current(rdsiter2, &rdataset);
1086                                 if (rdataset.type == covers)
1087                                         found = ISC_TRUE;
1088                                 dns_rdataset_disassociate(&rdataset);
1089                         }
1090                         if (!found) {
1091                                 if (result != ISC_R_NOMORE)
1092                                         fatal("rdataset iteration failed: %s",
1093                                               isc_result_totext(result));
1094                                 result = dns_db_deleterdataset(gdb, node,
1095                                                                gversion, type,
1096                                                                covers);
1097                                 check_result(result,
1098                                              "dns_db_deleterdataset(rrsig)");
1099                         } else if (result != ISC_R_NOMORE &&
1100                                    result != ISC_R_SUCCESS)
1101                                 fatal("rdataset iteration failed: %s",
1102                                       isc_result_totext(result));
1103                 }
1104                 if (result != ISC_R_NOMORE)
1105                         fatal("rdataset iteration failed: %s",
1106                               isc_result_totext(result));
1107                 dns_rdatasetiter_destroy(&rdsiter2);
1108         }
1109         dns_rdatasetiter_destroy(&rdsiter);
1110
1111         return (active);
1112 }
1113
1114 /*%
1115  * Extracts the TTL from the SOA.
1116  */
1117 static dns_ttl_t
1118 soattl(void) {
1119         dns_rdataset_t soaset;
1120         dns_fixedname_t fname;
1121         dns_name_t *name;
1122         isc_result_t result;
1123         dns_ttl_t ttl;
1124         dns_rdata_t rdata = DNS_RDATA_INIT;
1125         dns_rdata_soa_t soa;
1126
1127         dns_fixedname_init(&fname);
1128         name = dns_fixedname_name(&fname);
1129         dns_rdataset_init(&soaset);
1130         result = dns_db_find(gdb, gorigin, gversion, dns_rdatatype_soa,
1131                              0, 0, NULL, name, &soaset, NULL);
1132         if (result != ISC_R_SUCCESS)
1133                 fatal("failed to find an SOA at the zone apex: %s",
1134                       isc_result_totext(result));
1135
1136         result = dns_rdataset_first(&soaset);
1137         check_result(result, "dns_rdataset_first");
1138         dns_rdataset_current(&soaset, &rdata);
1139         result = dns_rdata_tostruct(&rdata, &soa, NULL);
1140         check_result(result, "dns_rdata_tostruct");
1141         ttl = soa.minimum;
1142         dns_rdataset_disassociate(&soaset);
1143         return (ttl);
1144 }
1145
1146 /*%
1147  * Increment (or set if nonzero) the SOA serial
1148  */
1149 static isc_result_t
1150 setsoaserial(isc_uint32_t serial) {
1151         isc_result_t result;
1152         dns_dbnode_t *node = NULL;
1153         dns_rdataset_t rdataset;
1154         dns_rdata_t rdata = DNS_RDATA_INIT;
1155         isc_uint32_t old_serial, new_serial;
1156
1157         result = dns_db_getoriginnode(gdb, &node);
1158         if (result != ISC_R_SUCCESS)
1159                 return result;
1160
1161         dns_rdataset_init(&rdataset);
1162
1163         result = dns_db_findrdataset(gdb, node, gversion,
1164                                      dns_rdatatype_soa, 0,
1165                                      0, &rdataset, NULL);
1166         if (result != ISC_R_SUCCESS)
1167                 goto cleanup;
1168
1169         result = dns_rdataset_first(&rdataset);
1170         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1171
1172         dns_rdataset_current(&rdataset, &rdata);
1173
1174         old_serial = dns_soa_getserial(&rdata);
1175
1176         if (serial) {
1177                 /* Set SOA serial to the value provided. */
1178                 new_serial = serial;
1179         } else {
1180                 /* Increment SOA serial using RFC 1982 arithmetics */
1181                 new_serial = (old_serial + 1) & 0xFFFFFFFF;
1182                 if (new_serial == 0)
1183                         new_serial = 1;
1184         }
1185
1186         /* If the new serial is not likely to cause a zone transfer
1187          * (a/ixfr) from servers having the old serial, warn the user.
1188          *
1189          * RFC1982 section 7 defines the maximum increment to be
1190          * (2^(32-1))-1.  Using u_int32_t arithmetic, we can do a single
1191          * comparison.  (5 - 6 == (2^32)-1, not negative-one)
1192          */
1193         if (new_serial == old_serial ||
1194             (new_serial - old_serial) > 0x7fffffffU)
1195                 fprintf(stderr, "%s: warning: Serial number not advanced, "
1196                         "zone may not transfer\n", program);
1197
1198         dns_soa_setserial(new_serial, &rdata);
1199
1200         result = dns_db_deleterdataset(gdb, node, gversion,
1201                                        dns_rdatatype_soa, 0);
1202         check_result(result, "dns_db_deleterdataset");
1203         if (result != ISC_R_SUCCESS)
1204                 goto cleanup;
1205
1206         result = dns_db_addrdataset(gdb, node, gversion,
1207                                     0, &rdataset, 0, NULL);
1208         check_result(result, "dns_db_addrdataset");
1209         if (result != ISC_R_SUCCESS)
1210                 goto cleanup;
1211
1212 cleanup:
1213         dns_rdataset_disassociate(&rdataset);
1214         if (node != NULL)
1215                 dns_db_detachnode(gdb, &node);
1216         dns_rdata_reset(&rdata);
1217
1218         return (result);
1219 }
1220
1221 /*%
1222  * Delete any RRSIG records at a node.
1223  */
1224 static void
1225 cleannode(dns_db_t *db, dns_dbversion_t *version, dns_dbnode_t *node) {
1226         dns_rdatasetiter_t *rdsiter = NULL;
1227         dns_rdataset_t set;
1228         isc_result_t result, dresult;
1229
1230         if (outputformat != dns_masterformat_text || !disable_zone_check)
1231                 return;
1232
1233         dns_rdataset_init(&set);
1234         result = dns_db_allrdatasets(db, node, version, 0, &rdsiter);
1235         check_result(result, "dns_db_allrdatasets");
1236         result = dns_rdatasetiter_first(rdsiter);
1237         while (result == ISC_R_SUCCESS) {
1238                 isc_boolean_t destroy = ISC_FALSE;
1239                 dns_rdatatype_t covers = 0;
1240                 dns_rdatasetiter_current(rdsiter, &set);
1241                 if (set.type == dns_rdatatype_rrsig) {
1242                         covers = set.covers;
1243                         destroy = ISC_TRUE;
1244                 }
1245                 dns_rdataset_disassociate(&set);
1246                 result = dns_rdatasetiter_next(rdsiter);
1247                 if (destroy) {
1248                         dresult = dns_db_deleterdataset(db, node, version,
1249                                                         dns_rdatatype_rrsig,
1250                                                         covers);
1251                         check_result(dresult, "dns_db_deleterdataset");
1252                 }
1253         }
1254         if (result != ISC_R_NOMORE)
1255                 fatal("rdataset iteration failed: %s",
1256                       isc_result_totext(result));
1257         dns_rdatasetiter_destroy(&rdsiter);
1258 }
1259
1260 /*%
1261  * Set up the iterator and global state before starting the tasks.
1262  */
1263 static void
1264 presign(void) {
1265         isc_result_t result;
1266
1267         gdbiter = NULL;
1268         result = dns_db_createiterator(gdb, 0, &gdbiter);
1269         check_result(result, "dns_db_createiterator()");
1270 }
1271
1272 /*%
1273  * Clean up the iterator and global state after the tasks complete.
1274  */
1275 static void
1276 postsign(void) {
1277         dns_dbiterator_destroy(&gdbiter);
1278 }
1279
1280 static isc_boolean_t
1281 goodsig(dns_rdata_t *sigrdata, dns_name_t *name, dns_rdataset_t *keyrdataset,
1282         dns_rdataset_t *rdataset)
1283 {
1284         dns_rdata_dnskey_t key;
1285         dns_rdata_rrsig_t sig;
1286         dst_key_t *dstkey = NULL;
1287         isc_result_t result;
1288
1289         dns_rdata_tostruct(sigrdata, &sig, NULL);
1290
1291         for (result = dns_rdataset_first(keyrdataset);
1292              result == ISC_R_SUCCESS;
1293              result = dns_rdataset_next(keyrdataset)) {
1294                 dns_rdata_t rdata = DNS_RDATA_INIT;
1295                 dns_rdataset_current(keyrdataset, &rdata);
1296                 dns_rdata_tostruct(&rdata, &key, NULL);
1297                 result = dns_dnssec_keyfromrdata(gorigin, &rdata, mctx,
1298                                                  &dstkey);
1299                 if (result != ISC_R_SUCCESS)
1300                         return (ISC_FALSE);
1301                 if (sig.algorithm != key.algorithm ||
1302                     sig.keyid != dst_key_id(dstkey) ||
1303                     !dns_name_equal(&sig.signer, gorigin)) {
1304                         dst_key_free(&dstkey);
1305                         continue;
1306                 }
1307                 result = dns_dnssec_verify(name, rdataset, dstkey, ISC_FALSE,
1308                                            mctx, sigrdata);
1309                 dst_key_free(&dstkey);
1310                 if (result == ISC_R_SUCCESS)
1311                         return(ISC_TRUE);
1312         }
1313         return (ISC_FALSE);
1314 }
1315
1316 static void
1317 verifyset(dns_rdataset_t *rdataset, dns_name_t *name, dns_dbnode_t *node,
1318           dns_rdataset_t *keyrdataset, unsigned char *ksk_algorithms,
1319           unsigned char *bad_algorithms)
1320 {
1321         unsigned char set_algorithms[256];
1322         char namebuf[DNS_NAME_FORMATSIZE];
1323         char algbuf[80];
1324         char typebuf[80];
1325         dns_rdataset_t sigrdataset;
1326         dns_rdatasetiter_t *rdsiter = NULL;
1327         isc_result_t result;
1328         int i;
1329
1330         dns_rdataset_init(&sigrdataset);
1331         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1332         check_result(result, "dns_db_allrdatasets()");
1333         for (result = dns_rdatasetiter_first(rdsiter);
1334              result == ISC_R_SUCCESS;
1335              result = dns_rdatasetiter_next(rdsiter)) {
1336                 dns_rdatasetiter_current(rdsiter, &sigrdataset);
1337                 if (sigrdataset.type == dns_rdatatype_rrsig &&
1338                     sigrdataset.covers == rdataset->type)
1339                         break;
1340                 dns_rdataset_disassociate(&sigrdataset);
1341         }
1342         if (result != ISC_R_SUCCESS) {
1343                 dns_name_format(name, namebuf, sizeof(namebuf));
1344                 type_format(rdataset->type, typebuf, sizeof(typebuf));
1345                 fprintf(stderr, "no signatures for %s/%s\n", namebuf, typebuf);
1346                 for (i = 0; i < 256; i++)
1347                         if (ksk_algorithms[i] != 0)
1348                                 bad_algorithms[i] = 1;
1349                 return;
1350         }
1351
1352         memset(set_algorithms, 0, sizeof(set_algorithms));
1353         for (result = dns_rdataset_first(&sigrdataset);
1354              result == ISC_R_SUCCESS;
1355              result = dns_rdataset_next(&sigrdataset)) {
1356                 dns_rdata_t rdata = DNS_RDATA_INIT;
1357                 dns_rdata_rrsig_t sig;
1358
1359                 dns_rdataset_current(&sigrdataset, &rdata);
1360                 dns_rdata_tostruct(&rdata, &sig, NULL);
1361                 if ((set_algorithms[sig.algorithm] != 0) ||
1362                     (ksk_algorithms[sig.algorithm] == 0))
1363                         continue;
1364                 if (goodsig(&rdata, name, keyrdataset, rdataset))
1365                         set_algorithms[sig.algorithm] = 1;
1366         }
1367         dns_rdatasetiter_destroy(&rdsiter);
1368         if (memcmp(set_algorithms, ksk_algorithms, sizeof(set_algorithms))) {
1369                 dns_name_format(name, namebuf, sizeof(namebuf));
1370                 type_format(rdataset->type, typebuf, sizeof(typebuf));
1371                 for (i = 0; i < 256; i++)
1372                         if ((ksk_algorithms[i] != 0) &&
1373                             (set_algorithms[i] == 0)) {
1374                                 alg_format(i, algbuf, sizeof(algbuf));
1375                                 fprintf(stderr, "Missing %s signature for "
1376                                         "%s %s\n", algbuf, namebuf, typebuf);
1377                                 bad_algorithms[i] = 1;
1378                         }
1379         }
1380         dns_rdataset_disassociate(&sigrdataset);
1381 }
1382
1383 static void
1384 verifynode(dns_name_t *name, dns_dbnode_t *node, isc_boolean_t delegation,
1385            dns_rdataset_t *keyrdataset, unsigned char *ksk_algorithms,
1386            unsigned char *bad_algorithms)
1387 {
1388         dns_rdataset_t rdataset;
1389         dns_rdatasetiter_t *rdsiter = NULL;
1390         isc_result_t result;
1391
1392         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1393         check_result(result, "dns_db_allrdatasets()");
1394         result = dns_rdatasetiter_first(rdsiter);
1395         dns_rdataset_init(&rdataset);
1396         while (result == ISC_R_SUCCESS) {
1397                 dns_rdatasetiter_current(rdsiter, &rdataset);
1398                 if (rdataset.type != dns_rdatatype_rrsig &&
1399                     rdataset.type != dns_rdatatype_dnskey &&
1400                     (!delegation || rdataset.type == dns_rdatatype_ds ||
1401                      rdataset.type == dns_rdatatype_nsec)) {
1402                         verifyset(&rdataset, name, node, keyrdataset,
1403                                   ksk_algorithms, bad_algorithms);
1404                 }
1405                 dns_rdataset_disassociate(&rdataset);
1406                 result = dns_rdatasetiter_next(rdsiter);
1407         }
1408         if (result != ISC_R_NOMORE)
1409                 fatal("rdataset iteration failed: %s",
1410                       isc_result_totext(result));
1411         dns_rdatasetiter_destroy(&rdsiter);
1412 }
1413
1414 /*%
1415  * Verify that certain things are sane:
1416  *
1417  *   The apex has a DNSKEY record with at least one KSK and at least
1418  *   one ZSK.
1419  *
1420  *   The DNSKEY record was signed with at least one of the KSKs in this
1421  *   set.
1422  *
1423  *   The rest of the zone was signed with at least one of the ZSKs
1424  *   present in the DNSKEY RRSET.
1425  */
1426 static void
1427 verifyzone(void) {
1428         char algbuf[80];
1429         dns_dbiterator_t *dbiter = NULL;
1430         dns_dbnode_t *node = NULL, *nextnode = NULL;
1431         dns_fixedname_t fname, fnextname, fzonecut;
1432         dns_name_t *name, *nextname, *zonecut;
1433         dns_rdata_dnskey_t dnskey;
1434         dns_rdata_t rdata = DNS_RDATA_INIT;
1435         dns_rdataset_t rdataset;
1436         dns_rdataset_t sigrdataset;
1437         int i;
1438         isc_boolean_t done = ISC_FALSE;
1439         isc_boolean_t first = ISC_TRUE;
1440         isc_boolean_t goodksk = ISC_FALSE;
1441         isc_boolean_t goodzsk = ISC_FALSE;
1442         isc_result_t result;
1443         unsigned char revoked[256];
1444         unsigned char standby[256];
1445         unsigned char ksk_algorithms[256];
1446         unsigned char zsk_algorithms[256];
1447         unsigned char bad_algorithms[256];
1448 #ifdef ALLOW_KSKLESS_ZONES
1449         isc_boolean_t allzsksigned = ISC_TRUE;
1450         unsigned char self_algorithms[256];
1451 #endif
1452
1453         if (disable_zone_check)
1454                 return;
1455
1456         result = dns_db_findnode(gdb, gorigin, ISC_FALSE, &node);
1457         if (result != ISC_R_SUCCESS)
1458                 fatal("failed to find the zone's origin: %s",
1459                       isc_result_totext(result));
1460
1461         dns_rdataset_init(&rdataset);
1462         dns_rdataset_init(&sigrdataset);
1463         result = dns_db_findrdataset(gdb, node, gversion,
1464                                      dns_rdatatype_dnskey,
1465                                      0, 0, &rdataset, &sigrdataset);
1466         dns_db_detachnode(gdb, &node);
1467         if (result != ISC_R_SUCCESS)
1468                 fatal("cannot find DNSKEY rrset\n");
1469
1470         if (!dns_rdataset_isassociated(&sigrdataset))
1471                 fatal("cannot find DNSKEY RRSIGs\n");
1472
1473         memset(revoked, 0, sizeof(revoked));
1474         memset(standby, 0, sizeof(revoked));
1475         memset(ksk_algorithms, 0, sizeof(ksk_algorithms));
1476         memset(zsk_algorithms, 0, sizeof(zsk_algorithms));
1477         memset(bad_algorithms, 0, sizeof(bad_algorithms));
1478 #ifdef ALLOW_KSKLESS_ZONES
1479         memset(self_algorithms, 0, sizeof(self_algorithms));
1480 #endif
1481
1482         /*
1483          * Check that the DNSKEY RR has at least one self signing KSK and
1484          * one ZSK per algorithm in it.
1485          */
1486         for (result = dns_rdataset_first(&rdataset);
1487              result == ISC_R_SUCCESS;
1488              result = dns_rdataset_next(&rdataset)) {
1489                 dns_rdataset_current(&rdataset, &rdata);
1490                 result = dns_rdata_tostruct(&rdata, &dnskey, NULL);
1491                 check_result(result, "dns_rdata_tostruct");
1492
1493                 if ((dnskey.flags & DNS_KEYOWNER_ZONE) == 0)
1494                         ;
1495                 else if ((dnskey.flags & DNS_KEYFLAG_REVOKE) != 0) {
1496                         if ((dnskey.flags & DNS_KEYFLAG_KSK) != 0 &&
1497                             !dns_dnssec_selfsigns(&rdata, gorigin, &rdataset,
1498                                                   &sigrdataset, ISC_FALSE,
1499                                                   mctx)) {
1500                                 char namebuf[DNS_NAME_FORMATSIZE];
1501                                 char buffer[1024];
1502                                 isc_buffer_t buf;
1503
1504                                 dns_name_format(gorigin, namebuf,
1505                                                 sizeof(namebuf));
1506                                 isc_buffer_init(&buf, buffer, sizeof(buffer));
1507                                 result = dns_rdata_totext(&rdata, NULL, &buf);
1508                                 check_result(result, "dns_rdata_totext");
1509                                 fatal("revoked KSK is not self signed:\n"
1510                                       "%s DNSKEY %.*s", namebuf,
1511                                       (int)isc_buffer_usedlength(&buf), buffer);
1512                         }
1513                         if ((dnskey.flags & DNS_KEYFLAG_KSK) != 0 &&
1514                              revoked[dnskey.algorithm] != 255)
1515                                 revoked[dnskey.algorithm]++;
1516                 } else if ((dnskey.flags & DNS_KEYFLAG_KSK) != 0) {
1517                         if (dns_dnssec_selfsigns(&rdata, gorigin, &rdataset,
1518                                               &sigrdataset, ISC_FALSE, mctx)) {
1519                                 if (ksk_algorithms[dnskey.algorithm] != 255)
1520                                         ksk_algorithms[dnskey.algorithm]++;
1521                                 goodksk = ISC_TRUE;
1522                         } else {
1523                                 if (standby[dnskey.algorithm] != 255)
1524                                         standby[dnskey.algorithm]++;
1525                         }
1526                 } else if (dns_dnssec_selfsigns(&rdata, gorigin, &rdataset,
1527                                                 &sigrdataset, ISC_FALSE,
1528                                                 mctx)) {
1529 #ifdef ALLOW_KSKLESS_ZONES
1530                         if (self_algorithms[dnskey.algorithm] != 255)
1531                                 self_algorithms[dnskey.algorithm]++;
1532 #endif
1533                         if (zsk_algorithms[dnskey.algorithm] != 255)
1534                                 zsk_algorithms[dnskey.algorithm]++;
1535                         goodzsk = ISC_TRUE;
1536                 } else {
1537                         if (zsk_algorithms[dnskey.algorithm] != 255)
1538                                 zsk_algorithms[dnskey.algorithm]++;
1539 #ifdef ALLOW_KSKLESS_ZONES
1540                         allzsksigned = ISC_FALSE;
1541 #endif
1542                 }
1543                 dns_rdata_freestruct(&dnskey);
1544                 dns_rdata_reset(&rdata);
1545         }
1546         dns_rdataset_disassociate(&sigrdataset);
1547
1548         if (!goodksk) {
1549 #ifdef ALLOW_KSKLESS_ZONES
1550                 if (!goodzsk)
1551                         fatal("no self signing keys found");
1552                 fprintf(stderr, "No self signing KSK found. Using self signed "
1553                         "ZSK's for active algorithm list.\n");
1554                 memcpy(ksk_algorithms, self_algorithms, sizeof(ksk_algorithms));
1555                 if (!allzsksigned)
1556                         fprintf(stderr, "warning: not all ZSK's are self "
1557                                 "signed.\n");
1558 #else
1559                 fatal("no self signed KSK's found");
1560 #endif
1561         }
1562
1563         fprintf(stderr, "Verifying the zone using the following algorithms:");
1564         for (i = 0; i < 256; i++) {
1565                 if (ksk_algorithms[i] != 0) {
1566                         alg_format(i, algbuf, sizeof(algbuf));
1567                         fprintf(stderr, " %s", algbuf);
1568                 }
1569         }
1570         fprintf(stderr, ".\n");
1571
1572         for (i = 0; i < 256; i++) {
1573                 /*
1574                  * The counts should both be zero or both be non-zero.
1575                  * Mark the algorithm as bad if this is not met.
1576                  */
1577                 if ((ksk_algorithms[i] != 0) == (zsk_algorithms[i] != 0))
1578                         continue;
1579                 alg_format(i, algbuf, sizeof(algbuf));
1580                 fprintf(stderr, "Missing %s for algorithm %s\n",
1581                         (ksk_algorithms[i] != 0) ? "ZSK" : "self signing KSK",
1582                         algbuf);
1583                 bad_algorithms[i] = 1;
1584         }
1585
1586         /*
1587          * Check that all the other records were signed by keys that are
1588          * present in the DNSKEY RRSET.
1589          */
1590
1591         dns_fixedname_init(&fname);
1592         name = dns_fixedname_name(&fname);
1593         dns_fixedname_init(&fnextname);
1594         nextname = dns_fixedname_name(&fnextname);
1595         dns_fixedname_init(&fzonecut);
1596         zonecut = NULL;
1597
1598         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
1599         check_result(result, "dns_db_createiterator()");
1600
1601         result = dns_dbiterator_first(dbiter);
1602         check_result(result, "dns_dbiterator_first()");
1603
1604         while (!done) {
1605                 isc_boolean_t isdelegation = ISC_FALSE;
1606
1607                 result = dns_dbiterator_current(dbiter, &node, name);
1608                 check_dns_dbiterator_current(result);
1609                 if (!dns_name_issubdomain(name, gorigin)) {
1610                         dns_db_detachnode(gdb, &node);
1611                         result = dns_dbiterator_next(dbiter);
1612                         if (result == ISC_R_NOMORE)
1613                                 done = ISC_TRUE;
1614                         else
1615                                 check_result(result, "dns_dbiterator_next()");
1616                         continue;
1617                 }
1618                 if (delegation(name, node, NULL)) {
1619                         zonecut = dns_fixedname_name(&fzonecut);
1620                         dns_name_copy(name, zonecut, NULL);
1621                         isdelegation = ISC_TRUE;
1622                 }
1623                 verifynode(name, node, isdelegation, &rdataset,
1624                            ksk_algorithms, bad_algorithms);
1625                 result = dns_dbiterator_next(dbiter);
1626                 nextnode = NULL;
1627                 while (result == ISC_R_SUCCESS) {
1628                         result = dns_dbiterator_current(dbiter, &nextnode,
1629                                                         nextname);
1630                         check_dns_dbiterator_current(result);
1631                         if (!dns_name_issubdomain(nextname, gorigin) ||
1632                             (zonecut != NULL &&
1633                              dns_name_issubdomain(nextname, zonecut)))
1634                         {
1635                                 dns_db_detachnode(gdb, &nextnode);
1636                                 result = dns_dbiterator_next(dbiter);
1637                                 continue;
1638                         }
1639                         dns_db_detachnode(gdb, &nextnode);
1640                         break;
1641                 }
1642                 if (result == ISC_R_NOMORE) {
1643                         done = ISC_TRUE;
1644                 } else if (result != ISC_R_SUCCESS)
1645                         fatal("iterating through the database failed: %s",
1646                               isc_result_totext(result));
1647                 dns_db_detachnode(gdb, &node);
1648         }
1649
1650         dns_dbiterator_destroy(&dbiter);
1651
1652         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
1653         check_result(result, "dns_db_createiterator()");
1654
1655         for (result = dns_dbiterator_first(dbiter);
1656              result == ISC_R_SUCCESS;
1657              result = dns_dbiterator_next(dbiter) ) {
1658                 result = dns_dbiterator_current(dbiter, &node, name);
1659                 check_dns_dbiterator_current(result);
1660                 verifynode(name, node, ISC_FALSE, &rdataset,
1661                            ksk_algorithms, bad_algorithms);
1662                 dns_db_detachnode(gdb, &node);
1663         }
1664         dns_dbiterator_destroy(&dbiter);
1665
1666         dns_rdataset_disassociate(&rdataset);
1667
1668         /*
1669          * If we made it this far, we have what we consider a properly signed
1670          * zone.  Set the good flag.
1671          */
1672         for (i = 0; i < 256; i++) {
1673                 if (bad_algorithms[i] != 0) {
1674                         if (first)
1675                                 fprintf(stderr, "The zone is not fully signed "
1676                                         "for the following algorithms:");
1677                         alg_format(i, algbuf, sizeof(algbuf));
1678                         fprintf(stderr, " %s", algbuf);
1679                         first = ISC_FALSE;
1680                 }
1681         }
1682         if (!first) {
1683                 fprintf(stderr, ".\n");
1684                 fatal("DNSSEC completeness test failed.");
1685         }
1686
1687         if (goodksk) {
1688                 /*
1689                  * Print the success summary.
1690                  */
1691                 fprintf(stderr, "Zone signing complete:\n");
1692                 for (i = 0; i < 256; i++) {
1693                         if ((zsk_algorithms[i] != 0) ||
1694                             (ksk_algorithms[i] != 0) ||
1695                             (revoked[i] != 0) || (standby[i] != 0)) {
1696                                 alg_format(i, algbuf, sizeof(algbuf));
1697                                 fprintf(stderr, "Algorithm: %s: ZSKs: %u, "
1698                                         "KSKs: %u active, %u revoked, %u "
1699                                         "stand-by\n", algbuf,
1700                                         zsk_algorithms[i], ksk_algorithms[i],
1701                                         revoked[i], standby[i]);
1702                         }
1703                 }
1704         }
1705 }
1706
1707 /*%
1708  * Sign the apex of the zone.
1709  * Note the origin may not be the first node if there are out of zone
1710  * records.
1711  */
1712 static void
1713 signapex(void) {
1714         dns_dbnode_t *node = NULL;
1715         dns_fixedname_t fixed;
1716         dns_name_t *name;
1717         isc_result_t result;
1718
1719         dns_fixedname_init(&fixed);
1720         name = dns_fixedname_name(&fixed);
1721         result = dns_dbiterator_seek(gdbiter, gorigin);
1722         check_result(result, "dns_dbiterator_seek()");
1723         result = dns_dbiterator_current(gdbiter, &node, name);
1724         check_dns_dbiterator_current(result);
1725         signname(node, name);
1726         dumpnode(name, node);
1727         cleannode(gdb, gversion, node);
1728         dns_db_detachnode(gdb, &node);
1729         result = dns_dbiterator_first(gdbiter);
1730         if (result == ISC_R_NOMORE)
1731                 finished = ISC_TRUE;
1732         else if (result != ISC_R_SUCCESS)
1733                 fatal("failure iterating database: %s",
1734                       isc_result_totext(result));
1735 }
1736
1737 /*%
1738  * Assigns a node to a worker thread.  This is protected by the master task's
1739  * lock.
1740  */
1741 static void
1742 assignwork(isc_task_t *task, isc_task_t *worker) {
1743         dns_fixedname_t *fname;
1744         dns_name_t *name;
1745         dns_dbnode_t *node;
1746         sevent_t *sevent;
1747         dns_rdataset_t nsec;
1748         isc_boolean_t found;
1749         isc_result_t result;
1750         static dns_name_t *zonecut = NULL;      /* Protected by namelock. */
1751         static dns_fixedname_t fzonecut;        /* Protected by namelock. */
1752         static unsigned int ended = 0;          /* Protected by namelock. */
1753
1754         if (shuttingdown)
1755                 return;
1756
1757         LOCK(&namelock);
1758         if (finished) {
1759                 ended++;
1760                 if (ended == ntasks) {
1761                         isc_task_detach(&task);
1762                         isc_app_shutdown();
1763                 }
1764                 goto unlock;
1765         }
1766
1767         fname = isc_mem_get(mctx, sizeof(dns_fixedname_t));
1768         if (fname == NULL)
1769                 fatal("out of memory");
1770         dns_fixedname_init(fname);
1771         name = dns_fixedname_name(fname);
1772         node = NULL;
1773         found = ISC_FALSE;
1774         while (!found) {
1775                 result = dns_dbiterator_current(gdbiter, &node, name);
1776                 check_dns_dbiterator_current(result);
1777                 /*
1778                  * The origin was handled by signapex().
1779                  */
1780                 if (dns_name_equal(name, gorigin)) {
1781                         dns_db_detachnode(gdb, &node);
1782                         goto next;
1783                 }
1784                 /*
1785                  * Sort the zone data from the glue and out-of-zone data.
1786                  * For NSEC zones nodes with zone data have NSEC records.
1787                  * For NSEC3 zones the NSEC3 nodes are zone data but
1788                  * outside of the zone name space.  For the rest we need
1789                  * to track the bottom of zone cuts.
1790                  * Nodes which don't need to be signed are dumped here.
1791                  */
1792                 dns_rdataset_init(&nsec);
1793                 result = dns_db_findrdataset(gdb, node, gversion,
1794                                              nsec_datatype, 0, 0,
1795                                              &nsec, NULL);
1796                 if (dns_rdataset_isassociated(&nsec))
1797                         dns_rdataset_disassociate(&nsec);
1798                 if (result == ISC_R_SUCCESS) {
1799                         found = ISC_TRUE;
1800                 } else if (nsec_datatype == dns_rdatatype_nsec3) {
1801                         if (dns_name_issubdomain(name, gorigin) &&
1802                             (zonecut == NULL ||
1803                              !dns_name_issubdomain(name, zonecut))) {
1804                                 if (delegation(name, node, NULL)) {
1805                                         dns_fixedname_init(&fzonecut);
1806                                         zonecut = dns_fixedname_name(&fzonecut);
1807                                         dns_name_copy(name, zonecut, NULL);
1808                                         if (!OPTOUT(nsec3flags) ||
1809                                             secure(name, node))
1810                                                 found = ISC_TRUE;
1811                                 } else
1812                                         found = ISC_TRUE;
1813                         }
1814                 }
1815
1816                 if (!found) {
1817                         dumpnode(name, node);
1818                         dns_db_detachnode(gdb, &node);
1819                 }
1820
1821  next:
1822                 result = dns_dbiterator_next(gdbiter);
1823                 if (result == ISC_R_NOMORE) {
1824                         finished = ISC_TRUE;
1825                         break;
1826                 } else if (result != ISC_R_SUCCESS)
1827                         fatal("failure iterating database: %s",
1828                               isc_result_totext(result));
1829         }
1830         if (!found) {
1831                 ended++;
1832                 if (ended == ntasks) {
1833                         isc_task_detach(&task);
1834                         isc_app_shutdown();
1835                 }
1836                 isc_mem_put(mctx, fname, sizeof(dns_fixedname_t));
1837                 goto unlock;
1838         }
1839         sevent = (sevent_t *)
1840                  isc_event_allocate(mctx, task, SIGNER_EVENT_WORK,
1841                                     sign, NULL, sizeof(sevent_t));
1842         if (sevent == NULL)
1843                 fatal("failed to allocate event\n");
1844
1845         sevent->node = node;
1846         sevent->fname = fname;
1847         isc_task_send(worker, ISC_EVENT_PTR(&sevent));
1848  unlock:
1849         UNLOCK(&namelock);
1850 }
1851
1852 /*%
1853  * Start a worker task
1854  */
1855 static void
1856 startworker(isc_task_t *task, isc_event_t *event) {
1857         isc_task_t *worker;
1858
1859         worker = (isc_task_t *)event->ev_arg;
1860         assignwork(task, worker);
1861         isc_event_free(&event);
1862 }
1863
1864 /*%
1865  * Write a node to the output file, and restart the worker task.
1866  */
1867 static void
1868 writenode(isc_task_t *task, isc_event_t *event) {
1869         isc_task_t *worker;
1870         sevent_t *sevent = (sevent_t *)event;
1871
1872         worker = (isc_task_t *)event->ev_sender;
1873         dumpnode(dns_fixedname_name(sevent->fname), sevent->node);
1874         cleannode(gdb, gversion, sevent->node);
1875         dns_db_detachnode(gdb, &sevent->node);
1876         isc_mem_put(mctx, sevent->fname, sizeof(dns_fixedname_t));
1877         assignwork(task, worker);
1878         isc_event_free(&event);
1879 }
1880
1881 /*%
1882  *  Sign a database node.
1883  */
1884 static void
1885 sign(isc_task_t *task, isc_event_t *event) {
1886         dns_fixedname_t *fname;
1887         dns_dbnode_t *node;
1888         sevent_t *sevent, *wevent;
1889
1890         sevent = (sevent_t *)event;
1891         node = sevent->node;
1892         fname = sevent->fname;
1893         isc_event_free(&event);
1894
1895         signname(node, dns_fixedname_name(fname));
1896         wevent = (sevent_t *)
1897                  isc_event_allocate(mctx, task, SIGNER_EVENT_WRITE,
1898                                     writenode, NULL, sizeof(sevent_t));
1899         if (wevent == NULL)
1900                 fatal("failed to allocate event\n");
1901         wevent->node = node;
1902         wevent->fname = fname;
1903         isc_task_send(master, ISC_EVENT_PTR(&wevent));
1904 }
1905
1906 /*%
1907  * Update / remove the DS RRset.  Preserve RRSIG(DS) if possible.
1908  */
1909 static void
1910 add_ds(dns_name_t *name, dns_dbnode_t *node, isc_uint32_t nsttl) {
1911         dns_rdataset_t dsset;
1912         dns_rdataset_t sigdsset;
1913         isc_result_t result;
1914
1915         dns_rdataset_init(&dsset);
1916         dns_rdataset_init(&sigdsset);
1917         result = dns_db_findrdataset(gdb, node, gversion,
1918                                      dns_rdatatype_ds,
1919                                      0, 0, &dsset, &sigdsset);
1920         if (result == ISC_R_SUCCESS) {
1921                 dns_rdataset_disassociate(&dsset);
1922                 result = dns_db_deleterdataset(gdb, node, gversion,
1923                                                dns_rdatatype_ds, 0);
1924                 check_result(result, "dns_db_deleterdataset");
1925         }
1926         result = loadds(name, nsttl, &dsset);
1927         if (result == ISC_R_SUCCESS) {
1928                 result = dns_db_addrdataset(gdb, node, gversion, 0,
1929                                             &dsset, 0, NULL);
1930                 check_result(result, "dns_db_addrdataset");
1931                 dns_rdataset_disassociate(&dsset);
1932                 if (dns_rdataset_isassociated(&sigdsset))
1933                         dns_rdataset_disassociate(&sigdsset);
1934         } else if (dns_rdataset_isassociated(&sigdsset)) {
1935                 result = dns_db_deleterdataset(gdb, node, gversion,
1936                                                dns_rdatatype_rrsig,
1937                                                dns_rdatatype_ds);
1938                 check_result(result, "dns_db_deleterdataset");
1939                 dns_rdataset_disassociate(&sigdsset);
1940         }
1941 }
1942
1943 /*
1944  * Remove records of the given type and their signatures.
1945  */
1946 static void
1947 remove_records(dns_dbnode_t *node, dns_rdatatype_t which) {
1948         isc_result_t result;
1949         dns_rdatatype_t type, covers;
1950         dns_rdatasetiter_t *rdsiter = NULL;
1951         dns_rdataset_t rdataset;
1952
1953         dns_rdataset_init(&rdataset);
1954
1955         /*
1956          * Delete any NSEC records at the apex.
1957          */
1958         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1959         check_result(result, "dns_db_allrdatasets()");
1960         for (result = dns_rdatasetiter_first(rdsiter);
1961              result == ISC_R_SUCCESS;
1962              result = dns_rdatasetiter_next(rdsiter)) {
1963                 dns_rdatasetiter_current(rdsiter, &rdataset);
1964                 type = rdataset.type;
1965                 covers = rdataset.covers;
1966                 dns_rdataset_disassociate(&rdataset);
1967                 if (type == which || covers == which) {
1968                         result = dns_db_deleterdataset(gdb, node, gversion,
1969                                                        type, covers);
1970                         check_result(result, "dns_db_deleterdataset()");
1971                         continue;
1972                 }
1973         }
1974         dns_rdatasetiter_destroy(&rdsiter);
1975 }
1976
1977 /*%
1978  * Generate NSEC records for the zone and remove NSEC3/NSEC3PARAM records.
1979  */
1980 static void
1981 nsecify(void) {
1982         dns_dbiterator_t *dbiter = NULL;
1983         dns_dbnode_t *node = NULL, *nextnode = NULL;
1984         dns_fixedname_t fname, fnextname, fzonecut;
1985         dns_name_t *name, *nextname, *zonecut;
1986         dns_rdataset_t rdataset;
1987         dns_rdatasetiter_t *rdsiter = NULL;
1988         dns_rdatatype_t type, covers;
1989         isc_boolean_t done = ISC_FALSE;
1990         isc_result_t result;
1991         isc_uint32_t nsttl = 0;
1992
1993         dns_rdataset_init(&rdataset);
1994         dns_fixedname_init(&fname);
1995         name = dns_fixedname_name(&fname);
1996         dns_fixedname_init(&fnextname);
1997         nextname = dns_fixedname_name(&fnextname);
1998         dns_fixedname_init(&fzonecut);
1999         zonecut = NULL;
2000
2001         /*
2002          * Remove any NSEC3 chains.
2003          */
2004         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
2005         check_result(result, "dns_db_createiterator()");
2006         for (result = dns_dbiterator_first(dbiter);
2007              result == ISC_R_SUCCESS;
2008              result = dns_dbiterator_next(dbiter)) {
2009                 result = dns_dbiterator_current(dbiter, &node, name);
2010                 check_dns_dbiterator_current(result);
2011                 result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
2012                 check_result(result, "dns_db_allrdatasets()");
2013                 for (result = dns_rdatasetiter_first(rdsiter);
2014                      result == ISC_R_SUCCESS;
2015                      result = dns_rdatasetiter_next(rdsiter)) {
2016                         dns_rdatasetiter_current(rdsiter, &rdataset);
2017                         type = rdataset.type;
2018                         covers = rdataset.covers;
2019                         dns_rdataset_disassociate(&rdataset);
2020                         result = dns_db_deleterdataset(gdb, node, gversion,
2021                                                        type, covers);
2022                         check_result(result,
2023                                      "dns_db_deleterdataset(nsec3param/rrsig)");
2024                 }
2025                 dns_rdatasetiter_destroy(&rdsiter);
2026                 dns_db_detachnode(gdb, &node);
2027         }
2028         dns_dbiterator_destroy(&dbiter);
2029
2030         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
2031         check_result(result, "dns_db_createiterator()");
2032
2033         result = dns_dbiterator_first(dbiter);
2034         check_result(result, "dns_dbiterator_first()");
2035
2036         while (!done) {
2037                 result = dns_dbiterator_current(dbiter, &node, name);
2038                 check_dns_dbiterator_current(result);
2039                 /*
2040                  * Skip out-of-zone records.
2041                  */
2042                 if (!dns_name_issubdomain(name, gorigin)) {
2043                         result = dns_dbiterator_next(dbiter);
2044                         if (result == ISC_R_NOMORE)
2045                                 done = ISC_TRUE;
2046                         else
2047                                 check_result(result, "dns_dbiterator_next()");
2048                         dns_db_detachnode(gdb, &node);
2049                         continue;
2050                 }
2051
2052                 if (dns_name_equal(name, gorigin))
2053                         remove_records(node, dns_rdatatype_nsec3param);
2054
2055                 if (delegation(name, node, &nsttl)) {
2056                         zonecut = dns_fixedname_name(&fzonecut);
2057                         dns_name_copy(name, zonecut, NULL);
2058                         if (generateds)
2059                                 add_ds(name, node, nsttl);
2060                 }
2061                 result = dns_dbiterator_next(dbiter);
2062                 nextnode = NULL;
2063                 while (result == ISC_R_SUCCESS) {
2064                         isc_boolean_t active = ISC_FALSE;
2065                         result = dns_dbiterator_current(dbiter, &nextnode,
2066                                                         nextname);
2067                         check_dns_dbiterator_current(result);
2068                         active = active_node(nextnode);
2069                         if (!active) {
2070                                 dns_db_detachnode(gdb, &nextnode);
2071                                 result = dns_dbiterator_next(dbiter);
2072                                 continue;
2073                         }
2074                         if (!dns_name_issubdomain(nextname, gorigin) ||
2075                             (zonecut != NULL &&
2076                              dns_name_issubdomain(nextname, zonecut)))
2077                         {
2078                                 dns_db_detachnode(gdb, &nextnode);
2079                                 result = dns_dbiterator_next(dbiter);
2080                                 continue;
2081                         }
2082                         dns_db_detachnode(gdb, &nextnode);
2083                         break;
2084                 }
2085                 if (result == ISC_R_NOMORE) {
2086                         dns_name_clone(gorigin, nextname);
2087                         done = ISC_TRUE;
2088                 } else if (result != ISC_R_SUCCESS)
2089                         fatal("iterating through the database failed: %s",
2090                               isc_result_totext(result));
2091                 result = dns_nsec_build(gdb, gversion, node, nextname,
2092                                         zonettl);
2093                 check_result(result, "dns_nsec_build()");
2094                 dns_db_detachnode(gdb, &node);
2095         }
2096
2097         dns_dbiterator_destroy(&dbiter);
2098 }
2099
2100 static void
2101 addnsec3param(const unsigned char *salt, size_t salt_length,
2102               unsigned int iterations)
2103 {
2104         dns_dbnode_t *node = NULL;
2105         dns_rdata_nsec3param_t nsec3param;
2106         unsigned char nsec3parambuf[5 + 255];
2107         dns_rdatalist_t rdatalist;
2108         dns_rdataset_t rdataset;
2109         dns_rdata_t rdata = DNS_RDATA_INIT;
2110         isc_buffer_t b;
2111         isc_result_t result;
2112
2113         dns_rdataset_init(&rdataset);
2114
2115         nsec3param.common.rdclass = gclass;
2116         nsec3param.common.rdtype = dns_rdatatype_nsec3param;
2117         ISC_LINK_INIT(&nsec3param.common, link);
2118         nsec3param.mctx = NULL;
2119         nsec3param.flags = 0;
2120         nsec3param.hash = unknownalg ? DNS_NSEC3_UNKNOWNALG : dns_hash_sha1;
2121         nsec3param.iterations = iterations;
2122         nsec3param.salt_length = salt_length;
2123         DE_CONST(salt, nsec3param.salt);
2124
2125         isc_buffer_init(&b, nsec3parambuf, sizeof(nsec3parambuf));
2126         result = dns_rdata_fromstruct(&rdata, gclass,
2127                                       dns_rdatatype_nsec3param,
2128                                       &nsec3param, &b);
2129         rdatalist.rdclass = rdata.rdclass;
2130         rdatalist.type = rdata.type;
2131         rdatalist.covers = 0;
2132         rdatalist.ttl = 0;
2133         ISC_LIST_INIT(rdatalist.rdata);
2134         ISC_LIST_APPEND(rdatalist.rdata, &rdata, link);
2135         result = dns_rdatalist_tordataset(&rdatalist, &rdataset);
2136         check_result(result, "dns_rdatalist_tordataset()");
2137
2138         result = dns_db_findnode(gdb, gorigin, ISC_TRUE, &node);
2139         check_result(result, "dns_db_find(gorigin)");
2140
2141         /*
2142          * Delete any current NSEC3PARAM records.
2143          */
2144         result = dns_db_deleterdataset(gdb, node, gversion,
2145                                        dns_rdatatype_nsec3param, 0);
2146         if (result == DNS_R_UNCHANGED)
2147                 result = ISC_R_SUCCESS;
2148         check_result(result, "dddnsec3param: dns_db_deleterdataset()");
2149
2150         result = dns_db_addrdataset(gdb, node, gversion, 0, &rdataset,
2151                                     DNS_DBADD_MERGE, NULL);
2152         if (result == DNS_R_UNCHANGED)
2153                 result = ISC_R_SUCCESS;
2154         check_result(result, "addnsec3param: dns_db_addrdataset()");
2155         dns_db_detachnode(gdb, &node);
2156 }
2157
2158 static void
2159 addnsec3(dns_name_t *name, dns_dbnode_t *node,
2160          const unsigned char *salt, size_t salt_length,
2161          unsigned int iterations, hashlist_t *hashlist,
2162          dns_ttl_t ttl)
2163 {
2164         unsigned char hash[NSEC3_MAX_HASH_LENGTH];
2165         const unsigned char *nexthash;
2166         unsigned char nsec3buffer[DNS_NSEC3_BUFFERSIZE];
2167         dns_fixedname_t hashname;
2168         dns_rdatalist_t rdatalist;
2169         dns_rdataset_t rdataset;
2170         dns_rdata_t rdata = DNS_RDATA_INIT;
2171         isc_result_t result;
2172         dns_dbnode_t *nsec3node = NULL;
2173         char namebuf[DNS_NAME_FORMATSIZE];
2174         size_t hash_length;
2175
2176         dns_name_format(name, namebuf, sizeof(namebuf));
2177
2178         dns_fixedname_init(&hashname);
2179         dns_rdataset_init(&rdataset);
2180
2181         dns_name_downcase(name, name, NULL);
2182         result = dns_nsec3_hashname(&hashname, hash, &hash_length,
2183                                     name, gorigin, dns_hash_sha1, iterations,
2184                                     salt, salt_length);
2185         check_result(result, "addnsec3: dns_nsec3_hashname()");
2186         nexthash = hashlist_findnext(hashlist, hash);
2187         result = dns_nsec3_buildrdata(gdb, gversion, node,
2188                                       unknownalg ?
2189                                           DNS_NSEC3_UNKNOWNALG : dns_hash_sha1,
2190                                       nsec3flags, iterations,
2191                                       salt, salt_length,
2192                                       nexthash, ISC_SHA1_DIGESTLENGTH,
2193                                       nsec3buffer, &rdata);
2194         check_result(result, "addnsec3: dns_nsec3_buildrdata()");
2195         rdatalist.rdclass = rdata.rdclass;
2196         rdatalist.type = rdata.type;
2197         rdatalist.covers = 0;
2198         rdatalist.ttl = ttl;
2199         ISC_LIST_INIT(rdatalist.rdata);
2200         ISC_LIST_APPEND(rdatalist.rdata, &rdata, link);
2201         result = dns_rdatalist_tordataset(&rdatalist, &rdataset);
2202         check_result(result, "dns_rdatalist_tordataset()");
2203         result = dns_db_findnsec3node(gdb, dns_fixedname_name(&hashname),
2204                                       ISC_TRUE, &nsec3node);
2205         check_result(result, "addnsec3: dns_db_findnode()");
2206         result = dns_db_addrdataset(gdb, nsec3node, gversion, 0, &rdataset,
2207                                     0, NULL);
2208         if (result == DNS_R_UNCHANGED)
2209                 result = ISC_R_SUCCESS;
2210         check_result(result, "addnsec3: dns_db_addrdataset()");
2211         dns_db_detachnode(gdb, &nsec3node);
2212 }
2213
2214 /*%
2215  * Clean out NSEC3 record and RRSIG(NSEC3) that are not in the hash list.
2216  *
2217  * Extract the hash from the first label of 'name' then see if it
2218  * is in hashlist.  If 'name' is not in the hashlist then delete the
2219  * any NSEC3 records which have the same parameters as the chain we
2220  * are building.
2221  *
2222  * XXXMPA Should we also check that it of the form <hash>.<origin>?
2223  */
2224 static void
2225 nsec3clean(dns_name_t *name, dns_dbnode_t *node,
2226            unsigned int hashalg, unsigned int iterations,
2227            const unsigned char *salt, size_t salt_length, hashlist_t *hashlist)
2228 {
2229         dns_label_t label;
2230         dns_rdata_nsec3_t nsec3;
2231         dns_rdata_t rdata, delrdata;
2232         dns_rdatalist_t rdatalist;
2233         dns_rdataset_t rdataset, delrdataset;
2234         isc_boolean_t delete_rrsigs = ISC_FALSE;
2235         isc_buffer_t target;
2236         isc_result_t result;
2237         unsigned char hash[NSEC3_MAX_HASH_LENGTH + 1];
2238         isc_boolean_t exists;
2239
2240         /*
2241          * Get the first label.
2242          */
2243         dns_name_getlabel(name, 0, &label);
2244
2245         /*
2246          * We want just the label contents.
2247          */
2248         isc_region_consume(&label, 1);
2249
2250         /*
2251          * Decode base32hex string.
2252          */
2253         isc_buffer_init(&target, hash, sizeof(hash) - 1);
2254         result = isc_base32hex_decoderegion(&label, &target);
2255         if (result != ISC_R_SUCCESS)
2256                 return;
2257
2258         hash[isc_buffer_usedlength(&target)] = 0;
2259
2260         exists = hashlist_exists(hashlist, hash);
2261
2262         /*
2263          * Verify that the NSEC3 parameters match the current ones
2264          * otherwise we are dealing with a different NSEC3 chain.
2265          */
2266         dns_rdataset_init(&rdataset);
2267         dns_rdataset_init(&delrdataset);
2268
2269         result = dns_db_findrdataset(gdb, node, gversion, dns_rdatatype_nsec3,
2270                                      0, 0, &rdataset, NULL);
2271         if (result != ISC_R_SUCCESS)
2272                 return;
2273
2274         /*
2275          * Delete any NSEC3 records which are not part of the current
2276          * NSEC3 chain.
2277          */
2278         for (result = dns_rdataset_first(&rdataset);
2279              result == ISC_R_SUCCESS;
2280              result = dns_rdataset_next(&rdataset)) {
2281                 dns_rdata_init(&rdata);
2282                 dns_rdataset_current(&rdataset, &rdata);
2283                 result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
2284                 check_result(result, "dns_rdata_tostruct");
2285                 if (exists && nsec3.hash == hashalg &&
2286                     nsec3.iterations == iterations &&
2287                     nsec3.salt_length == salt_length &&
2288                     !memcmp(nsec3.salt, salt, salt_length))
2289                         continue;
2290                 rdatalist.rdclass = rdata.rdclass;
2291                 rdatalist.type = rdata.type;
2292                 rdatalist.covers = 0;
2293                 rdatalist.ttl = rdataset.ttl;
2294                 ISC_LIST_INIT(rdatalist.rdata);
2295                 dns_rdata_init(&delrdata);
2296                 dns_rdata_clone(&rdata, &delrdata);
2297                 ISC_LIST_APPEND(rdatalist.rdata, &delrdata, link);
2298                 result = dns_rdatalist_tordataset(&rdatalist, &delrdataset);
2299                 check_result(result, "dns_rdatalist_tordataset()");
2300                 result = dns_db_subtractrdataset(gdb, node, gversion,
2301                                                  &delrdataset, 0, NULL);
2302                 dns_rdataset_disassociate(&delrdataset);
2303                 if (result != ISC_R_SUCCESS && result != DNS_R_NXRRSET)
2304                         check_result(result, "dns_db_subtractrdataset(NSEC3)");
2305                 delete_rrsigs = ISC_TRUE;
2306         }
2307         dns_rdataset_disassociate(&rdataset);
2308         if (result != ISC_R_NOMORE)
2309                 check_result(result, "dns_rdataset_first/next");
2310
2311         if (!delete_rrsigs)
2312                 return;
2313         /*
2314          * Delete the NSEC3 RRSIGs
2315          */
2316         result = dns_db_deleterdataset(gdb, node, gversion,
2317                                        dns_rdatatype_rrsig,
2318                                        dns_rdatatype_nsec3);
2319         if (result != ISC_R_SUCCESS && result != DNS_R_UNCHANGED)
2320                 check_result(result, "dns_db_deleterdataset(RRSIG(NSEC3))");
2321 }
2322
2323 /*
2324  * Generate NSEC3 records for the zone.
2325  */
2326 static void
2327 nsec3ify(unsigned int hashalg, unsigned int iterations,
2328          const unsigned char *salt, size_t salt_length, hashlist_t *hashlist)
2329 {
2330         dns_dbiterator_t *dbiter = NULL;
2331         dns_dbnode_t *node = NULL, *nextnode = NULL;
2332         dns_fixedname_t fname, fnextname, fzonecut;
2333         dns_name_t *name, *nextname, *zonecut;
2334         dns_rdataset_t rdataset;
2335         int order;
2336         isc_boolean_t active;
2337         isc_boolean_t done = ISC_FALSE;
2338         isc_result_t result;
2339         isc_uint32_t nsttl = 0;
2340         unsigned int count, nlabels;
2341
2342         dns_rdataset_init(&rdataset);
2343         dns_fixedname_init(&fname);
2344         name = dns_fixedname_name(&fname);
2345         dns_fixedname_init(&fnextname);
2346         nextname = dns_fixedname_name(&fnextname);
2347         dns_fixedname_init(&fzonecut);
2348         zonecut = NULL;
2349
2350         /*
2351          * Walk the zone generating the hash names.
2352          */
2353         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
2354         check_result(result, "dns_db_createiterator()");
2355
2356         result = dns_dbiterator_first(dbiter);
2357         check_result(result, "dns_dbiterator_first()");
2358
2359         while (!done) {
2360                 result = dns_dbiterator_current(dbiter, &node, name);
2361                 check_dns_dbiterator_current(result);
2362                 /*
2363                  * Skip out-of-zone records.
2364                  */
2365                 if (!dns_name_issubdomain(name, gorigin)) {
2366                         result = dns_dbiterator_next(dbiter);
2367                         if (result == ISC_R_NOMORE)
2368                                 done = ISC_TRUE;
2369                         else
2370                                 check_result(result, "dns_dbiterator_next()");
2371                         dns_db_detachnode(gdb, &node);
2372                         continue;
2373                 }
2374
2375                 if (dns_name_equal(name, gorigin))
2376                         remove_records(node, dns_rdatatype_nsec);
2377
2378                 result = dns_dbiterator_next(dbiter);
2379                 nextnode = NULL;
2380                 while (result == ISC_R_SUCCESS) {
2381                         result = dns_dbiterator_current(dbiter, &nextnode,
2382                                                         nextname);
2383                         check_dns_dbiterator_current(result);
2384                         active = active_node(nextnode);
2385                         if (!active) {
2386                                 dns_db_detachnode(gdb, &nextnode);
2387                                 result = dns_dbiterator_next(dbiter);
2388                                 continue;
2389                         }
2390                         if (!dns_name_issubdomain(nextname, gorigin) ||
2391                             (zonecut != NULL &&
2392                              dns_name_issubdomain(nextname, zonecut))) {
2393                                 dns_db_detachnode(gdb, &nextnode);
2394                                 result = dns_dbiterator_next(dbiter);
2395                                 continue;
2396                         }
2397                         if (delegation(nextname, nextnode, &nsttl)) {
2398                                 zonecut = dns_fixedname_name(&fzonecut);
2399                                 dns_name_copy(nextname, zonecut, NULL);
2400                                 if (generateds)
2401                                         add_ds(nextname, nextnode, nsttl);
2402                                 if (OPTOUT(nsec3flags) &&
2403                                     !secure(nextname, nextnode)) {
2404                                         dns_db_detachnode(gdb, &nextnode);
2405                                         result = dns_dbiterator_next(dbiter);
2406                                         continue;
2407                                 }
2408                         }
2409                         dns_db_detachnode(gdb, &nextnode);
2410                         break;
2411                 }
2412                 if (result == ISC_R_NOMORE) {
2413                         dns_name_copy(gorigin, nextname, NULL);
2414                         done = ISC_TRUE;
2415                 } else if (result != ISC_R_SUCCESS)
2416                         fatal("iterating through the database failed: %s",
2417                               isc_result_totext(result));
2418                 dns_name_downcase(name, name, NULL);
2419                 hashlist_add_dns_name(hashlist, name, hashalg, iterations,
2420                                       salt, salt_length, ISC_FALSE);
2421                 dns_db_detachnode(gdb, &node);
2422                 /*
2423                  * Add hashs for empty nodes.  Use closest encloser logic.
2424                  * The closest encloser either has data or is a empty
2425                  * node for another <name,nextname> span so we don't add
2426                  * it here.  Empty labels on nextname are within the span.
2427                  */
2428                 dns_name_downcase(nextname, nextname, NULL);
2429                 dns_name_fullcompare(name, nextname, &order, &nlabels);
2430                 addnowildcardhash(hashlist, name, hashalg, iterations,
2431                                   salt, salt_length);
2432                 count = dns_name_countlabels(nextname);
2433                 while (count > nlabels + 1) {
2434                         count--;
2435                         dns_name_split(nextname, count, NULL, nextname);
2436                         hashlist_add_dns_name(hashlist, nextname, hashalg,
2437                                               iterations, salt, salt_length,
2438                                               ISC_FALSE);
2439                         addnowildcardhash(hashlist, nextname, hashalg,
2440                                           iterations, salt, salt_length);
2441                 }
2442         }
2443         dns_dbiterator_destroy(&dbiter);
2444
2445         /*
2446          * We have all the hashes now so we can sort them.
2447          */
2448         hashlist_sort(hashlist);
2449
2450         /*
2451          * Check for duplicate hashes.  If found the salt needs to
2452          * be changed.
2453          */
2454         if (hashlist_hasdup(hashlist))
2455                 fatal("Duplicate hash detected. Pick a different salt.");
2456
2457         /*
2458          * Generate the nsec3 records.
2459          */
2460         zonecut = NULL;
2461         done = ISC_FALSE;
2462
2463         addnsec3param(salt, salt_length, iterations);
2464
2465         /*
2466          * Clean out NSEC3 records which don't match this chain.
2467          */
2468         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
2469         check_result(result, "dns_db_createiterator()");
2470
2471         for (result = dns_dbiterator_first(dbiter);
2472              result == ISC_R_SUCCESS;
2473              result = dns_dbiterator_next(dbiter)) {
2474                 result = dns_dbiterator_current(dbiter, &node, name);
2475                 check_dns_dbiterator_current(result);
2476                 nsec3clean(name, node, hashalg, iterations, salt, salt_length,
2477                            hashlist);
2478                 dns_db_detachnode(gdb, &node);
2479         }
2480         dns_dbiterator_destroy(&dbiter);
2481
2482         /*
2483          * Generate / complete the new chain.
2484          */
2485         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
2486         check_result(result, "dns_db_createiterator()");
2487
2488         result = dns_dbiterator_first(dbiter);
2489         check_result(result, "dns_dbiterator_first()");
2490
2491         while (!done) {
2492                 result = dns_dbiterator_current(dbiter, &node, name);
2493                 check_dns_dbiterator_current(result);
2494                 /*
2495                  * Skip out-of-zone records.
2496                  */
2497                 if (!dns_name_issubdomain(name, gorigin)) {
2498                         result = dns_dbiterator_next(dbiter);
2499                         if (result == ISC_R_NOMORE)
2500                                 done = ISC_TRUE;
2501                         else
2502                                 check_result(result, "dns_dbiterator_next()");
2503                         dns_db_detachnode(gdb, &node);
2504                         continue;
2505                 }
2506                 result = dns_dbiterator_next(dbiter);
2507                 nextnode = NULL;
2508                 while (result == ISC_R_SUCCESS) {
2509                         result = dns_dbiterator_current(dbiter, &nextnode,
2510                                                         nextname);
2511                         check_dns_dbiterator_current(result);
2512                         active = active_node(nextnode);
2513                         if (!active) {
2514                                 dns_db_detachnode(gdb, &nextnode);
2515                                 result = dns_dbiterator_next(dbiter);
2516                                 continue;
2517                         }
2518                         if (!dns_name_issubdomain(nextname, gorigin) ||
2519                             (zonecut != NULL &&
2520                              dns_name_issubdomain(nextname, zonecut))) {
2521                                 dns_db_detachnode(gdb, &nextnode);
2522                                 result = dns_dbiterator_next(dbiter);
2523                                 continue;
2524                         }
2525                         if (delegation(nextname, nextnode, NULL)) {
2526                                 zonecut = dns_fixedname_name(&fzonecut);
2527                                 dns_name_copy(nextname, zonecut, NULL);
2528                                 if (OPTOUT(nsec3flags) &&
2529                                     !secure(nextname, nextnode)) {
2530                                         dns_db_detachnode(gdb, &nextnode);
2531                                         result = dns_dbiterator_next(dbiter);
2532                                         continue;
2533                                 }
2534                         }
2535                         dns_db_detachnode(gdb, &nextnode);
2536                         break;
2537                 }
2538                 if (result == ISC_R_NOMORE) {
2539                         dns_name_copy(gorigin, nextname, NULL);
2540                         done = ISC_TRUE;
2541                 } else if (result != ISC_R_SUCCESS)
2542                         fatal("iterating through the database failed: %s",
2543                               isc_result_totext(result));
2544                 /*
2545                  * We need to pause here to release the lock on the database.
2546                  */
2547                 dns_dbiterator_pause(dbiter);
2548                 addnsec3(name, node, salt, salt_length, iterations,
2549                          hashlist, zonettl);
2550                 dns_db_detachnode(gdb, &node);
2551                 /*
2552                  * Add NSEC3's for empty nodes.  Use closest encloser logic.
2553                  */
2554                 dns_name_fullcompare(name, nextname, &order, &nlabels);
2555                 count = dns_name_countlabels(nextname);
2556                 while (count > nlabels + 1) {
2557                         count--;
2558                         dns_name_split(nextname, count, NULL, nextname);
2559                         addnsec3(nextname, NULL, salt, salt_length,
2560                                  iterations, hashlist, zonettl);
2561                 }
2562         }
2563         dns_dbiterator_destroy(&dbiter);
2564 }
2565
2566 /*%
2567  * Load the zone file from disk
2568  */
2569 static void
2570 loadzone(char *file, char *origin, dns_rdataclass_t rdclass, dns_db_t **db) {
2571         isc_buffer_t b;
2572         int len;
2573         dns_fixedname_t fname;
2574         dns_name_t *name;
2575         isc_result_t result;
2576
2577         len = strlen(origin);
2578         isc_buffer_init(&b, origin, len);
2579         isc_buffer_add(&b, len);
2580
2581         dns_fixedname_init(&fname);
2582         name = dns_fixedname_name(&fname);
2583         result = dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL);
2584         if (result != ISC_R_SUCCESS)
2585                 fatal("failed converting name '%s' to dns format: %s",
2586                       origin, isc_result_totext(result));
2587
2588         result = dns_db_create(mctx, "rbt", name, dns_dbtype_zone,
2589                                rdclass, 0, NULL, db);
2590         check_result(result, "dns_db_create()");
2591
2592         result = dns_db_load2(*db, file, inputformat);
2593         if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE)
2594                 fatal("failed loading zone from '%s': %s",
2595                       file, isc_result_totext(result));
2596 }
2597
2598 /*%
2599  * Finds all public zone keys in the zone, and attempts to load the
2600  * private keys from disk.
2601  */
2602 static void
2603 loadzonekeys(dns_db_t *db) {
2604         dns_dbnode_t *node;
2605         dns_dbversion_t *currentversion;
2606         isc_result_t result;
2607         dst_key_t *keys[20];
2608         unsigned int nkeys, i;
2609
2610         currentversion = NULL;
2611         dns_db_currentversion(db, &currentversion);
2612
2613         node = NULL;
2614         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2615         if (result != ISC_R_SUCCESS)
2616                 fatal("failed to find the zone's origin: %s",
2617                       isc_result_totext(result));
2618
2619         result = dns_dnssec_findzonekeys(db, currentversion, node, gorigin,
2620                                          mctx, 20, keys, &nkeys);
2621         if (result == ISC_R_NOTFOUND)
2622                 result = ISC_R_SUCCESS;
2623         if (result != ISC_R_SUCCESS)
2624                 fatal("failed to find the zone keys: %s",
2625                       isc_result_totext(result));
2626
2627         for (i = 0; i < nkeys; i++) {
2628                 signer_key_t *key;
2629
2630                 key = newkeystruct(keys[i], dst_key_isprivate(keys[i]));
2631                 ISC_LIST_APPEND(keylist, key, link);
2632         }
2633         dns_db_detachnode(db, &node);
2634         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2635 }
2636
2637 /*%
2638  * Finds all public zone keys in the zone.
2639  */
2640 static void
2641 loadzonepubkeys(dns_db_t *db) {
2642         dns_dbversion_t *currentversion = NULL;
2643         dns_dbnode_t *node = NULL;
2644         dns_rdataset_t rdataset;
2645         dns_rdata_t rdata = DNS_RDATA_INIT;
2646         dst_key_t *pubkey;
2647         signer_key_t *key;
2648         isc_result_t result;
2649
2650         dns_db_currentversion(db, &currentversion);
2651
2652         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2653         if (result != ISC_R_SUCCESS)
2654                 fatal("failed to find the zone's origin: %s",
2655                       isc_result_totext(result));
2656
2657         dns_rdataset_init(&rdataset);
2658         result = dns_db_findrdataset(db, node, currentversion,
2659                                      dns_rdatatype_dnskey, 0, 0, &rdataset,
2660                                      NULL);
2661         if (result != ISC_R_SUCCESS)
2662                 fatal("failed to find keys at the zone apex: %s",
2663                       isc_result_totext(result));
2664         result = dns_rdataset_first(&rdataset);
2665         check_result(result, "dns_rdataset_first");
2666         while (result == ISC_R_SUCCESS) {
2667                 pubkey = NULL;
2668                 dns_rdata_reset(&rdata);
2669                 dns_rdataset_current(&rdataset, &rdata);
2670                 result = dns_dnssec_keyfromrdata(gorigin, &rdata, mctx,
2671                                                  &pubkey);
2672                 if (result != ISC_R_SUCCESS)
2673                         goto next;
2674                 if (!dst_key_iszonekey(pubkey)) {
2675                         dst_key_free(&pubkey);
2676                         goto next;
2677                 }
2678
2679                 key = newkeystruct(pubkey, ISC_FALSE);
2680                 ISC_LIST_APPEND(keylist, key, link);
2681  next:
2682                 result = dns_rdataset_next(&rdataset);
2683         }
2684         dns_rdataset_disassociate(&rdataset);
2685         dns_db_detachnode(db, &node);
2686         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2687 }
2688
2689 static void
2690 warnifallksk(dns_db_t *db) {
2691         dns_dbversion_t *currentversion = NULL;
2692         dns_dbnode_t *node = NULL;
2693         dns_rdataset_t rdataset;
2694         dns_rdata_t rdata = DNS_RDATA_INIT;
2695         isc_result_t result;
2696         dns_rdata_dnskey_t dnskey;
2697         isc_boolean_t have_non_ksk = ISC_FALSE;
2698
2699         dns_db_currentversion(db, &currentversion);
2700
2701         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2702         if (result != ISC_R_SUCCESS)
2703                 fatal("failed to find the zone's origin: %s",
2704                       isc_result_totext(result));
2705
2706         dns_rdataset_init(&rdataset);
2707         result = dns_db_findrdataset(db, node, currentversion,
2708                                      dns_rdatatype_dnskey, 0, 0, &rdataset,
2709                                      NULL);
2710         if (result != ISC_R_SUCCESS)
2711                 fatal("failed to find keys at the zone apex: %s",
2712                       isc_result_totext(result));
2713         result = dns_rdataset_first(&rdataset);
2714         check_result(result, "dns_rdataset_first");
2715         while (result == ISC_R_SUCCESS) {
2716                 dns_rdata_reset(&rdata);
2717                 dns_rdataset_current(&rdataset, &rdata);
2718                 result = dns_rdata_tostruct(&rdata, &dnskey, NULL);
2719                 check_result(result, "dns_rdata_tostruct");
2720                 if ((dnskey.flags & DNS_KEYFLAG_KSK) == 0) {
2721                         have_non_ksk = ISC_TRUE;
2722                         result = ISC_R_NOMORE;
2723                 } else
2724                         result = dns_rdataset_next(&rdataset);
2725                 dns_rdata_freestruct(&dnskey);
2726         }
2727         dns_rdataset_disassociate(&rdataset);
2728         dns_db_detachnode(db, &node);
2729         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2730         if (!have_non_ksk && !ignoreksk) {
2731                 if (disable_zone_check)
2732                         fprintf(stderr, "%s: warning: No non-KSK dnskey found. "
2733                                 "Supply non-KSK dnskey or use '-z'.\n",
2734                                 program);
2735                 else
2736                         fatal("No non-KSK dnskey found. "
2737                               "Supply non-KSK dnskey or use '-z'.");
2738         }
2739 }
2740
2741 static void
2742 writeset(const char *prefix, dns_rdatatype_t type) {
2743         char *filename;
2744         char namestr[DNS_NAME_FORMATSIZE];
2745         dns_db_t *db = NULL;
2746         dns_dbversion_t *version = NULL;
2747         dns_diff_t diff;
2748         dns_difftuple_t *tuple = NULL;
2749         dns_fixedname_t fixed;
2750         dns_name_t *name;
2751         dns_rdata_t rdata, ds;
2752         isc_boolean_t have_ksk = ISC_FALSE;
2753         isc_boolean_t have_non_ksk = ISC_FALSE;
2754         isc_buffer_t b;
2755         isc_buffer_t namebuf;
2756         isc_region_t r;
2757         isc_result_t result;
2758         signer_key_t *key;
2759         unsigned char dsbuf[DNS_DS_BUFFERSIZE];
2760         unsigned char keybuf[DST_KEY_MAXSIZE];
2761         unsigned int filenamelen;
2762         const dns_master_style_t *style =
2763                 (type == dns_rdatatype_dnskey) ? masterstyle : dsstyle;
2764
2765         isc_buffer_init(&namebuf, namestr, sizeof(namestr));
2766         result = dns_name_tofilenametext(gorigin, ISC_FALSE, &namebuf);
2767         check_result(result, "dns_name_tofilenametext");
2768         isc_buffer_putuint8(&namebuf, 0);
2769         filenamelen = strlen(prefix) + strlen(namestr);
2770         if (directory != NULL)
2771                 filenamelen += strlen(directory) + 1;
2772         filename = isc_mem_get(mctx, filenamelen + 1);
2773         if (filename == NULL)
2774                 fatal("out of memory");
2775         if (directory != NULL)
2776                 sprintf(filename, "%s/", directory);
2777         else
2778                 filename[0] = 0;
2779         strcat(filename, prefix);
2780         strcat(filename, namestr);
2781
2782         dns_diff_init(mctx, &diff);
2783
2784         for (key = ISC_LIST_HEAD(keylist);
2785              key != NULL;
2786              key = ISC_LIST_NEXT(key, link))
2787                 if (!key->isksk) {
2788                         have_non_ksk = ISC_TRUE;
2789                         break;
2790                 }
2791
2792         for (key = ISC_LIST_HEAD(keylist);
2793              key != NULL;
2794              key = ISC_LIST_NEXT(key, link))
2795                 if (key->isksk) {
2796                         have_ksk = ISC_TRUE;
2797                         break;
2798                 }
2799
2800         if (type == dns_rdatatype_dlv) {
2801                 dns_name_t tname;
2802                 unsigned int labels;
2803
2804                 dns_name_init(&tname, NULL);
2805                 dns_fixedname_init(&fixed);
2806                 name = dns_fixedname_name(&fixed);
2807                 labels = dns_name_countlabels(gorigin);
2808                 dns_name_getlabelsequence(gorigin, 0, labels - 1, &tname);
2809                 result = dns_name_concatenate(&tname, dlv, name, NULL);
2810                 check_result(result, "dns_name_concatenate");
2811         } else
2812                 name = gorigin;
2813
2814         for (key = ISC_LIST_HEAD(keylist);
2815              key != NULL;
2816              key = ISC_LIST_NEXT(key, link))
2817         {
2818                 if (have_ksk && have_non_ksk && !key->isksk)
2819                         continue;
2820                 dns_rdata_init(&rdata);
2821                 dns_rdata_init(&ds);
2822                 isc_buffer_init(&b, keybuf, sizeof(keybuf));
2823                 result = dst_key_todns(key->key, &b);
2824                 check_result(result, "dst_key_todns");
2825                 isc_buffer_usedregion(&b, &r);
2826                 dns_rdata_fromregion(&rdata, gclass, dns_rdatatype_dnskey, &r);
2827                 if (type != dns_rdatatype_dnskey) {
2828                         result = dns_ds_buildrdata(gorigin, &rdata,
2829                                                    DNS_DSDIGEST_SHA1,
2830                                                    dsbuf, &ds);
2831                         check_result(result, "dns_ds_buildrdata");
2832                         if (type == dns_rdatatype_dlv)
2833                                 ds.type = dns_rdatatype_dlv;
2834                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2835                                                       name, 0, &ds, &tuple);
2836                         check_result(result, "dns_difftuple_create");
2837                         dns_diff_append(&diff, &tuple);
2838
2839                         dns_rdata_reset(&ds);
2840                         result = dns_ds_buildrdata(gorigin, &rdata,
2841                                                    DNS_DSDIGEST_SHA256,
2842                                                    dsbuf, &ds);
2843                         check_result(result, "dns_ds_buildrdata");
2844                         if (type == dns_rdatatype_dlv)
2845                                 ds.type = dns_rdatatype_dlv;
2846                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2847                                                       name, 0, &ds, &tuple);
2848
2849                 } else
2850                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2851                                                       gorigin, zonettl,
2852                                                       &rdata, &tuple);
2853                 check_result(result, "dns_difftuple_create");
2854                 dns_diff_append(&diff, &tuple);
2855         }
2856
2857         result = dns_db_create(mctx, "rbt", dns_rootname, dns_dbtype_zone,
2858                                gclass, 0, NULL, &db);
2859         check_result(result, "dns_db_create");
2860
2861         result = dns_db_newversion(db, &version);
2862         check_result(result, "dns_db_newversion");
2863
2864         result = dns_diff_apply(&diff, db, version);
2865         check_result(result, "dns_diff_apply");
2866         dns_diff_clear(&diff);
2867
2868         result = dns_master_dump(mctx, db, version, style, filename);
2869         check_result(result, "dns_master_dump");
2870
2871         isc_mem_put(mctx, filename, filenamelen + 1);
2872
2873         dns_db_closeversion(db, &version, ISC_FALSE);
2874         dns_db_detach(&db);
2875 }
2876
2877 static void
2878 print_time(FILE *fp) {
2879         time_t currenttime;
2880
2881         if (outputformat != dns_masterformat_text)
2882                 return;
2883
2884         currenttime = time(NULL);
2885         fprintf(fp, "; File written on %s", ctime(&currenttime));
2886 }
2887
2888 static void
2889 print_version(FILE *fp) {
2890         if (outputformat != dns_masterformat_text)
2891                 return;
2892
2893         fprintf(fp, "; dnssec_signzone version " VERSION "\n");
2894 }
2895
2896 static void
2897 usage(void) {
2898         fprintf(stderr, "Usage:\n");
2899         fprintf(stderr, "\t%s [options] zonefile [keys]\n", program);
2900
2901         fprintf(stderr, "\n");
2902
2903         fprintf(stderr, "Version: %s\n", VERSION);
2904
2905         fprintf(stderr, "Options: (default value in parenthesis) \n");
2906         fprintf(stderr, "\t-c class (IN)\n");
2907         fprintf(stderr, "\t-d directory\n");
2908         fprintf(stderr, "\t\tdirectory to find keyset files (.)\n");
2909         fprintf(stderr, "\t-g:\t");
2910         fprintf(stderr, "generate DS records from keyset files\n");
2911         fprintf(stderr, "\t-s [YYYYMMDDHHMMSS|+offset]:\n");
2912         fprintf(stderr, "\t\tRRSIG start time - absolute|offset "
2913                                 "(now - 1 hour)\n");
2914         fprintf(stderr, "\t-e [YYYYMMDDHHMMSS|+offset|\"now\"+offset]:\n");
2915         fprintf(stderr, "\t\tRRSIG end time  - absolute|from start|from now "
2916                                 "(now + 30 days)\n");
2917         fprintf(stderr, "\t-i interval:\n");
2918         fprintf(stderr, "\t\tcycle interval - resign "
2919                                 "if < interval from end ( (end-start)/4 )\n");
2920         fprintf(stderr, "\t-j jitter:\n");
2921         fprintf(stderr, "\t\trandomize signature end time up to jitter "
2922                                 "seconds\n");
2923         fprintf(stderr, "\t-v debuglevel (0)\n");
2924         fprintf(stderr, "\t-o origin:\n");
2925         fprintf(stderr, "\t\tzone origin (name of zonefile)\n");
2926         fprintf(stderr, "\t-f outfile:\n");
2927         fprintf(stderr, "\t\tfile the signed zone is written in "
2928                                 "(zonefile + .signed)\n");
2929         fprintf(stderr, "\t-I format:\n");
2930         fprintf(stderr, "\t\tfile format of input zonefile (text)\n");
2931         fprintf(stderr, "\t-O format:\n");
2932         fprintf(stderr, "\t\tfile format of signed zone file (text)\n");
2933         fprintf(stderr, "\t-N format:\n");
2934         fprintf(stderr, "\t\tsoa serial format of signed zone file (keep)\n");
2935         fprintf(stderr, "\t-r randomdev:\n");
2936         fprintf(stderr, "\t\ta file containing random data\n");
2937         fprintf(stderr, "\t-a:\t");
2938         fprintf(stderr, "verify generated signatures\n");
2939         fprintf(stderr, "\t-p:\t");
2940         fprintf(stderr, "use pseudorandom data (faster but less secure)\n");
2941         fprintf(stderr, "\t-P:\t");
2942         fprintf(stderr, "disable post-sign verification\n");
2943         fprintf(stderr, "\t-t:\t");
2944         fprintf(stderr, "print statistics\n");
2945         fprintf(stderr, "\t-n ncpus (number of cpus present)\n");
2946         fprintf(stderr, "\t-k key_signing_key\n");
2947         fprintf(stderr, "\t-l lookasidezone\n");
2948         fprintf(stderr, "\t-3 salt (NSEC3 salt)\n");
2949         fprintf(stderr, "\t-H iterations (NSEC3 iterations)\n");
2950         fprintf(stderr, "\t-A (NSEC3 optout)\n");
2951         fprintf(stderr, "\t-z:\t");
2952         fprintf(stderr, "ignore KSK flag in DNSKEYs");
2953
2954         fprintf(stderr, "\n");
2955
2956         fprintf(stderr, "Signing Keys: ");
2957         fprintf(stderr, "(default: all zone keys that have private keys)\n");
2958         fprintf(stderr, "\tkeyfile (Kname+alg+tag)\n");
2959         exit(0);
2960 }
2961
2962 static void
2963 removetempfile(void) {
2964         if (removefile)
2965                 isc_file_remove(tempfile);
2966 }
2967
2968 static void
2969 print_stats(isc_time_t *timer_start, isc_time_t *timer_finish) {
2970         isc_uint64_t runtime_us;   /* Runtime in microseconds */
2971         isc_uint64_t runtime_ms;   /* Runtime in milliseconds */
2972         isc_uint64_t sig_ms;       /* Signatures per millisecond */
2973
2974         runtime_us = isc_time_microdiff(timer_finish, timer_start);
2975
2976         printf("Signatures generated:               %10d\n", nsigned);
2977         printf("Signatures retained:                %10d\n", nretained);
2978         printf("Signatures dropped:                 %10d\n", ndropped);
2979         printf("Signatures successfully verified:   %10d\n", nverified);
2980         printf("Signatures unsuccessfully verified: %10d\n", nverifyfailed);
2981         runtime_ms = runtime_us / 1000;
2982         printf("Runtime in seconds:                %7u.%03u\n",
2983                (unsigned int) (runtime_ms / 1000),
2984                (unsigned int) (runtime_ms % 1000));
2985         if (runtime_us > 0) {
2986                 sig_ms = ((isc_uint64_t)nsigned * 1000000000) / runtime_us;
2987                 printf("Signatures per second:             %7u.%03u\n",
2988                        (unsigned int) sig_ms / 1000,
2989                        (unsigned int) sig_ms % 1000);
2990         }
2991 }
2992
2993 int
2994 main(int argc, char *argv[]) {
2995         int i, ch;
2996         char *startstr = NULL, *endstr = NULL, *classname = NULL;
2997         char *origin = NULL, *file = NULL, *output = NULL;
2998         char *inputformatstr = NULL, *outputformatstr = NULL;
2999         char *serialformatstr = NULL;
3000         char *dskeyfile[MAXDSKEYS];
3001         int ndskeys = 0;
3002         char *endp;
3003         isc_time_t timer_start, timer_finish;
3004         signer_key_t *key;
3005         isc_result_t result;
3006         isc_log_t *log = NULL;
3007         isc_boolean_t pseudorandom = ISC_FALSE;
3008         unsigned int eflags;
3009         isc_boolean_t free_output = ISC_FALSE;
3010         int tempfilelen;
3011         dns_rdataclass_t rdclass;
3012         isc_task_t **tasks = NULL;
3013         isc_buffer_t b;
3014         int len;
3015         unsigned int iterations = 100U;
3016         const unsigned char *salt = NULL;
3017         size_t salt_length = 0;
3018         unsigned char saltbuf[255];
3019         hashlist_t hashlist;
3020
3021 #define CMDLINE_FLAGS "3:aAc:d:e:f:FghH:i:I:j:k:l:m:n:N:o:O:pPr:s:StUv:z"
3022
3023         /*
3024          * Process memory debugging argument first.
3025          */
3026         while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
3027                 switch (ch) {
3028                 case 'm':
3029                         if (strcasecmp(isc_commandline_argument, "record") == 0)
3030                                 isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
3031                         if (strcasecmp(isc_commandline_argument, "trace") == 0)
3032                                 isc_mem_debugging |= ISC_MEM_DEBUGTRACE;
3033                         if (strcasecmp(isc_commandline_argument, "usage") == 0)
3034                                 isc_mem_debugging |= ISC_MEM_DEBUGUSAGE;
3035                         if (strcasecmp(isc_commandline_argument, "size") == 0)
3036                                 isc_mem_debugging |= ISC_MEM_DEBUGSIZE;
3037                         if (strcasecmp(isc_commandline_argument, "mctx") == 0)
3038                                 isc_mem_debugging |= ISC_MEM_DEBUGCTX;
3039                         break;
3040                 default:
3041                         break;
3042                 }
3043         }
3044         isc_commandline_reset = ISC_TRUE;
3045
3046         masterstyle = &dns_master_style_explicitttl;
3047
3048         check_result(isc_app_start(), "isc_app_start");
3049
3050         result = isc_mem_create(0, 0, &mctx);
3051         if (result != ISC_R_SUCCESS)
3052                 fatal("out of memory");
3053
3054         dns_result_register();
3055
3056         isc_commandline_errprint = ISC_FALSE;
3057
3058         while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
3059                 switch (ch) {
3060                 case '3':
3061                         if (strcmp(isc_commandline_argument, "-")) {
3062                                 isc_buffer_t target;
3063                                 char *sarg;
3064
3065                                 sarg = isc_commandline_argument;
3066                                 isc_buffer_init(&target, saltbuf,
3067                                                 sizeof(saltbuf));
3068                                 result = isc_hex_decodestring(sarg, &target);
3069                                 check_result(result,
3070                                              "isc_hex_decodestring(salt)");
3071                                 salt = saltbuf;
3072                                 salt_length = isc_buffer_usedlength(&target);
3073                         } else {
3074                                 salt = saltbuf;
3075                                 salt_length = 0;
3076                         }
3077                         nsec_datatype = dns_rdatatype_nsec3;
3078                         break;
3079
3080                 case 'A':
3081                         nsec3flags |= DNS_NSEC3FLAG_OPTOUT;
3082                         break;
3083
3084                 case 'a':
3085                         tryverify = ISC_TRUE;
3086                         break;
3087
3088                 case 'c':
3089                         classname = isc_commandline_argument;
3090                         break;
3091
3092                 case 'd':
3093                         directory = isc_commandline_argument;
3094                         break;
3095
3096                 case 'e':
3097                         endstr = isc_commandline_argument;
3098                         break;
3099
3100                 case 'f':
3101                         output = isc_commandline_argument;
3102                         break;
3103
3104                 case 'g':
3105                         generateds = ISC_TRUE;
3106                         break;
3107
3108                 case 'H':
3109                         iterations = strtoul(isc_commandline_argument,
3110                                              &endp, 0);
3111                         if (*endp != '\0')
3112                                 fatal("iterations must be numeric");
3113                         if (iterations > 0xffffU)
3114                                 fatal("iterations too big");
3115                         break;
3116
3117                 case 'h':
3118                         usage();
3119                         break;
3120
3121                 case 'i':
3122                         endp = NULL;
3123                         cycle = strtol(isc_commandline_argument, &endp, 0);
3124                         if (*endp != '\0' || cycle < 0)
3125                                 fatal("cycle period must be numeric and "
3126                                       "positive");
3127                         break;
3128
3129                 case 'I':
3130                         inputformatstr = isc_commandline_argument;
3131                         break;
3132
3133                 case 'j':
3134                         endp = NULL;
3135                         jitter = strtol(isc_commandline_argument, &endp, 0);
3136                         if (*endp != '\0' || jitter < 0)
3137                                 fatal("jitter must be numeric and positive");
3138                         break;
3139
3140                 case 'k':
3141                         if (ndskeys == MAXDSKEYS)
3142                                 fatal("too many key-signing keys specified");
3143                         dskeyfile[ndskeys++] = isc_commandline_argument;
3144                         break;
3145
3146                 case 'l':
3147                         len = strlen(isc_commandline_argument);
3148                         isc_buffer_init(&b, isc_commandline_argument, len);
3149                         isc_buffer_add(&b, len);
3150
3151                         dns_fixedname_init(&dlv_fixed);
3152                         dlv = dns_fixedname_name(&dlv_fixed);
3153                         result = dns_name_fromtext(dlv, &b, dns_rootname,
3154                                                    ISC_FALSE, NULL);
3155                         check_result(result, "dns_name_fromtext(dlv)");
3156                         break;
3157
3158                 case 'm':
3159                         break;
3160
3161                 case 'n':
3162                         endp = NULL;
3163                         ntasks = strtol(isc_commandline_argument, &endp, 0);
3164                         if (*endp != '\0' || ntasks > ISC_INT32_MAX)
3165                                 fatal("number of cpus must be numeric");
3166                         break;
3167
3168                 case 'N':
3169                         serialformatstr = isc_commandline_argument;
3170                         break;
3171
3172                 case 'o':
3173                         origin = isc_commandline_argument;
3174                         break;
3175
3176                 case 'O':
3177                         outputformatstr = isc_commandline_argument;
3178                         break;
3179
3180                 case 'p':
3181                         pseudorandom = ISC_TRUE;
3182                         break;
3183
3184                 case 'P':
3185                         disable_zone_check = ISC_TRUE;
3186                         break;
3187
3188                 case 'r':
3189                         setup_entropy(mctx, isc_commandline_argument, &ectx);
3190                         break;
3191
3192                 case 's':
3193                         startstr = isc_commandline_argument;
3194                         break;
3195
3196                 case 'S':
3197                         /* This is intentionally undocumented */
3198                         /* -S: simple output style */
3199                         masterstyle = &dns_master_style_simple;
3200                         break;
3201
3202                 case 't':
3203                         printstats = ISC_TRUE;
3204                         break;
3205
3206                 case 'U':       /* Undocumented for testing only. */
3207                         unknownalg = ISC_TRUE;
3208                         break;
3209
3210                 case 'v':
3211                         endp = NULL;
3212                         verbose = strtol(isc_commandline_argument, &endp, 0);
3213                         if (*endp != '\0')
3214                                 fatal("verbose level must be numeric");
3215                         break;
3216
3217                 case 'z':
3218                         ignoreksk = ISC_TRUE;
3219                         break;
3220
3221                 case 'F':
3222                         /* Reserved for FIPS mode */
3223                         /* FALLTHROUGH */
3224                 case '?':
3225                         if (isc_commandline_option != '?')
3226                                 fprintf(stderr, "%s: invalid argument -%c\n",
3227                                         program, isc_commandline_option);
3228                         usage();
3229                         break;
3230
3231                 default:
3232                         fprintf(stderr, "%s: unhandled option -%c\n",
3233                                 program, isc_commandline_option);
3234                         exit(1);
3235                 }
3236         }
3237
3238         if (ectx == NULL)
3239                 setup_entropy(mctx, NULL, &ectx);
3240         eflags = ISC_ENTROPY_BLOCKING;
3241         if (!pseudorandom)
3242                 eflags |= ISC_ENTROPY_GOODONLY;
3243
3244         result = isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE);
3245         if (result != ISC_R_SUCCESS)
3246                 fatal("could not create hash context");
3247
3248         result = dst_lib_init(mctx, ectx, eflags);
3249         if (result != ISC_R_SUCCESS)
3250                 fatal("could not initialize dst");
3251
3252         isc_stdtime_get(&now);
3253
3254         if (startstr != NULL)
3255                 starttime = strtotime(startstr, now, now);
3256         else
3257                 starttime = now - 3600;  /* Allow for some clock skew. */
3258
3259         if (endstr != NULL)
3260                 endtime = strtotime(endstr, now, starttime);
3261         else
3262                 endtime = starttime + (30 * 24 * 60 * 60);
3263
3264         if (cycle == -1)
3265                 cycle = (endtime - starttime) / 4;
3266
3267         if (ntasks == 0)
3268                 ntasks = isc_os_ncpus() * 2;
3269         vbprintf(4, "using %d cpus\n", ntasks);
3270
3271         rdclass = strtoclass(classname);
3272
3273         setup_logging(verbose, mctx, &log);
3274
3275         argc -= isc_commandline_index;
3276         argv += isc_commandline_index;
3277
3278         if (argc < 1)
3279                 usage();
3280
3281         file = argv[0];
3282
3283         argc -= 1;
3284         argv += 1;
3285
3286         if (origin == NULL)
3287                 origin = file;
3288
3289         if (output == NULL) {
3290                 free_output = ISC_TRUE;
3291                 output = isc_mem_allocate(mctx,
3292                                           strlen(file) + strlen(".signed") + 1);
3293                 if (output == NULL)
3294                         fatal("out of memory");
3295                 sprintf(output, "%s.signed", file);
3296         }
3297
3298         if (inputformatstr != NULL) {
3299                 if (strcasecmp(inputformatstr, "text") == 0)
3300                         inputformat = dns_masterformat_text;
3301                 else if (strcasecmp(inputformatstr, "raw") == 0)
3302                         inputformat = dns_masterformat_raw;
3303                 else
3304                         fatal("unknown file format: %s\n", inputformatstr);
3305         }
3306
3307         if (outputformatstr != NULL) {
3308                 if (strcasecmp(outputformatstr, "text") == 0)
3309                         outputformat = dns_masterformat_text;
3310                 else if (strcasecmp(outputformatstr, "raw") == 0)
3311                         outputformat = dns_masterformat_raw;
3312                 else
3313                         fatal("unknown file format: %s\n", outputformatstr);
3314         }
3315
3316         if (serialformatstr != NULL) {
3317                 if (strcasecmp(serialformatstr, "keep") == 0)
3318                         serialformat = SOA_SERIAL_KEEP;
3319                 else if (strcasecmp(serialformatstr, "increment") == 0 ||
3320                          strcasecmp(serialformatstr, "incr") == 0)
3321                         serialformat = SOA_SERIAL_INCREMENT;
3322                 else if (strcasecmp(serialformatstr, "unixtime") == 0)
3323                         serialformat = SOA_SERIAL_UNIXTIME;
3324                 else
3325                         fatal("unknown soa serial format: %s\n",
3326                               serialformatstr);
3327         }
3328
3329         result = dns_master_stylecreate(&dsstyle,  DNS_STYLEFLAG_NO_TTL,
3330                                         0, 24, 0, 0, 0, 8, mctx);
3331         check_result(result, "dns_master_stylecreate");
3332
3333         gdb = NULL;
3334         TIME_NOW(&timer_start);
3335         loadzone(file, origin, rdclass, &gdb);
3336         gorigin = dns_db_origin(gdb);
3337         gclass = dns_db_class(gdb);
3338         zonettl = soattl();
3339
3340         if (IS_NSEC3) {
3341                 isc_boolean_t answer;
3342                 hash_length = dns_nsec3_hashlength(dns_hash_sha1);
3343                 hashlist_init(&hashlist, dns_db_nodecount(gdb) * 2,
3344                               hash_length);
3345                 result = dns_nsec_nseconly(gdb, gversion, &answer);
3346                 check_result(result, "dns_nsec_nseconly");
3347                 if (answer)
3348                         fatal("NSEC3 generation requested with "
3349                               "NSEC only DNSKEY");
3350         }
3351
3352         /*
3353          * We need to do this early on, as we start messing with the list
3354          * of keys rather early.
3355          */
3356         ISC_LIST_INIT(keylist);
3357         isc_rwlock_init(&keylist_lock, 0, 0);
3358
3359         if (argc == 0) {
3360                 loadzonekeys(gdb);
3361         } else {
3362                 for (i = 0; i < argc; i++) {
3363                         dst_key_t *newkey = NULL;
3364
3365                         result = dst_key_fromnamedfile(argv[i],
3366                                                        DST_TYPE_PUBLIC |
3367                                                        DST_TYPE_PRIVATE,
3368                                                        mctx, &newkey);
3369                         if (result != ISC_R_SUCCESS)
3370                                 fatal("cannot load dnskey %s: %s", argv[i],
3371                                       isc_result_totext(result));
3372
3373                         if (!dns_name_equal(gorigin, dst_key_name(newkey)))
3374                                 fatal("key %s not at origin\n", argv[i]);
3375
3376                         key = ISC_LIST_HEAD(keylist);
3377                         while (key != NULL) {
3378                                 dst_key_t *dkey = key->key;
3379                                 if (dst_key_id(dkey) == dst_key_id(newkey) &&
3380                                     dst_key_alg(dkey) == dst_key_alg(newkey) &&
3381                                     dns_name_equal(dst_key_name(dkey),
3382                                                    dst_key_name(newkey)))
3383                                 {
3384                                         if (!dst_key_isprivate(dkey))
3385                                                 fatal("cannot sign zone with "
3386                                                       "non-private dnskey %s",
3387                                                       argv[i]);
3388                                         break;
3389                                 }
3390                                 key = ISC_LIST_NEXT(key, link);
3391                         }
3392                         if (key == NULL) {
3393                                 key = newkeystruct(newkey, ISC_TRUE);
3394                                 key->commandline = ISC_TRUE;
3395                                 ISC_LIST_APPEND(keylist, key, link);
3396                         } else
3397                                 dst_key_free(&newkey);
3398                 }
3399
3400                 loadzonepubkeys(gdb);
3401         }
3402
3403         for (i = 0; i < ndskeys; i++) {
3404                 dst_key_t *newkey = NULL;
3405
3406                 result = dst_key_fromnamedfile(dskeyfile[i],
3407                                                DST_TYPE_PUBLIC |
3408                                                DST_TYPE_PRIVATE,
3409                                                mctx, &newkey);
3410                 if (result != ISC_R_SUCCESS)
3411                         fatal("cannot load dnskey %s: %s", dskeyfile[i],
3412                               isc_result_totext(result));
3413
3414                 if (!dns_name_equal(gorigin, dst_key_name(newkey)))
3415                         fatal("key %s not at origin\n", dskeyfile[i]);
3416
3417                 key = ISC_LIST_HEAD(keylist);
3418                 while (key != NULL) {
3419                         dst_key_t *dkey = key->key;
3420                         if (dst_key_id(dkey) == dst_key_id(newkey) &&
3421                             dst_key_alg(dkey) == dst_key_alg(newkey) &&
3422                             dns_name_equal(dst_key_name(dkey),
3423                                            dst_key_name(newkey)))
3424                         {
3425                                 /* Override key flags. */
3426                                 key->issigningkey = ISC_TRUE;
3427                                 key->isksk = ISC_TRUE;
3428                                 key->isdsk = ISC_FALSE;
3429                                 dst_key_free(&dkey);
3430                                 key->key = newkey;
3431                                 break;
3432                         }
3433                         key = ISC_LIST_NEXT(key, link);
3434                 }
3435                 if (key == NULL) {
3436                         /* Override dnskey flags. */
3437                         key = newkeystruct(newkey, ISC_TRUE);
3438                         key->isksk = ISC_TRUE;
3439                         key->isdsk = ISC_FALSE;
3440                         ISC_LIST_APPEND(keylist, key, link);
3441                 }
3442         }
3443
3444         if (ISC_LIST_EMPTY(keylist)) {
3445                 if (disable_zone_check)
3446                         fprintf(stderr, "%s: warning: No keys specified "
3447                                 "or found\n", program);
3448                 else
3449                         fatal("No signing keys specified or found.");
3450                 nokeys = ISC_TRUE;
3451         }
3452
3453         if (IS_NSEC3) {
3454                 unsigned int max;
3455                 result = dns_nsec3_maxiterations(gdb, NULL, mctx, &max);
3456                 check_result(result, "dns_nsec3_maxiterations()");
3457                 if (iterations > max)
3458                         fatal("NSEC3 iterations too big for weakest DNSKEY "
3459                               "strength. Maximum iterations allowed %u.", max);
3460         }
3461
3462         warnifallksk(gdb);
3463
3464         gversion = NULL;
3465         result = dns_db_newversion(gdb, &gversion);
3466         check_result(result, "dns_db_newversion()");
3467
3468         switch (serialformat) {
3469                 case SOA_SERIAL_INCREMENT:
3470                         setsoaserial(0);
3471                         break;
3472                 case SOA_SERIAL_UNIXTIME:
3473                         setsoaserial(now);
3474                         break;
3475                 case SOA_SERIAL_KEEP:
3476                 default:
3477                         /* do nothing */
3478                         break;
3479         }
3480
3481         if (IS_NSEC3)
3482                 nsec3ify(dns_hash_sha1, iterations, salt, salt_length,
3483                          &hashlist);
3484         else
3485                 nsecify();
3486
3487         if (!nokeys) {
3488                 writeset("keyset-", dns_rdatatype_dnskey);
3489                 writeset("dsset-", dns_rdatatype_ds);
3490                 if (dlv != NULL) {
3491                         writeset("dlvset-", dns_rdatatype_dlv);
3492                 }
3493         }
3494
3495         tempfilelen = strlen(output) + 20;
3496         tempfile = isc_mem_get(mctx, tempfilelen);
3497         if (tempfile == NULL)
3498                 fatal("out of memory");
3499
3500         result = isc_file_mktemplate(output, tempfile, tempfilelen);
3501         check_result(result, "isc_file_mktemplate");
3502
3503         fp = NULL;
3504         result = isc_file_openunique(tempfile, &fp);
3505         if (result != ISC_R_SUCCESS)
3506                 fatal("failed to open temporary output file: %s",
3507                       isc_result_totext(result));
3508         removefile = ISC_TRUE;
3509         setfatalcallback(&removetempfile);
3510
3511         print_time(fp);
3512         print_version(fp);
3513
3514         result = isc_taskmgr_create(mctx, ntasks, 0, &taskmgr);
3515         if (result != ISC_R_SUCCESS)
3516                 fatal("failed to create task manager: %s",
3517                       isc_result_totext(result));
3518
3519         master = NULL;
3520         result = isc_task_create(taskmgr, 0, &master);
3521         if (result != ISC_R_SUCCESS)
3522                 fatal("failed to create task: %s", isc_result_totext(result));
3523
3524         tasks = isc_mem_get(mctx, ntasks * sizeof(isc_task_t *));
3525         if (tasks == NULL)
3526                 fatal("out of memory");
3527         for (i = 0; i < (int)ntasks; i++) {
3528                 tasks[i] = NULL;
3529                 result = isc_task_create(taskmgr, 0, &tasks[i]);
3530                 if (result != ISC_R_SUCCESS)
3531                         fatal("failed to create task: %s",
3532                               isc_result_totext(result));
3533         }
3534
3535         RUNTIME_CHECK(isc_mutex_init(&namelock) == ISC_R_SUCCESS);
3536         if (printstats)
3537                 RUNTIME_CHECK(isc_mutex_init(&statslock) == ISC_R_SUCCESS);
3538
3539         presign();
3540         signapex();
3541         if (!finished) {
3542                 /*
3543                  * There is more work to do.  Spread it out over multiple
3544                  * processors if possible.
3545                  */
3546                 for (i = 0; i < (int)ntasks; i++) {
3547                         result = isc_app_onrun(mctx, master, startworker,
3548                                                tasks[i]);
3549                         if (result != ISC_R_SUCCESS)
3550                                 fatal("failed to start task: %s",
3551                                       isc_result_totext(result));
3552                 }
3553                 (void)isc_app_run();
3554                 if (!finished)
3555                         fatal("process aborted by user");
3556         } else
3557                 isc_task_detach(&master);
3558         shuttingdown = ISC_TRUE;
3559         for (i = 0; i < (int)ntasks; i++)
3560                 isc_task_detach(&tasks[i]);
3561         isc_taskmgr_destroy(&taskmgr);
3562         isc_mem_put(mctx, tasks, ntasks * sizeof(isc_task_t *));
3563         postsign();
3564         verifyzone();
3565
3566         if (outputformat != dns_masterformat_text) {
3567                 result = dns_master_dumptostream2(mctx, gdb, gversion,
3568                                                   masterstyle, outputformat,
3569                                                   fp);
3570                 check_result(result, "dns_master_dumptostream2");
3571         }
3572
3573         result = isc_stdio_close(fp);
3574         check_result(result, "isc_stdio_close");
3575         removefile = ISC_FALSE;
3576
3577         result = isc_file_rename(tempfile, output);
3578         if (result != ISC_R_SUCCESS)
3579                 fatal("failed to rename temp file to %s: %s\n",
3580                       output, isc_result_totext(result));
3581
3582         DESTROYLOCK(&namelock);
3583         if (printstats)
3584                 DESTROYLOCK(&statslock);
3585
3586         printf("%s\n", output);
3587
3588         dns_db_closeversion(gdb, &gversion, ISC_FALSE);
3589         dns_db_detach(&gdb);
3590
3591         while (!ISC_LIST_EMPTY(keylist)) {
3592                 key = ISC_LIST_HEAD(keylist);
3593                 ISC_LIST_UNLINK(keylist, key, link);
3594                 dst_key_free(&key->key);
3595                 isc_mem_put(mctx, key, sizeof(signer_key_t));
3596         }
3597
3598         isc_mem_put(mctx, tempfile, tempfilelen);
3599
3600         if (free_output)
3601                 isc_mem_free(mctx, output);
3602
3603         dns_master_styledestroy(&dsstyle, mctx);
3604
3605         cleanup_logging(&log);
3606         dst_lib_destroy();
3607         isc_hash_destroy();
3608         cleanup_entropy(&ectx);
3609         dns_name_destroy();
3610         if (verbose > 10)
3611                 isc_mem_stats(mctx, stdout);
3612         isc_mem_destroy(&mctx);
3613
3614         (void) isc_app_finish();
3615
3616         if (printstats) {
3617                 TIME_NOW(&timer_finish);
3618                 print_stats(&timer_start, &timer_finish);
3619         }
3620
3621         return (0);
3622 }