]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - contrib/bind9/bin/dnssec/dnssec-signzone.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / contrib / bind9 / bin / dnssec / dnssec-signzone.c
1 /*
2  * Portions Copyright (C) 2004-2009  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.18 2009/11/03 23:47:45 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 (delegation(name, node, NULL)) {
1610                         zonecut = dns_fixedname_name(&fzonecut);
1611                         dns_name_copy(name, zonecut, NULL);
1612                         isdelegation = ISC_TRUE;
1613                 }
1614                 verifynode(name, node, isdelegation, &rdataset,
1615                            ksk_algorithms, bad_algorithms);
1616                 result = dns_dbiterator_next(dbiter);
1617                 nextnode = NULL;
1618                 while (result == ISC_R_SUCCESS) {
1619                         result = dns_dbiterator_current(dbiter, &nextnode,
1620                                                         nextname);
1621                         check_dns_dbiterator_current(result);
1622                         if (!dns_name_issubdomain(nextname, gorigin) ||
1623                             (zonecut != NULL &&
1624                              dns_name_issubdomain(nextname, zonecut)))
1625                         {
1626                                 dns_db_detachnode(gdb, &nextnode);
1627                                 result = dns_dbiterator_next(dbiter);
1628                                 continue;
1629                         }
1630                         dns_db_detachnode(gdb, &nextnode);
1631                         break;
1632                 }
1633                 if (result == ISC_R_NOMORE) {
1634                         done = ISC_TRUE;
1635                 } else if (result != ISC_R_SUCCESS)
1636                         fatal("iterating through the database failed: %s",
1637                               isc_result_totext(result));
1638                 dns_db_detachnode(gdb, &node);
1639         }
1640
1641         dns_dbiterator_destroy(&dbiter);
1642
1643         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
1644         check_result(result, "dns_db_createiterator()");
1645
1646         for (result = dns_dbiterator_first(dbiter);
1647              result == ISC_R_SUCCESS;
1648              result = dns_dbiterator_next(dbiter) ) {
1649                 result = dns_dbiterator_current(dbiter, &node, name);
1650                 check_dns_dbiterator_current(result);
1651                 verifynode(name, node, ISC_FALSE, &rdataset,
1652                            ksk_algorithms, bad_algorithms);
1653                 dns_db_detachnode(gdb, &node);
1654         }
1655         dns_dbiterator_destroy(&dbiter);
1656
1657         dns_rdataset_disassociate(&rdataset);
1658
1659         /*
1660          * If we made it this far, we have what we consider a properly signed
1661          * zone.  Set the good flag.
1662          */
1663         for (i = 0; i < 256; i++) {
1664                 if (bad_algorithms[i] != 0) {
1665                         if (first)
1666                                 fprintf(stderr, "The zone is not fully signed "
1667                                         "for the following algorithms:");
1668                         alg_format(i, algbuf, sizeof(algbuf));
1669                         fprintf(stderr, " %s", algbuf);
1670                         first = ISC_FALSE;
1671                 }
1672         }
1673         if (!first) {
1674                 fprintf(stderr, ".\n");
1675                 fatal("DNSSEC completeness test failed.");
1676         }
1677
1678         if (goodksk) {
1679                 /*
1680                  * Print the success summary.
1681                  */
1682                 fprintf(stderr, "Zone signing complete:\n");
1683                 for (i = 0; i < 256; i++) {
1684                         if ((zsk_algorithms[i] != 0) ||
1685                             (ksk_algorithms[i] != 0) ||
1686                             (revoked[i] != 0) || (standby[i] != 0)) {
1687                                 alg_format(i, algbuf, sizeof(algbuf));
1688                                 fprintf(stderr, "Algorithm: %s: ZSKs: %u, "
1689                                         "KSKs: %u active, %u revoked, %u "
1690                                         "stand-by\n", algbuf,
1691                                         zsk_algorithms[i], ksk_algorithms[i],
1692                                         revoked[i], standby[i]);
1693                         }
1694                 }
1695         }
1696 }
1697
1698 /*%
1699  * Sign the apex of the zone.
1700  * Note the origin may not be the first node if there are out of zone
1701  * records.
1702  */
1703 static void
1704 signapex(void) {
1705         dns_dbnode_t *node = NULL;
1706         dns_fixedname_t fixed;
1707         dns_name_t *name;
1708         isc_result_t result;
1709
1710         dns_fixedname_init(&fixed);
1711         name = dns_fixedname_name(&fixed);
1712         result = dns_dbiterator_seek(gdbiter, gorigin);
1713         check_result(result, "dns_dbiterator_seek()");
1714         result = dns_dbiterator_current(gdbiter, &node, name);
1715         check_dns_dbiterator_current(result);
1716         signname(node, name);
1717         dumpnode(name, node);
1718         cleannode(gdb, gversion, node);
1719         dns_db_detachnode(gdb, &node);
1720         result = dns_dbiterator_first(gdbiter);
1721         if (result == ISC_R_NOMORE)
1722                 finished = ISC_TRUE;
1723         else if (result != ISC_R_SUCCESS)
1724                 fatal("failure iterating database: %s",
1725                       isc_result_totext(result));
1726 }
1727
1728 /*%
1729  * Assigns a node to a worker thread.  This is protected by the master task's
1730  * lock.
1731  */
1732 static void
1733 assignwork(isc_task_t *task, isc_task_t *worker) {
1734         dns_fixedname_t *fname;
1735         dns_name_t *name;
1736         dns_dbnode_t *node;
1737         sevent_t *sevent;
1738         dns_rdataset_t nsec;
1739         isc_boolean_t found;
1740         isc_result_t result;
1741         static dns_name_t *zonecut = NULL;      /* Protected by namelock. */
1742         static dns_fixedname_t fzonecut;        /* Protected by namelock. */
1743         static unsigned int ended = 0;          /* Protected by namelock. */
1744
1745         if (shuttingdown)
1746                 return;
1747
1748         LOCK(&namelock);
1749         if (finished) {
1750                 ended++;
1751                 if (ended == ntasks) {
1752                         isc_task_detach(&task);
1753                         isc_app_shutdown();
1754                 }
1755                 goto unlock;
1756         }
1757
1758         fname = isc_mem_get(mctx, sizeof(dns_fixedname_t));
1759         if (fname == NULL)
1760                 fatal("out of memory");
1761         dns_fixedname_init(fname);
1762         name = dns_fixedname_name(fname);
1763         node = NULL;
1764         found = ISC_FALSE;
1765         while (!found) {
1766                 result = dns_dbiterator_current(gdbiter, &node, name);
1767                 check_dns_dbiterator_current(result);
1768                 /*
1769                  * The origin was handled by signapex().
1770                  */
1771                 if (dns_name_equal(name, gorigin)) {
1772                         dns_db_detachnode(gdb, &node);
1773                         goto next;
1774                 }
1775                 /*
1776                  * Sort the zone data from the glue and out-of-zone data.
1777                  * For NSEC zones nodes with zone data have NSEC records.
1778                  * For NSEC3 zones the NSEC3 nodes are zone data but
1779                  * outside of the zone name space.  For the rest we need
1780                  * to track the bottom of zone cuts.
1781                  * Nodes which don't need to be signed are dumped here.
1782                  */
1783                 dns_rdataset_init(&nsec);
1784                 result = dns_db_findrdataset(gdb, node, gversion,
1785                                              nsec_datatype, 0, 0,
1786                                              &nsec, NULL);
1787                 if (dns_rdataset_isassociated(&nsec))
1788                         dns_rdataset_disassociate(&nsec);
1789                 if (result == ISC_R_SUCCESS) {
1790                         found = ISC_TRUE;
1791                 } else if (nsec_datatype == dns_rdatatype_nsec3) {
1792                         if (dns_name_issubdomain(name, gorigin) &&
1793                             (zonecut == NULL ||
1794                              !dns_name_issubdomain(name, zonecut))) {
1795                                 if (delegation(name, node, NULL)) {
1796                                         dns_fixedname_init(&fzonecut);
1797                                         zonecut = dns_fixedname_name(&fzonecut);
1798                                         dns_name_copy(name, zonecut, NULL);
1799                                         if (!OPTOUT(nsec3flags) ||
1800                                             secure(name, node))
1801                                                 found = ISC_TRUE;
1802                                 } else
1803                                         found = ISC_TRUE;
1804                         }
1805                 }
1806
1807                 if (!found) {
1808                         dumpnode(name, node);
1809                         dns_db_detachnode(gdb, &node);
1810                 }
1811
1812  next:
1813                 result = dns_dbiterator_next(gdbiter);
1814                 if (result == ISC_R_NOMORE) {
1815                         finished = ISC_TRUE;
1816                         break;
1817                 } else if (result != ISC_R_SUCCESS)
1818                         fatal("failure iterating database: %s",
1819                               isc_result_totext(result));
1820         }
1821         if (!found) {
1822                 ended++;
1823                 if (ended == ntasks) {
1824                         isc_task_detach(&task);
1825                         isc_app_shutdown();
1826                 }
1827                 isc_mem_put(mctx, fname, sizeof(dns_fixedname_t));
1828                 goto unlock;
1829         }
1830         sevent = (sevent_t *)
1831                  isc_event_allocate(mctx, task, SIGNER_EVENT_WORK,
1832                                     sign, NULL, sizeof(sevent_t));
1833         if (sevent == NULL)
1834                 fatal("failed to allocate event\n");
1835
1836         sevent->node = node;
1837         sevent->fname = fname;
1838         isc_task_send(worker, ISC_EVENT_PTR(&sevent));
1839  unlock:
1840         UNLOCK(&namelock);
1841 }
1842
1843 /*%
1844  * Start a worker task
1845  */
1846 static void
1847 startworker(isc_task_t *task, isc_event_t *event) {
1848         isc_task_t *worker;
1849
1850         worker = (isc_task_t *)event->ev_arg;
1851         assignwork(task, worker);
1852         isc_event_free(&event);
1853 }
1854
1855 /*%
1856  * Write a node to the output file, and restart the worker task.
1857  */
1858 static void
1859 writenode(isc_task_t *task, isc_event_t *event) {
1860         isc_task_t *worker;
1861         sevent_t *sevent = (sevent_t *)event;
1862
1863         worker = (isc_task_t *)event->ev_sender;
1864         dumpnode(dns_fixedname_name(sevent->fname), sevent->node);
1865         cleannode(gdb, gversion, sevent->node);
1866         dns_db_detachnode(gdb, &sevent->node);
1867         isc_mem_put(mctx, sevent->fname, sizeof(dns_fixedname_t));
1868         assignwork(task, worker);
1869         isc_event_free(&event);
1870 }
1871
1872 /*%
1873  *  Sign a database node.
1874  */
1875 static void
1876 sign(isc_task_t *task, isc_event_t *event) {
1877         dns_fixedname_t *fname;
1878         dns_dbnode_t *node;
1879         sevent_t *sevent, *wevent;
1880
1881         sevent = (sevent_t *)event;
1882         node = sevent->node;
1883         fname = sevent->fname;
1884         isc_event_free(&event);
1885
1886         signname(node, dns_fixedname_name(fname));
1887         wevent = (sevent_t *)
1888                  isc_event_allocate(mctx, task, SIGNER_EVENT_WRITE,
1889                                     writenode, NULL, sizeof(sevent_t));
1890         if (wevent == NULL)
1891                 fatal("failed to allocate event\n");
1892         wevent->node = node;
1893         wevent->fname = fname;
1894         isc_task_send(master, ISC_EVENT_PTR(&wevent));
1895 }
1896
1897 /*%
1898  * Update / remove the DS RRset.  Preserve RRSIG(DS) if possible.
1899  */
1900 static void
1901 add_ds(dns_name_t *name, dns_dbnode_t *node, isc_uint32_t nsttl) {
1902         dns_rdataset_t dsset;
1903         dns_rdataset_t sigdsset;
1904         isc_result_t result;
1905
1906         dns_rdataset_init(&dsset);
1907         dns_rdataset_init(&sigdsset);
1908         result = dns_db_findrdataset(gdb, node, gversion,
1909                                      dns_rdatatype_ds,
1910                                      0, 0, &dsset, &sigdsset);
1911         if (result == ISC_R_SUCCESS) {
1912                 dns_rdataset_disassociate(&dsset);
1913                 result = dns_db_deleterdataset(gdb, node, gversion,
1914                                                dns_rdatatype_ds, 0);
1915                 check_result(result, "dns_db_deleterdataset");
1916         }
1917         result = loadds(name, nsttl, &dsset);
1918         if (result == ISC_R_SUCCESS) {
1919                 result = dns_db_addrdataset(gdb, node, gversion, 0,
1920                                             &dsset, 0, NULL);
1921                 check_result(result, "dns_db_addrdataset");
1922                 dns_rdataset_disassociate(&dsset);
1923                 if (dns_rdataset_isassociated(&sigdsset))
1924                         dns_rdataset_disassociate(&sigdsset);
1925         } else if (dns_rdataset_isassociated(&sigdsset)) {
1926                 result = dns_db_deleterdataset(gdb, node, gversion,
1927                                                dns_rdatatype_rrsig,
1928                                                dns_rdatatype_ds);
1929                 check_result(result, "dns_db_deleterdataset");
1930                 dns_rdataset_disassociate(&sigdsset);
1931         }
1932 }
1933
1934 /*%
1935  * Generate NSEC records for the zone and remove NSEC3/NSEC3PARAM records.
1936  */
1937 static void
1938 nsecify(void) {
1939         dns_dbiterator_t *dbiter = NULL;
1940         dns_dbnode_t *node = NULL, *nextnode = NULL;
1941         dns_fixedname_t fname, fnextname, fzonecut;
1942         dns_name_t *name, *nextname, *zonecut;
1943         dns_rdataset_t rdataset;
1944         dns_rdatasetiter_t *rdsiter = NULL;
1945         dns_rdatatype_t type, covers;
1946         isc_boolean_t done = ISC_FALSE;
1947         isc_result_t result;
1948         isc_uint32_t nsttl = 0;
1949
1950         dns_rdataset_init(&rdataset);
1951         dns_fixedname_init(&fname);
1952         name = dns_fixedname_name(&fname);
1953         dns_fixedname_init(&fnextname);
1954         nextname = dns_fixedname_name(&fnextname);
1955         dns_fixedname_init(&fzonecut);
1956         zonecut = NULL;
1957
1958         /*
1959          * Remove any NSEC3 chains.
1960          */
1961         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
1962         check_result(result, "dns_db_createiterator()");
1963         for (result = dns_dbiterator_first(dbiter);
1964              result == ISC_R_SUCCESS;
1965              result = dns_dbiterator_next(dbiter)) {
1966                 result = dns_dbiterator_current(dbiter, &node, name);
1967                 check_dns_dbiterator_current(result);
1968                 result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1969                 check_result(result, "dns_db_allrdatasets()");
1970                 for (result = dns_rdatasetiter_first(rdsiter);
1971                      result == ISC_R_SUCCESS;
1972                      result = dns_rdatasetiter_next(rdsiter)) {
1973                         dns_rdatasetiter_current(rdsiter, &rdataset);
1974                         type = rdataset.type;
1975                         covers = rdataset.covers;
1976                         dns_rdataset_disassociate(&rdataset);
1977                         result = dns_db_deleterdataset(gdb, node, gversion,
1978                                                        type, covers);
1979                         check_result(result,
1980                                      "dns_db_deleterdataset(nsec3param/rrsig)");
1981                 }
1982                 dns_rdatasetiter_destroy(&rdsiter);
1983                 dns_db_detachnode(gdb, &node);
1984         }
1985         dns_dbiterator_destroy(&dbiter);
1986
1987         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
1988         check_result(result, "dns_db_createiterator()");
1989
1990         result = dns_dbiterator_first(dbiter);
1991         check_result(result, "dns_dbiterator_first()");
1992
1993         result = dns_dbiterator_current(dbiter, &node, name);
1994         check_dns_dbiterator_current(result);
1995         /*
1996          * Delete any NSEC3PARAM records at the apex.
1997          */
1998         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
1999         check_result(result, "dns_db_allrdatasets()");
2000         for (result = dns_rdatasetiter_first(rdsiter);
2001              result == ISC_R_SUCCESS;
2002              result = dns_rdatasetiter_next(rdsiter)) {
2003                 dns_rdatasetiter_current(rdsiter, &rdataset);
2004                 type = rdataset.type;
2005                 covers = rdataset.covers;
2006                 dns_rdataset_disassociate(&rdataset);
2007                 if (type == dns_rdatatype_nsec3param ||
2008                     covers == dns_rdatatype_nsec3param) {
2009                         result = dns_db_deleterdataset(gdb, node, gversion,
2010                                                        type, covers);
2011                         check_result(result,
2012                                      "dns_db_deleterdataset(nsec3param/rrsig)");
2013                         continue;
2014                 }
2015         }
2016         dns_rdatasetiter_destroy(&rdsiter);
2017         dns_db_detachnode(gdb, &node);
2018
2019         while (!done) {
2020                 result = dns_dbiterator_current(dbiter, &node, name);
2021                 check_dns_dbiterator_current(result);
2022                 if (delegation(name, node, &nsttl)) {
2023                         zonecut = dns_fixedname_name(&fzonecut);
2024                         dns_name_copy(name, zonecut, NULL);
2025                         if (generateds)
2026                                 add_ds(name, node, nsttl);
2027                 }
2028                 result = dns_dbiterator_next(dbiter);
2029                 nextnode = NULL;
2030                 while (result == ISC_R_SUCCESS) {
2031                         isc_boolean_t active = ISC_FALSE;
2032                         result = dns_dbiterator_current(dbiter, &nextnode,
2033                                                         nextname);
2034                         check_dns_dbiterator_current(result);
2035                         active = active_node(nextnode);
2036                         if (!active) {
2037                                 dns_db_detachnode(gdb, &nextnode);
2038                                 result = dns_dbiterator_next(dbiter);
2039                                 continue;
2040                         }
2041                         if (!dns_name_issubdomain(nextname, gorigin) ||
2042                             (zonecut != NULL &&
2043                              dns_name_issubdomain(nextname, zonecut)))
2044                         {
2045                                 dns_db_detachnode(gdb, &nextnode);
2046                                 result = dns_dbiterator_next(dbiter);
2047                                 continue;
2048                         }
2049                         dns_db_detachnode(gdb, &nextnode);
2050                         break;
2051                 }
2052                 if (result == ISC_R_NOMORE) {
2053                         dns_name_clone(gorigin, nextname);
2054                         done = ISC_TRUE;
2055                 } else if (result != ISC_R_SUCCESS)
2056                         fatal("iterating through the database failed: %s",
2057                               isc_result_totext(result));
2058                 result = dns_nsec_build(gdb, gversion, node, nextname,
2059                                         zonettl);
2060                 check_result(result, "dns_nsec_build()");
2061                 dns_db_detachnode(gdb, &node);
2062         }
2063
2064         dns_dbiterator_destroy(&dbiter);
2065 }
2066
2067 static void
2068 addnsec3param(const unsigned char *salt, size_t salt_length,
2069               unsigned int iterations)
2070 {
2071         dns_dbnode_t *node = NULL;
2072         dns_rdata_nsec3param_t nsec3param;
2073         unsigned char nsec3parambuf[5 + 255];
2074         dns_rdatalist_t rdatalist;
2075         dns_rdataset_t rdataset;
2076         dns_rdata_t rdata = DNS_RDATA_INIT;
2077         isc_buffer_t b;
2078         isc_result_t result;
2079
2080         dns_rdataset_init(&rdataset);
2081
2082         nsec3param.common.rdclass = gclass;
2083         nsec3param.common.rdtype = dns_rdatatype_nsec3param;
2084         ISC_LINK_INIT(&nsec3param.common, link);
2085         nsec3param.mctx = NULL;
2086         nsec3param.flags = 0;
2087         nsec3param.hash = unknownalg ? DNS_NSEC3_UNKNOWNALG : dns_hash_sha1;
2088         nsec3param.iterations = iterations;
2089         nsec3param.salt_length = salt_length;
2090         DE_CONST(salt, nsec3param.salt);
2091
2092         isc_buffer_init(&b, nsec3parambuf, sizeof(nsec3parambuf));
2093         result = dns_rdata_fromstruct(&rdata, gclass,
2094                                       dns_rdatatype_nsec3param,
2095                                       &nsec3param, &b);
2096         rdatalist.rdclass = rdata.rdclass;
2097         rdatalist.type = rdata.type;
2098         rdatalist.covers = 0;
2099         rdatalist.ttl = 0;
2100         ISC_LIST_INIT(rdatalist.rdata);
2101         ISC_LIST_APPEND(rdatalist.rdata, &rdata, link);
2102         result = dns_rdatalist_tordataset(&rdatalist, &rdataset);
2103         check_result(result, "dns_rdatalist_tordataset()");
2104
2105         result = dns_db_findnode(gdb, gorigin, ISC_TRUE, &node);
2106         check_result(result, "dns_db_find(gorigin)");
2107
2108         /*
2109          * Delete any current NSEC3PARAM records.
2110          */
2111         result = dns_db_deleterdataset(gdb, node, gversion,
2112                                        dns_rdatatype_nsec3param, 0);
2113         if (result == DNS_R_UNCHANGED)
2114                 result = ISC_R_SUCCESS;
2115         check_result(result, "dddnsec3param: dns_db_deleterdataset()");
2116
2117         result = dns_db_addrdataset(gdb, node, gversion, 0, &rdataset,
2118                                     DNS_DBADD_MERGE, NULL);
2119         if (result == DNS_R_UNCHANGED)
2120                 result = ISC_R_SUCCESS;
2121         check_result(result, "addnsec3param: dns_db_addrdataset()");
2122         dns_db_detachnode(gdb, &node);
2123 }
2124
2125 static void
2126 addnsec3(dns_name_t *name, dns_dbnode_t *node,
2127          const unsigned char *salt, size_t salt_length,
2128          unsigned int iterations, hashlist_t *hashlist,
2129          dns_ttl_t ttl)
2130 {
2131         unsigned char hash[NSEC3_MAX_HASH_LENGTH];
2132         const unsigned char *nexthash;
2133         unsigned char nsec3buffer[DNS_NSEC3_BUFFERSIZE];
2134         dns_fixedname_t hashname;
2135         dns_rdatalist_t rdatalist;
2136         dns_rdataset_t rdataset;
2137         dns_rdata_t rdata = DNS_RDATA_INIT;
2138         isc_result_t result;
2139         dns_dbnode_t *nsec3node = NULL;
2140         char namebuf[DNS_NAME_FORMATSIZE];
2141         size_t hash_length;
2142
2143         dns_name_format(name, namebuf, sizeof(namebuf));
2144
2145         dns_fixedname_init(&hashname);
2146         dns_rdataset_init(&rdataset);
2147
2148         dns_name_downcase(name, name, NULL);
2149         result = dns_nsec3_hashname(&hashname, hash, &hash_length,
2150                                     name, gorigin, dns_hash_sha1, iterations,
2151                                     salt, salt_length);
2152         check_result(result, "addnsec3: dns_nsec3_hashname()");
2153         nexthash = hashlist_findnext(hashlist, hash);
2154         result = dns_nsec3_buildrdata(gdb, gversion, node,
2155                                       unknownalg ?
2156                                           DNS_NSEC3_UNKNOWNALG : dns_hash_sha1,
2157                                       nsec3flags, iterations,
2158                                       salt, salt_length,
2159                                       nexthash, ISC_SHA1_DIGESTLENGTH,
2160                                       nsec3buffer, &rdata);
2161         check_result(result, "addnsec3: dns_nsec3_buildrdata()");
2162         rdatalist.rdclass = rdata.rdclass;
2163         rdatalist.type = rdata.type;
2164         rdatalist.covers = 0;
2165         rdatalist.ttl = ttl;
2166         ISC_LIST_INIT(rdatalist.rdata);
2167         ISC_LIST_APPEND(rdatalist.rdata, &rdata, link);
2168         result = dns_rdatalist_tordataset(&rdatalist, &rdataset);
2169         check_result(result, "dns_rdatalist_tordataset()");
2170         result = dns_db_findnsec3node(gdb, dns_fixedname_name(&hashname),
2171                                       ISC_TRUE, &nsec3node);
2172         check_result(result, "addnsec3: dns_db_findnode()");
2173         result = dns_db_addrdataset(gdb, nsec3node, gversion, 0, &rdataset,
2174                                     0, NULL);
2175         if (result == DNS_R_UNCHANGED)
2176                 result = ISC_R_SUCCESS;
2177         check_result(result, "addnsec3: dns_db_addrdataset()");
2178         dns_db_detachnode(gdb, &nsec3node);
2179 }
2180
2181 /*%
2182  * Clean out NSEC3 record and RRSIG(NSEC3) that are not in the hash list.
2183  *
2184  * Extract the hash from the first label of 'name' then see if it
2185  * is in hashlist.  If 'name' is not in the hashlist then delete the
2186  * any NSEC3 records which have the same parameters as the chain we
2187  * are building.
2188  *
2189  * XXXMPA Should we also check that it of the form <hash>.<origin>?
2190  */
2191 static void
2192 nsec3clean(dns_name_t *name, dns_dbnode_t *node,
2193            unsigned int hashalg, unsigned int iterations,
2194            const unsigned char *salt, size_t salt_length, hashlist_t *hashlist)
2195 {
2196         dns_label_t label;
2197         dns_rdata_nsec3_t nsec3;
2198         dns_rdata_t rdata, delrdata;
2199         dns_rdatalist_t rdatalist;
2200         dns_rdataset_t rdataset, delrdataset;
2201         isc_boolean_t delete_rrsigs = ISC_FALSE;
2202         isc_buffer_t target;
2203         isc_result_t result;
2204         unsigned char hash[NSEC3_MAX_HASH_LENGTH + 1];
2205         isc_boolean_t exists;
2206
2207         /*
2208          * Get the first label.
2209          */
2210         dns_name_getlabel(name, 0, &label);
2211
2212         /*
2213          * We want just the label contents.
2214          */
2215         isc_region_consume(&label, 1);
2216
2217         /*
2218          * Decode base32hex string.
2219          */
2220         isc_buffer_init(&target, hash, sizeof(hash) - 1);
2221         result = isc_base32hex_decoderegion(&label, &target);
2222         if (result != ISC_R_SUCCESS)
2223                 return;
2224
2225         hash[isc_buffer_usedlength(&target)] = 0;
2226
2227         exists = hashlist_exists(hashlist, hash);
2228
2229         /*
2230          * Verify that the NSEC3 parameters match the current ones
2231          * otherwise we are dealing with a different NSEC3 chain.
2232          */
2233         dns_rdataset_init(&rdataset);
2234         dns_rdataset_init(&delrdataset);
2235
2236         result = dns_db_findrdataset(gdb, node, gversion, dns_rdatatype_nsec3,
2237                                      0, 0, &rdataset, NULL);
2238         if (result != ISC_R_SUCCESS)
2239                 return;
2240
2241         /*
2242          * Delete any NSEC3 records which are not part of the current
2243          * NSEC3 chain.
2244          */
2245         for (result = dns_rdataset_first(&rdataset);
2246              result == ISC_R_SUCCESS;
2247              result = dns_rdataset_next(&rdataset)) {
2248                 dns_rdata_init(&rdata);
2249                 dns_rdataset_current(&rdataset, &rdata);
2250                 result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
2251                 check_result(result, "dns_rdata_tostruct");
2252                 if (exists && nsec3.hash == hashalg &&
2253                     nsec3.iterations == iterations &&
2254                     nsec3.salt_length == salt_length &&
2255                     !memcmp(nsec3.salt, salt, salt_length))
2256                         continue;
2257                 rdatalist.rdclass = rdata.rdclass;
2258                 rdatalist.type = rdata.type;
2259                 rdatalist.covers = 0;
2260                 rdatalist.ttl = rdataset.ttl;
2261                 ISC_LIST_INIT(rdatalist.rdata);
2262                 dns_rdata_init(&delrdata);
2263                 dns_rdata_clone(&rdata, &delrdata);
2264                 ISC_LIST_APPEND(rdatalist.rdata, &delrdata, link);
2265                 result = dns_rdatalist_tordataset(&rdatalist, &delrdataset);
2266                 check_result(result, "dns_rdatalist_tordataset()");
2267                 result = dns_db_subtractrdataset(gdb, node, gversion,
2268                                                  &delrdataset, 0, NULL);
2269                 dns_rdataset_disassociate(&delrdataset);
2270                 if (result != ISC_R_SUCCESS && result != DNS_R_NXRRSET)
2271                         check_result(result, "dns_db_subtractrdataset(NSEC3)");
2272                 delete_rrsigs = ISC_TRUE;
2273         }
2274         dns_rdataset_disassociate(&rdataset);
2275         if (result != ISC_R_NOMORE)
2276                 check_result(result, "dns_rdataset_first/next");
2277
2278         if (!delete_rrsigs)
2279                 return;
2280         /*
2281          * Delete the NSEC3 RRSIGs
2282          */
2283         result = dns_db_deleterdataset(gdb, node, gversion,
2284                                        dns_rdatatype_rrsig,
2285                                        dns_rdatatype_nsec3);
2286         if (result != ISC_R_SUCCESS && result != DNS_R_UNCHANGED)
2287                 check_result(result, "dns_db_deleterdataset(RRSIG(NSEC3))");
2288 }
2289
2290 /*
2291  * Generate NSEC3 records for the zone.
2292  */
2293 static void
2294 nsec3ify(unsigned int hashalg, unsigned int iterations,
2295          const unsigned char *salt, size_t salt_length, hashlist_t *hashlist)
2296 {
2297         dns_dbiterator_t *dbiter = NULL;
2298         dns_dbnode_t *node = NULL, *nextnode = NULL;
2299         dns_fixedname_t fname, fnextname, fzonecut;
2300         dns_name_t *name, *nextname, *zonecut;
2301         dns_rdataset_t rdataset;
2302         dns_rdatasetiter_t *rdsiter = NULL;
2303         dns_rdatatype_t type, covers;
2304         int order;
2305         isc_boolean_t active;
2306         isc_boolean_t done = ISC_FALSE;
2307         isc_result_t result;
2308         isc_uint32_t nsttl = 0;
2309         unsigned int count, nlabels;
2310
2311         dns_rdataset_init(&rdataset);
2312         dns_fixedname_init(&fname);
2313         name = dns_fixedname_name(&fname);
2314         dns_fixedname_init(&fnextname);
2315         nextname = dns_fixedname_name(&fnextname);
2316         dns_fixedname_init(&fzonecut);
2317         zonecut = NULL;
2318
2319         /*
2320          * Walk the zone generating the hash names.
2321          */
2322         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
2323         check_result(result, "dns_db_createiterator()");
2324
2325         result = dns_dbiterator_first(dbiter);
2326         check_result(result, "dns_dbiterator_first()");
2327
2328         result = dns_dbiterator_current(dbiter, &node, name);
2329         check_dns_dbiterator_current(result);
2330         /*
2331          * Delete any NSEC records at the apex.
2332          */
2333         result = dns_db_allrdatasets(gdb, node, gversion, 0, &rdsiter);
2334         check_result(result, "dns_db_allrdatasets()");
2335         for (result = dns_rdatasetiter_first(rdsiter);
2336              result == ISC_R_SUCCESS;
2337              result = dns_rdatasetiter_next(rdsiter)) {
2338                 dns_rdatasetiter_current(rdsiter, &rdataset);
2339                 type = rdataset.type;
2340                 covers = rdataset.covers;
2341                 dns_rdataset_disassociate(&rdataset);
2342                 if (type == dns_rdatatype_nsec ||
2343                     covers == dns_rdatatype_nsec) {
2344                         result = dns_db_deleterdataset(gdb, node, gversion,
2345                                                        type, covers);
2346                         check_result(result,
2347                                      "dns_db_deleterdataset(nsec3param/rrsig)");
2348                         continue;
2349                 }
2350         }
2351         dns_rdatasetiter_destroy(&rdsiter);
2352         dns_db_detachnode(gdb, &node);
2353
2354         while (!done) {
2355                 result = dns_dbiterator_current(dbiter, &node, name);
2356                 check_dns_dbiterator_current(result);
2357                 result = dns_dbiterator_next(dbiter);
2358                 nextnode = NULL;
2359                 while (result == ISC_R_SUCCESS) {
2360                         result = dns_dbiterator_current(dbiter, &nextnode,
2361                                                         nextname);
2362                         check_dns_dbiterator_current(result);
2363                         active = active_node(nextnode);
2364                         if (!active) {
2365                                 dns_db_detachnode(gdb, &nextnode);
2366                                 result = dns_dbiterator_next(dbiter);
2367                                 continue;
2368                         }
2369                         if (!dns_name_issubdomain(nextname, gorigin) ||
2370                             (zonecut != NULL &&
2371                              dns_name_issubdomain(nextname, zonecut))) {
2372                                 dns_db_detachnode(gdb, &nextnode);
2373                                 result = dns_dbiterator_next(dbiter);
2374                                 continue;
2375                         }
2376                         if (delegation(nextname, nextnode, &nsttl)) {
2377                                 zonecut = dns_fixedname_name(&fzonecut);
2378                                 dns_name_copy(nextname, zonecut, NULL);
2379                                 if (generateds)
2380                                         add_ds(nextname, nextnode, nsttl);
2381                                 if (OPTOUT(nsec3flags) &&
2382                                     !secure(nextname, nextnode)) {
2383                                         dns_db_detachnode(gdb, &nextnode);
2384                                         result = dns_dbiterator_next(dbiter);
2385                                         continue;
2386                                 }
2387                         }
2388                         dns_db_detachnode(gdb, &nextnode);
2389                         break;
2390                 }
2391                 if (result == ISC_R_NOMORE) {
2392                         dns_name_copy(gorigin, nextname, NULL);
2393                         done = ISC_TRUE;
2394                 } else if (result != ISC_R_SUCCESS)
2395                         fatal("iterating through the database failed: %s",
2396                               isc_result_totext(result));
2397                 dns_name_downcase(name, name, NULL);
2398                 hashlist_add_dns_name(hashlist, name, hashalg, iterations,
2399                                       salt, salt_length, ISC_FALSE);
2400                 dns_db_detachnode(gdb, &node);
2401                 /*
2402                  * Add hashs for empty nodes.  Use closest encloser logic.
2403                  * The closest encloser either has data or is a empty
2404                  * node for another <name,nextname> span so we don't add
2405                  * it here.  Empty labels on nextname are within the span.
2406                  */
2407                 dns_name_downcase(nextname, nextname, NULL);
2408                 dns_name_fullcompare(name, nextname, &order, &nlabels);
2409                 addnowildcardhash(hashlist, name, hashalg, iterations,
2410                                   salt, salt_length);
2411                 count = dns_name_countlabels(nextname);
2412                 while (count > nlabels + 1) {
2413                         count--;
2414                         dns_name_split(nextname, count, NULL, nextname);
2415                         hashlist_add_dns_name(hashlist, nextname, hashalg,
2416                                               iterations, salt, salt_length,
2417                                               ISC_FALSE);
2418                         addnowildcardhash(hashlist, nextname, hashalg,
2419                                           iterations, salt, salt_length);
2420                 }
2421         }
2422         dns_dbiterator_destroy(&dbiter);
2423
2424         /*
2425          * We have all the hashes now so we can sort them.
2426          */
2427         hashlist_sort(hashlist);
2428
2429         /*
2430          * Check for duplicate hashes.  If found the salt needs to
2431          * be changed.
2432          */
2433         if (hashlist_hasdup(hashlist))
2434                 fatal("Duplicate hash detected. Pick a different salt.");
2435
2436         /*
2437          * Generate the nsec3 records.
2438          */
2439         zonecut = NULL;
2440         done = ISC_FALSE;
2441
2442         addnsec3param(salt, salt_length, iterations);
2443
2444         /*
2445          * Clean out NSEC3 records which don't match this chain.
2446          */
2447         result = dns_db_createiterator(gdb, DNS_DB_NSEC3ONLY, &dbiter);
2448         check_result(result, "dns_db_createiterator()");
2449
2450         for (result = dns_dbiterator_first(dbiter);
2451              result == ISC_R_SUCCESS;
2452              result = dns_dbiterator_next(dbiter)) {
2453                 result = dns_dbiterator_current(dbiter, &node, name);
2454                 check_dns_dbiterator_current(result);
2455                 nsec3clean(name, node, hashalg, iterations, salt, salt_length,
2456                            hashlist);
2457                 dns_db_detachnode(gdb, &node);
2458         }
2459         dns_dbiterator_destroy(&dbiter);
2460
2461         /*
2462          * Generate / complete the new chain.
2463          */
2464         result = dns_db_createiterator(gdb, DNS_DB_NONSEC3, &dbiter);
2465         check_result(result, "dns_db_createiterator()");
2466
2467         result = dns_dbiterator_first(dbiter);
2468         check_result(result, "dns_dbiterator_first()");
2469
2470         while (!done) {
2471                 result = dns_dbiterator_current(dbiter, &node, name);
2472                 check_dns_dbiterator_current(result);
2473                 result = dns_dbiterator_next(dbiter);
2474                 nextnode = NULL;
2475                 while (result == ISC_R_SUCCESS) {
2476                         result = dns_dbiterator_current(dbiter, &nextnode,
2477                                                         nextname);
2478                         check_dns_dbiterator_current(result);
2479                         active = active_node(nextnode);
2480                         if (!active) {
2481                                 dns_db_detachnode(gdb, &nextnode);
2482                                 result = dns_dbiterator_next(dbiter);
2483                                 continue;
2484                         }
2485                         if (!dns_name_issubdomain(nextname, gorigin) ||
2486                             (zonecut != NULL &&
2487                              dns_name_issubdomain(nextname, zonecut))) {
2488                                 dns_db_detachnode(gdb, &nextnode);
2489                                 result = dns_dbiterator_next(dbiter);
2490                                 continue;
2491                         }
2492                         if (delegation(nextname, nextnode, NULL)) {
2493                                 zonecut = dns_fixedname_name(&fzonecut);
2494                                 dns_name_copy(nextname, zonecut, NULL);
2495                                 if (OPTOUT(nsec3flags) &&
2496                                     !secure(nextname, nextnode)) {
2497                                         dns_db_detachnode(gdb, &nextnode);
2498                                         result = dns_dbiterator_next(dbiter);
2499                                         continue;
2500                                 }
2501                         }
2502                         dns_db_detachnode(gdb, &nextnode);
2503                         break;
2504                 }
2505                 if (result == ISC_R_NOMORE) {
2506                         dns_name_copy(gorigin, nextname, NULL);
2507                         done = ISC_TRUE;
2508                 } else if (result != ISC_R_SUCCESS)
2509                         fatal("iterating through the database failed: %s",
2510                               isc_result_totext(result));
2511                 /*
2512                  * We need to pause here to release the lock on the database.
2513                  */
2514                 dns_dbiterator_pause(dbiter);
2515                 addnsec3(name, node, salt, salt_length, iterations,
2516                          hashlist, zonettl);
2517                 dns_db_detachnode(gdb, &node);
2518                 /*
2519                  * Add NSEC3's for empty nodes.  Use closest encloser logic.
2520                  */
2521                 dns_name_fullcompare(name, nextname, &order, &nlabels);
2522                 count = dns_name_countlabels(nextname);
2523                 while (count > nlabels + 1) {
2524                         count--;
2525                         dns_name_split(nextname, count, NULL, nextname);
2526                         addnsec3(nextname, NULL, salt, salt_length,
2527                                  iterations, hashlist, zonettl);
2528                 }
2529         }
2530         dns_dbiterator_destroy(&dbiter);
2531 }
2532
2533 /*%
2534  * Load the zone file from disk
2535  */
2536 static void
2537 loadzone(char *file, char *origin, dns_rdataclass_t rdclass, dns_db_t **db) {
2538         isc_buffer_t b;
2539         int len;
2540         dns_fixedname_t fname;
2541         dns_name_t *name;
2542         isc_result_t result;
2543
2544         len = strlen(origin);
2545         isc_buffer_init(&b, origin, len);
2546         isc_buffer_add(&b, len);
2547
2548         dns_fixedname_init(&fname);
2549         name = dns_fixedname_name(&fname);
2550         result = dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL);
2551         if (result != ISC_R_SUCCESS)
2552                 fatal("failed converting name '%s' to dns format: %s",
2553                       origin, isc_result_totext(result));
2554
2555         result = dns_db_create(mctx, "rbt", name, dns_dbtype_zone,
2556                                rdclass, 0, NULL, db);
2557         check_result(result, "dns_db_create()");
2558
2559         result = dns_db_load2(*db, file, inputformat);
2560         if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE)
2561                 fatal("failed loading zone from '%s': %s",
2562                       file, isc_result_totext(result));
2563 }
2564
2565 /*%
2566  * Finds all public zone keys in the zone, and attempts to load the
2567  * private keys from disk.
2568  */
2569 static void
2570 loadzonekeys(dns_db_t *db) {
2571         dns_dbnode_t *node;
2572         dns_dbversion_t *currentversion;
2573         isc_result_t result;
2574         dst_key_t *keys[20];
2575         unsigned int nkeys, i;
2576
2577         currentversion = NULL;
2578         dns_db_currentversion(db, &currentversion);
2579
2580         node = NULL;
2581         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2582         if (result != ISC_R_SUCCESS)
2583                 fatal("failed to find the zone's origin: %s",
2584                       isc_result_totext(result));
2585
2586         result = dns_dnssec_findzonekeys(db, currentversion, node, gorigin,
2587                                          mctx, 20, keys, &nkeys);
2588         if (result == ISC_R_NOTFOUND)
2589                 result = ISC_R_SUCCESS;
2590         if (result != ISC_R_SUCCESS)
2591                 fatal("failed to find the zone keys: %s",
2592                       isc_result_totext(result));
2593
2594         for (i = 0; i < nkeys; i++) {
2595                 signer_key_t *key;
2596
2597                 key = newkeystruct(keys[i], dst_key_isprivate(keys[i]));
2598                 ISC_LIST_APPEND(keylist, key, link);
2599         }
2600         dns_db_detachnode(db, &node);
2601         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2602 }
2603
2604 /*%
2605  * Finds all public zone keys in the zone.
2606  */
2607 static void
2608 loadzonepubkeys(dns_db_t *db) {
2609         dns_dbversion_t *currentversion = NULL;
2610         dns_dbnode_t *node = NULL;
2611         dns_rdataset_t rdataset;
2612         dns_rdata_t rdata = DNS_RDATA_INIT;
2613         dst_key_t *pubkey;
2614         signer_key_t *key;
2615         isc_result_t result;
2616
2617         dns_db_currentversion(db, &currentversion);
2618
2619         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2620         if (result != ISC_R_SUCCESS)
2621                 fatal("failed to find the zone's origin: %s",
2622                       isc_result_totext(result));
2623
2624         dns_rdataset_init(&rdataset);
2625         result = dns_db_findrdataset(db, node, currentversion,
2626                                      dns_rdatatype_dnskey, 0, 0, &rdataset,
2627                                      NULL);
2628         if (result != ISC_R_SUCCESS)
2629                 fatal("failed to find keys at the zone apex: %s",
2630                       isc_result_totext(result));
2631         result = dns_rdataset_first(&rdataset);
2632         check_result(result, "dns_rdataset_first");
2633         while (result == ISC_R_SUCCESS) {
2634                 pubkey = NULL;
2635                 dns_rdata_reset(&rdata);
2636                 dns_rdataset_current(&rdataset, &rdata);
2637                 result = dns_dnssec_keyfromrdata(gorigin, &rdata, mctx,
2638                                                  &pubkey);
2639                 if (result != ISC_R_SUCCESS)
2640                         goto next;
2641                 if (!dst_key_iszonekey(pubkey)) {
2642                         dst_key_free(&pubkey);
2643                         goto next;
2644                 }
2645
2646                 key = newkeystruct(pubkey, ISC_FALSE);
2647                 ISC_LIST_APPEND(keylist, key, link);
2648  next:
2649                 result = dns_rdataset_next(&rdataset);
2650         }
2651         dns_rdataset_disassociate(&rdataset);
2652         dns_db_detachnode(db, &node);
2653         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2654 }
2655
2656 static void
2657 warnifallksk(dns_db_t *db) {
2658         dns_dbversion_t *currentversion = NULL;
2659         dns_dbnode_t *node = NULL;
2660         dns_rdataset_t rdataset;
2661         dns_rdata_t rdata = DNS_RDATA_INIT;
2662         isc_result_t result;
2663         dns_rdata_dnskey_t dnskey;
2664         isc_boolean_t have_non_ksk = ISC_FALSE;
2665
2666         dns_db_currentversion(db, &currentversion);
2667
2668         result = dns_db_findnode(db, gorigin, ISC_FALSE, &node);
2669         if (result != ISC_R_SUCCESS)
2670                 fatal("failed to find the zone's origin: %s",
2671                       isc_result_totext(result));
2672
2673         dns_rdataset_init(&rdataset);
2674         result = dns_db_findrdataset(db, node, currentversion,
2675                                      dns_rdatatype_dnskey, 0, 0, &rdataset,
2676                                      NULL);
2677         if (result != ISC_R_SUCCESS)
2678                 fatal("failed to find keys at the zone apex: %s",
2679                       isc_result_totext(result));
2680         result = dns_rdataset_first(&rdataset);
2681         check_result(result, "dns_rdataset_first");
2682         while (result == ISC_R_SUCCESS) {
2683                 dns_rdata_reset(&rdata);
2684                 dns_rdataset_current(&rdataset, &rdata);
2685                 result = dns_rdata_tostruct(&rdata, &dnskey, NULL);
2686                 check_result(result, "dns_rdata_tostruct");
2687                 if ((dnskey.flags & DNS_KEYFLAG_KSK) == 0) {
2688                         have_non_ksk = ISC_TRUE;
2689                         result = ISC_R_NOMORE;
2690                 } else
2691                         result = dns_rdataset_next(&rdataset);
2692                 dns_rdata_freestruct(&dnskey);
2693         }
2694         dns_rdataset_disassociate(&rdataset);
2695         dns_db_detachnode(db, &node);
2696         dns_db_closeversion(db, &currentversion, ISC_FALSE);
2697         if (!have_non_ksk && !ignoreksk) {
2698                 if (disable_zone_check)
2699                         fprintf(stderr, "%s: warning: No non-KSK dnskey found. "
2700                                 "Supply non-KSK dnskey or use '-z'.\n",
2701                                 program);
2702                 else
2703                         fatal("No non-KSK dnskey found. "
2704                               "Supply non-KSK dnskey or use '-z'.");
2705         }
2706 }
2707
2708 static void
2709 writeset(const char *prefix, dns_rdatatype_t type) {
2710         char *filename;
2711         char namestr[DNS_NAME_FORMATSIZE];
2712         dns_db_t *db = NULL;
2713         dns_dbversion_t *version = NULL;
2714         dns_diff_t diff;
2715         dns_difftuple_t *tuple = NULL;
2716         dns_fixedname_t fixed;
2717         dns_name_t *name;
2718         dns_rdata_t rdata, ds;
2719         isc_boolean_t have_ksk = ISC_FALSE;
2720         isc_boolean_t have_non_ksk = ISC_FALSE;
2721         isc_buffer_t b;
2722         isc_buffer_t namebuf;
2723         isc_region_t r;
2724         isc_result_t result;
2725         signer_key_t *key;
2726         unsigned char dsbuf[DNS_DS_BUFFERSIZE];
2727         unsigned char keybuf[DST_KEY_MAXSIZE];
2728         unsigned int filenamelen;
2729         const dns_master_style_t *style =
2730                 (type == dns_rdatatype_dnskey) ? masterstyle : dsstyle;
2731
2732         isc_buffer_init(&namebuf, namestr, sizeof(namestr));
2733         result = dns_name_tofilenametext(gorigin, ISC_FALSE, &namebuf);
2734         check_result(result, "dns_name_tofilenametext");
2735         isc_buffer_putuint8(&namebuf, 0);
2736         filenamelen = strlen(prefix) + strlen(namestr);
2737         if (directory != NULL)
2738                 filenamelen += strlen(directory) + 1;
2739         filename = isc_mem_get(mctx, filenamelen + 1);
2740         if (filename == NULL)
2741                 fatal("out of memory");
2742         if (directory != NULL)
2743                 sprintf(filename, "%s/", directory);
2744         else
2745                 filename[0] = 0;
2746         strcat(filename, prefix);
2747         strcat(filename, namestr);
2748
2749         dns_diff_init(mctx, &diff);
2750
2751         for (key = ISC_LIST_HEAD(keylist);
2752              key != NULL;
2753              key = ISC_LIST_NEXT(key, link))
2754                 if (!key->isksk) {
2755                         have_non_ksk = ISC_TRUE;
2756                         break;
2757                 }
2758
2759         for (key = ISC_LIST_HEAD(keylist);
2760              key != NULL;
2761              key = ISC_LIST_NEXT(key, link))
2762                 if (key->isksk) {
2763                         have_ksk = ISC_TRUE;
2764                         break;
2765                 }
2766
2767         if (type == dns_rdatatype_dlv) {
2768                 dns_name_t tname;
2769                 unsigned int labels;
2770
2771                 dns_name_init(&tname, NULL);
2772                 dns_fixedname_init(&fixed);
2773                 name = dns_fixedname_name(&fixed);
2774                 labels = dns_name_countlabels(gorigin);
2775                 dns_name_getlabelsequence(gorigin, 0, labels - 1, &tname);
2776                 result = dns_name_concatenate(&tname, dlv, name, NULL);
2777                 check_result(result, "dns_name_concatenate");
2778         } else
2779                 name = gorigin;
2780
2781         for (key = ISC_LIST_HEAD(keylist);
2782              key != NULL;
2783              key = ISC_LIST_NEXT(key, link))
2784         {
2785                 if (have_ksk && have_non_ksk && !key->isksk)
2786                         continue;
2787                 dns_rdata_init(&rdata);
2788                 dns_rdata_init(&ds);
2789                 isc_buffer_init(&b, keybuf, sizeof(keybuf));
2790                 result = dst_key_todns(key->key, &b);
2791                 check_result(result, "dst_key_todns");
2792                 isc_buffer_usedregion(&b, &r);
2793                 dns_rdata_fromregion(&rdata, gclass, dns_rdatatype_dnskey, &r);
2794                 if (type != dns_rdatatype_dnskey) {
2795                         result = dns_ds_buildrdata(gorigin, &rdata,
2796                                                    DNS_DSDIGEST_SHA1,
2797                                                    dsbuf, &ds);
2798                         check_result(result, "dns_ds_buildrdata");
2799                         if (type == dns_rdatatype_dlv)
2800                                 ds.type = dns_rdatatype_dlv;
2801                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2802                                                       name, 0, &ds, &tuple);
2803                         check_result(result, "dns_difftuple_create");
2804                         dns_diff_append(&diff, &tuple);
2805
2806                         dns_rdata_reset(&ds);
2807                         result = dns_ds_buildrdata(gorigin, &rdata,
2808                                                    DNS_DSDIGEST_SHA256,
2809                                                    dsbuf, &ds);
2810                         check_result(result, "dns_ds_buildrdata");
2811                         if (type == dns_rdatatype_dlv)
2812                                 ds.type = dns_rdatatype_dlv;
2813                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2814                                                       name, 0, &ds, &tuple);
2815
2816                 } else
2817                         result = dns_difftuple_create(mctx, DNS_DIFFOP_ADD,
2818                                                       gorigin, zonettl,
2819                                                       &rdata, &tuple);
2820                 check_result(result, "dns_difftuple_create");
2821                 dns_diff_append(&diff, &tuple);
2822         }
2823
2824         result = dns_db_create(mctx, "rbt", dns_rootname, dns_dbtype_zone,
2825                                gclass, 0, NULL, &db);
2826         check_result(result, "dns_db_create");
2827
2828         result = dns_db_newversion(db, &version);
2829         check_result(result, "dns_db_newversion");
2830
2831         result = dns_diff_apply(&diff, db, version);
2832         check_result(result, "dns_diff_apply");
2833         dns_diff_clear(&diff);
2834
2835         result = dns_master_dump(mctx, db, version, style, filename);
2836         check_result(result, "dns_master_dump");
2837
2838         isc_mem_put(mctx, filename, filenamelen + 1);
2839
2840         dns_db_closeversion(db, &version, ISC_FALSE);
2841         dns_db_detach(&db);
2842 }
2843
2844 static void
2845 print_time(FILE *fp) {
2846         time_t currenttime;
2847
2848         if (outputformat != dns_masterformat_text)
2849                 return;
2850
2851         currenttime = time(NULL);
2852         fprintf(fp, "; File written on %s", ctime(&currenttime));
2853 }
2854
2855 static void
2856 print_version(FILE *fp) {
2857         if (outputformat != dns_masterformat_text)
2858                 return;
2859
2860         fprintf(fp, "; dnssec_signzone version " VERSION "\n");
2861 }
2862
2863 static void
2864 usage(void) {
2865         fprintf(stderr, "Usage:\n");
2866         fprintf(stderr, "\t%s [options] zonefile [keys]\n", program);
2867
2868         fprintf(stderr, "\n");
2869
2870         fprintf(stderr, "Version: %s\n", VERSION);
2871
2872         fprintf(stderr, "Options: (default value in parenthesis) \n");
2873         fprintf(stderr, "\t-c class (IN)\n");
2874         fprintf(stderr, "\t-d directory\n");
2875         fprintf(stderr, "\t\tdirectory to find keyset files (.)\n");
2876         fprintf(stderr, "\t-g:\t");
2877         fprintf(stderr, "generate DS records from keyset files\n");
2878         fprintf(stderr, "\t-s [YYYYMMDDHHMMSS|+offset]:\n");
2879         fprintf(stderr, "\t\tRRSIG start time - absolute|offset "
2880                                 "(now - 1 hour)\n");
2881         fprintf(stderr, "\t-e [YYYYMMDDHHMMSS|+offset|\"now\"+offset]:\n");
2882         fprintf(stderr, "\t\tRRSIG end time  - absolute|from start|from now "
2883                                 "(now + 30 days)\n");
2884         fprintf(stderr, "\t-i interval:\n");
2885         fprintf(stderr, "\t\tcycle interval - resign "
2886                                 "if < interval from end ( (end-start)/4 )\n");
2887         fprintf(stderr, "\t-j jitter:\n");
2888         fprintf(stderr, "\t\trandomize signature end time up to jitter "
2889                                 "seconds\n");
2890         fprintf(stderr, "\t-v debuglevel (0)\n");
2891         fprintf(stderr, "\t-o origin:\n");
2892         fprintf(stderr, "\t\tzone origin (name of zonefile)\n");
2893         fprintf(stderr, "\t-f outfile:\n");
2894         fprintf(stderr, "\t\tfile the signed zone is written in "
2895                                 "(zonefile + .signed)\n");
2896         fprintf(stderr, "\t-I format:\n");
2897         fprintf(stderr, "\t\tfile format of input zonefile (text)\n");
2898         fprintf(stderr, "\t-O format:\n");
2899         fprintf(stderr, "\t\tfile format of signed zone file (text)\n");
2900         fprintf(stderr, "\t-N format:\n");
2901         fprintf(stderr, "\t\tsoa serial format of signed zone file (keep)\n");
2902         fprintf(stderr, "\t-r randomdev:\n");
2903         fprintf(stderr, "\t\ta file containing random data\n");
2904         fprintf(stderr, "\t-a:\t");
2905         fprintf(stderr, "verify generated signatures\n");
2906         fprintf(stderr, "\t-p:\t");
2907         fprintf(stderr, "use pseudorandom data (faster but less secure)\n");
2908         fprintf(stderr, "\t-P:\t");
2909         fprintf(stderr, "disable post-sign verification\n");
2910         fprintf(stderr, "\t-t:\t");
2911         fprintf(stderr, "print statistics\n");
2912         fprintf(stderr, "\t-n ncpus (number of cpus present)\n");
2913         fprintf(stderr, "\t-k key_signing_key\n");
2914         fprintf(stderr, "\t-l lookasidezone\n");
2915         fprintf(stderr, "\t-3 salt (NSEC3 salt)\n");
2916         fprintf(stderr, "\t-H iterations (NSEC3 iterations)\n");
2917         fprintf(stderr, "\t-A (NSEC3 optout)\n");
2918         fprintf(stderr, "\t-z:\t");
2919         fprintf(stderr, "ignore KSK flag in DNSKEYs");
2920
2921         fprintf(stderr, "\n");
2922
2923         fprintf(stderr, "Signing Keys: ");
2924         fprintf(stderr, "(default: all zone keys that have private keys)\n");
2925         fprintf(stderr, "\tkeyfile (Kname+alg+tag)\n");
2926         exit(0);
2927 }
2928
2929 static void
2930 removetempfile(void) {
2931         if (removefile)
2932                 isc_file_remove(tempfile);
2933 }
2934
2935 static void
2936 print_stats(isc_time_t *timer_start, isc_time_t *timer_finish) {
2937         isc_uint64_t runtime_us;   /* Runtime in microseconds */
2938         isc_uint64_t runtime_ms;   /* Runtime in milliseconds */
2939         isc_uint64_t sig_ms;       /* Signatures per millisecond */
2940
2941         runtime_us = isc_time_microdiff(timer_finish, timer_start);
2942
2943         printf("Signatures generated:               %10d\n", nsigned);
2944         printf("Signatures retained:                %10d\n", nretained);
2945         printf("Signatures dropped:                 %10d\n", ndropped);
2946         printf("Signatures successfully verified:   %10d\n", nverified);
2947         printf("Signatures unsuccessfully verified: %10d\n", nverifyfailed);
2948         runtime_ms = runtime_us / 1000;
2949         printf("Runtime in seconds:                %7u.%03u\n",
2950                (unsigned int) (runtime_ms / 1000),
2951                (unsigned int) (runtime_ms % 1000));
2952         if (runtime_us > 0) {
2953                 sig_ms = ((isc_uint64_t)nsigned * 1000000000) / runtime_us;
2954                 printf("Signatures per second:             %7u.%03u\n",
2955                        (unsigned int) sig_ms / 1000,
2956                        (unsigned int) sig_ms % 1000);
2957         }
2958 }
2959
2960 int
2961 main(int argc, char *argv[]) {
2962         int i, ch;
2963         char *startstr = NULL, *endstr = NULL, *classname = NULL;
2964         char *origin = NULL, *file = NULL, *output = NULL;
2965         char *inputformatstr = NULL, *outputformatstr = NULL;
2966         char *serialformatstr = NULL;
2967         char *dskeyfile[MAXDSKEYS];
2968         int ndskeys = 0;
2969         char *endp;
2970         isc_time_t timer_start, timer_finish;
2971         signer_key_t *key;
2972         isc_result_t result;
2973         isc_log_t *log = NULL;
2974         isc_boolean_t pseudorandom = ISC_FALSE;
2975         unsigned int eflags;
2976         isc_boolean_t free_output = ISC_FALSE;
2977         int tempfilelen;
2978         dns_rdataclass_t rdclass;
2979         isc_task_t **tasks = NULL;
2980         isc_buffer_t b;
2981         int len;
2982         unsigned int iterations = 100U;
2983         const unsigned char *salt = NULL;
2984         size_t salt_length = 0;
2985         unsigned char saltbuf[255];
2986         hashlist_t hashlist;
2987
2988 #define CMDLINE_FLAGS "3:aAc:d:e:f:FghH:i:I:j:k:l:m:n:N:o:O:pPr:s:StUv:z"
2989
2990         /*
2991          * Process memory debugging argument first.
2992          */
2993         while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
2994                 switch (ch) {
2995                 case 'm':
2996                         if (strcasecmp(isc_commandline_argument, "record") == 0)
2997                                 isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
2998                         if (strcasecmp(isc_commandline_argument, "trace") == 0)
2999                                 isc_mem_debugging |= ISC_MEM_DEBUGTRACE;
3000                         if (strcasecmp(isc_commandline_argument, "usage") == 0)
3001                                 isc_mem_debugging |= ISC_MEM_DEBUGUSAGE;
3002                         if (strcasecmp(isc_commandline_argument, "size") == 0)
3003                                 isc_mem_debugging |= ISC_MEM_DEBUGSIZE;
3004                         if (strcasecmp(isc_commandline_argument, "mctx") == 0)
3005                                 isc_mem_debugging |= ISC_MEM_DEBUGCTX;
3006                         break;
3007                 default:
3008                         break;
3009                 }
3010         }
3011         isc_commandline_reset = ISC_TRUE;
3012
3013         masterstyle = &dns_master_style_explicitttl;
3014
3015         check_result(isc_app_start(), "isc_app_start");
3016
3017         result = isc_mem_create(0, 0, &mctx);
3018         if (result != ISC_R_SUCCESS)
3019                 fatal("out of memory");
3020
3021         dns_result_register();
3022
3023         isc_commandline_errprint = ISC_FALSE;
3024
3025         while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
3026                 switch (ch) {
3027                 case '3':
3028                         if (strcmp(isc_commandline_argument, "-")) {
3029                                 isc_buffer_t target;
3030                                 char *sarg;
3031
3032                                 sarg = isc_commandline_argument;
3033                                 isc_buffer_init(&target, saltbuf,
3034                                                 sizeof(saltbuf));
3035                                 result = isc_hex_decodestring(sarg, &target);
3036                                 check_result(result,
3037                                              "isc_hex_decodestring(salt)");
3038                                 salt = saltbuf;
3039                                 salt_length = isc_buffer_usedlength(&target);
3040                         } else {
3041                                 salt = saltbuf;
3042                                 salt_length = 0;
3043                         }
3044                         nsec_datatype = dns_rdatatype_nsec3;
3045                         break;
3046
3047                 case 'A':
3048                         nsec3flags |= DNS_NSEC3FLAG_OPTOUT;
3049                         break;
3050
3051                 case 'a':
3052                         tryverify = ISC_TRUE;
3053                         break;
3054
3055                 case 'c':
3056                         classname = isc_commandline_argument;
3057                         break;
3058
3059                 case 'd':
3060                         directory = isc_commandline_argument;
3061                         break;
3062
3063                 case 'e':
3064                         endstr = isc_commandline_argument;
3065                         break;
3066
3067                 case 'f':
3068                         output = isc_commandline_argument;
3069                         break;
3070
3071                 case 'g':
3072                         generateds = ISC_TRUE;
3073                         break;
3074
3075                 case 'H':
3076                         iterations = strtoul(isc_commandline_argument,
3077                                              &endp, 0);
3078                         if (*endp != '\0')
3079                                 fatal("iterations must be numeric");
3080                         if (iterations > 0xffffU)
3081                                 fatal("iterations too big");
3082                         break;
3083
3084                 case 'h':
3085                         usage();
3086                         break;
3087
3088                 case 'i':
3089                         endp = NULL;
3090                         cycle = strtol(isc_commandline_argument, &endp, 0);
3091                         if (*endp != '\0' || cycle < 0)
3092                                 fatal("cycle period must be numeric and "
3093                                       "positive");
3094                         break;
3095
3096                 case 'I':
3097                         inputformatstr = isc_commandline_argument;
3098                         break;
3099
3100                 case 'j':
3101                         endp = NULL;
3102                         jitter = strtol(isc_commandline_argument, &endp, 0);
3103                         if (*endp != '\0' || jitter < 0)
3104                                 fatal("jitter must be numeric and positive");
3105                         break;
3106
3107                 case 'k':
3108                         if (ndskeys == MAXDSKEYS)
3109                                 fatal("too many key-signing keys specified");
3110                         dskeyfile[ndskeys++] = isc_commandline_argument;
3111                         break;
3112
3113                 case 'l':
3114                         len = strlen(isc_commandline_argument);
3115                         isc_buffer_init(&b, isc_commandline_argument, len);
3116                         isc_buffer_add(&b, len);
3117
3118                         dns_fixedname_init(&dlv_fixed);
3119                         dlv = dns_fixedname_name(&dlv_fixed);
3120                         result = dns_name_fromtext(dlv, &b, dns_rootname,
3121                                                    ISC_FALSE, NULL);
3122                         check_result(result, "dns_name_fromtext(dlv)");
3123                         break;
3124
3125                 case 'm':
3126                         break;
3127
3128                 case 'n':
3129                         endp = NULL;
3130                         ntasks = strtol(isc_commandline_argument, &endp, 0);
3131                         if (*endp != '\0' || ntasks > ISC_INT32_MAX)
3132                                 fatal("number of cpus must be numeric");
3133                         break;
3134
3135                 case 'N':
3136                         serialformatstr = isc_commandline_argument;
3137                         break;
3138
3139                 case 'o':
3140                         origin = isc_commandline_argument;
3141                         break;
3142
3143                 case 'O':
3144                         outputformatstr = isc_commandline_argument;
3145                         break;
3146
3147                 case 'p':
3148                         pseudorandom = ISC_TRUE;
3149                         break;
3150
3151                 case 'P':
3152                         disable_zone_check = ISC_TRUE;
3153                         break;
3154
3155                 case 'r':
3156                         setup_entropy(mctx, isc_commandline_argument, &ectx);
3157                         break;
3158
3159                 case 's':
3160                         startstr = isc_commandline_argument;
3161                         break;
3162
3163                 case 'S':
3164                         /* This is intentionally undocumented */
3165                         /* -S: simple output style */
3166                         masterstyle = &dns_master_style_simple;
3167                         break;
3168
3169                 case 't':
3170                         printstats = ISC_TRUE;
3171                         break;
3172
3173                 case 'U':       /* Undocumented for testing only. */
3174                         unknownalg = ISC_TRUE;
3175                         break;
3176
3177                 case 'v':
3178                         endp = NULL;
3179                         verbose = strtol(isc_commandline_argument, &endp, 0);
3180                         if (*endp != '\0')
3181                                 fatal("verbose level must be numeric");
3182                         break;
3183
3184                 case 'z':
3185                         ignoreksk = ISC_TRUE;
3186                         break;
3187
3188                 case 'F':
3189                         /* Reserved for FIPS mode */
3190                         /* FALLTHROUGH */
3191                 case '?':
3192                         if (isc_commandline_option != '?')
3193                                 fprintf(stderr, "%s: invalid argument -%c\n",
3194                                         program, isc_commandline_option);
3195                         usage();
3196                         break;
3197
3198                 default:
3199                         fprintf(stderr, "%s: unhandled option -%c\n",
3200                                 program, isc_commandline_option);
3201                         exit(1);
3202                 }
3203         }
3204
3205         if (ectx == NULL)
3206                 setup_entropy(mctx, NULL, &ectx);
3207         eflags = ISC_ENTROPY_BLOCKING;
3208         if (!pseudorandom)
3209                 eflags |= ISC_ENTROPY_GOODONLY;
3210
3211         result = isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE);
3212         if (result != ISC_R_SUCCESS)
3213                 fatal("could not create hash context");
3214
3215         result = dst_lib_init(mctx, ectx, eflags);
3216         if (result != ISC_R_SUCCESS)
3217                 fatal("could not initialize dst");
3218
3219         isc_stdtime_get(&now);
3220
3221         if (startstr != NULL)
3222                 starttime = strtotime(startstr, now, now);
3223         else
3224                 starttime = now - 3600;  /* Allow for some clock skew. */
3225
3226         if (endstr != NULL)
3227                 endtime = strtotime(endstr, now, starttime);
3228         else
3229                 endtime = starttime + (30 * 24 * 60 * 60);
3230
3231         if (cycle == -1)
3232                 cycle = (endtime - starttime) / 4;
3233
3234         if (ntasks == 0)
3235                 ntasks = isc_os_ncpus() * 2;
3236         vbprintf(4, "using %d cpus\n", ntasks);
3237
3238         rdclass = strtoclass(classname);
3239
3240         setup_logging(verbose, mctx, &log);
3241
3242         argc -= isc_commandline_index;
3243         argv += isc_commandline_index;
3244
3245         if (argc < 1)
3246                 usage();
3247
3248         file = argv[0];
3249
3250         argc -= 1;
3251         argv += 1;
3252
3253         if (origin == NULL)
3254                 origin = file;
3255
3256         if (output == NULL) {
3257                 free_output = ISC_TRUE;
3258                 output = isc_mem_allocate(mctx,
3259                                           strlen(file) + strlen(".signed") + 1);
3260                 if (output == NULL)
3261                         fatal("out of memory");
3262                 sprintf(output, "%s.signed", file);
3263         }
3264
3265         if (inputformatstr != NULL) {
3266                 if (strcasecmp(inputformatstr, "text") == 0)
3267                         inputformat = dns_masterformat_text;
3268                 else if (strcasecmp(inputformatstr, "raw") == 0)
3269                         inputformat = dns_masterformat_raw;
3270                 else
3271                         fatal("unknown file format: %s\n", inputformatstr);
3272         }
3273
3274         if (outputformatstr != NULL) {
3275                 if (strcasecmp(outputformatstr, "text") == 0)
3276                         outputformat = dns_masterformat_text;
3277                 else if (strcasecmp(outputformatstr, "raw") == 0)
3278                         outputformat = dns_masterformat_raw;
3279                 else
3280                         fatal("unknown file format: %s\n", outputformatstr);
3281         }
3282
3283         if (serialformatstr != NULL) {
3284                 if (strcasecmp(serialformatstr, "keep") == 0)
3285                         serialformat = SOA_SERIAL_KEEP;
3286                 else if (strcasecmp(serialformatstr, "increment") == 0 ||
3287                          strcasecmp(serialformatstr, "incr") == 0)
3288                         serialformat = SOA_SERIAL_INCREMENT;
3289                 else if (strcasecmp(serialformatstr, "unixtime") == 0)
3290                         serialformat = SOA_SERIAL_UNIXTIME;
3291                 else
3292                         fatal("unknown soa serial format: %s\n",
3293                               serialformatstr);
3294         }
3295
3296         result = dns_master_stylecreate(&dsstyle,  DNS_STYLEFLAG_NO_TTL,
3297                                         0, 24, 0, 0, 0, 8, mctx);
3298         check_result(result, "dns_master_stylecreate");
3299
3300         gdb = NULL;
3301         TIME_NOW(&timer_start);
3302         loadzone(file, origin, rdclass, &gdb);
3303         gorigin = dns_db_origin(gdb);
3304         gclass = dns_db_class(gdb);
3305         zonettl = soattl();
3306
3307         if (IS_NSEC3) {
3308                 isc_boolean_t answer;
3309                 hash_length = dns_nsec3_hashlength(dns_hash_sha1);
3310                 hashlist_init(&hashlist, dns_db_nodecount(gdb) * 2,
3311                               hash_length);
3312                 result = dns_nsec_nseconly(gdb, gversion, &answer);
3313                 check_result(result, "dns_nsec_nseconly");
3314                 if (answer)
3315                         fatal("NSEC3 generation requested with "
3316                               "NSEC only DNSKEY");
3317         }
3318
3319         /*
3320          * We need to do this early on, as we start messing with the list
3321          * of keys rather early.
3322          */
3323         ISC_LIST_INIT(keylist);
3324         isc_rwlock_init(&keylist_lock, 0, 0);
3325
3326         if (argc == 0) {
3327                 loadzonekeys(gdb);
3328         } else {
3329                 for (i = 0; i < argc; i++) {
3330                         dst_key_t *newkey = NULL;
3331
3332                         result = dst_key_fromnamedfile(argv[i],
3333                                                        DST_TYPE_PUBLIC |
3334                                                        DST_TYPE_PRIVATE,
3335                                                        mctx, &newkey);
3336                         if (result != ISC_R_SUCCESS)
3337                                 fatal("cannot load dnskey %s: %s", argv[i],
3338                                       isc_result_totext(result));
3339
3340                         if (!dns_name_equal(gorigin, dst_key_name(newkey)))
3341                                 fatal("key %s not at origin\n", argv[i]);
3342
3343                         key = ISC_LIST_HEAD(keylist);
3344                         while (key != NULL) {
3345                                 dst_key_t *dkey = key->key;
3346                                 if (dst_key_id(dkey) == dst_key_id(newkey) &&
3347                                     dst_key_alg(dkey) == dst_key_alg(newkey) &&
3348                                     dns_name_equal(dst_key_name(dkey),
3349                                                    dst_key_name(newkey)))
3350                                 {
3351                                         if (!dst_key_isprivate(dkey))
3352                                                 fatal("cannot sign zone with "
3353                                                       "non-private dnskey %s",
3354                                                       argv[i]);
3355                                         break;
3356                                 }
3357                                 key = ISC_LIST_NEXT(key, link);
3358                         }
3359                         if (key == NULL) {
3360                                 key = newkeystruct(newkey, ISC_TRUE);
3361                                 key->commandline = ISC_TRUE;
3362                                 ISC_LIST_APPEND(keylist, key, link);
3363                         } else
3364                                 dst_key_free(&newkey);
3365                 }
3366
3367                 loadzonepubkeys(gdb);
3368         }
3369
3370         for (i = 0; i < ndskeys; i++) {
3371                 dst_key_t *newkey = NULL;
3372
3373                 result = dst_key_fromnamedfile(dskeyfile[i],
3374                                                DST_TYPE_PUBLIC |
3375                                                DST_TYPE_PRIVATE,
3376                                                mctx, &newkey);
3377                 if (result != ISC_R_SUCCESS)
3378                         fatal("cannot load dnskey %s: %s", dskeyfile[i],
3379                               isc_result_totext(result));
3380
3381                 if (!dns_name_equal(gorigin, dst_key_name(newkey)))
3382                         fatal("key %s not at origin\n", dskeyfile[i]);
3383
3384                 key = ISC_LIST_HEAD(keylist);
3385                 while (key != NULL) {
3386                         dst_key_t *dkey = key->key;
3387                         if (dst_key_id(dkey) == dst_key_id(newkey) &&
3388                             dst_key_alg(dkey) == dst_key_alg(newkey) &&
3389                             dns_name_equal(dst_key_name(dkey),
3390                                            dst_key_name(newkey)))
3391                         {
3392                                 /* Override key flags. */
3393                                 key->issigningkey = ISC_TRUE;
3394                                 key->isksk = ISC_TRUE;
3395                                 key->isdsk = ISC_FALSE;
3396                                 dst_key_free(&dkey);
3397                                 key->key = newkey;
3398                                 break;
3399                         }
3400                         key = ISC_LIST_NEXT(key, link);
3401                 }
3402                 if (key == NULL) {
3403                         /* Override dnskey flags. */
3404                         key = newkeystruct(newkey, ISC_TRUE);
3405                         key->isksk = ISC_TRUE;
3406                         key->isdsk = ISC_FALSE;
3407                         ISC_LIST_APPEND(keylist, key, link);
3408                 }
3409         }
3410
3411         if (ISC_LIST_EMPTY(keylist)) {
3412                 if (disable_zone_check)
3413                         fprintf(stderr, "%s: warning: No keys specified "
3414                                 "or found\n", program);
3415                 else
3416                         fatal("No signing keys specified or found.");
3417                 nokeys = ISC_TRUE;
3418         }
3419
3420         if (IS_NSEC3) {
3421                 unsigned int max;
3422                 result = dns_nsec3_maxiterations(gdb, NULL, mctx, &max);
3423                 check_result(result, "dns_nsec3_maxiterations()");
3424                 if (iterations > max)
3425                         fatal("NSEC3 iterations too big for weakest DNSKEY "
3426                               "strength. Maximum iterations allowed %u.", max);
3427         }
3428
3429         warnifallksk(gdb);
3430
3431         gversion = NULL;
3432         result = dns_db_newversion(gdb, &gversion);
3433         check_result(result, "dns_db_newversion()");
3434
3435         switch (serialformat) {
3436                 case SOA_SERIAL_INCREMENT:
3437                         setsoaserial(0);
3438                         break;
3439                 case SOA_SERIAL_UNIXTIME:
3440                         setsoaserial(now);
3441                         break;
3442                 case SOA_SERIAL_KEEP:
3443                 default:
3444                         /* do nothing */
3445                         break;
3446         }
3447
3448         if (IS_NSEC3)
3449                 nsec3ify(dns_hash_sha1, iterations, salt, salt_length,
3450                          &hashlist);
3451         else
3452                 nsecify();
3453
3454         if (!nokeys) {
3455                 writeset("keyset-", dns_rdatatype_dnskey);
3456                 writeset("dsset-", dns_rdatatype_ds);
3457                 if (dlv != NULL) {
3458                         writeset("dlvset-", dns_rdatatype_dlv);
3459                 }
3460         }
3461
3462         tempfilelen = strlen(output) + 20;
3463         tempfile = isc_mem_get(mctx, tempfilelen);
3464         if (tempfile == NULL)
3465                 fatal("out of memory");
3466
3467         result = isc_file_mktemplate(output, tempfile, tempfilelen);
3468         check_result(result, "isc_file_mktemplate");
3469
3470         fp = NULL;
3471         result = isc_file_openunique(tempfile, &fp);
3472         if (result != ISC_R_SUCCESS)
3473                 fatal("failed to open temporary output file: %s",
3474                       isc_result_totext(result));
3475         removefile = ISC_TRUE;
3476         setfatalcallback(&removetempfile);
3477
3478         print_time(fp);
3479         print_version(fp);
3480
3481         result = isc_taskmgr_create(mctx, ntasks, 0, &taskmgr);
3482         if (result != ISC_R_SUCCESS)
3483                 fatal("failed to create task manager: %s",
3484                       isc_result_totext(result));
3485
3486         master = NULL;
3487         result = isc_task_create(taskmgr, 0, &master);
3488         if (result != ISC_R_SUCCESS)
3489                 fatal("failed to create task: %s", isc_result_totext(result));
3490
3491         tasks = isc_mem_get(mctx, ntasks * sizeof(isc_task_t *));
3492         if (tasks == NULL)
3493                 fatal("out of memory");
3494         for (i = 0; i < (int)ntasks; i++) {
3495                 tasks[i] = NULL;
3496                 result = isc_task_create(taskmgr, 0, &tasks[i]);
3497                 if (result != ISC_R_SUCCESS)
3498                         fatal("failed to create task: %s",
3499                               isc_result_totext(result));
3500         }
3501
3502         RUNTIME_CHECK(isc_mutex_init(&namelock) == ISC_R_SUCCESS);
3503         if (printstats)
3504                 RUNTIME_CHECK(isc_mutex_init(&statslock) == ISC_R_SUCCESS);
3505
3506         presign();
3507         signapex();
3508         if (!finished) {
3509                 /*
3510                  * There is more work to do.  Spread it out over multiple
3511                  * processors if possible.
3512                  */
3513                 for (i = 0; i < (int)ntasks; i++) {
3514                         result = isc_app_onrun(mctx, master, startworker,
3515                                                tasks[i]);
3516                         if (result != ISC_R_SUCCESS)
3517                                 fatal("failed to start task: %s",
3518                                       isc_result_totext(result));
3519                 }
3520                 (void)isc_app_run();
3521                 if (!finished)
3522                         fatal("process aborted by user");
3523         } else
3524                 isc_task_detach(&master);
3525         shuttingdown = ISC_TRUE;
3526         for (i = 0; i < (int)ntasks; i++)
3527                 isc_task_detach(&tasks[i]);
3528         isc_taskmgr_destroy(&taskmgr);
3529         isc_mem_put(mctx, tasks, ntasks * sizeof(isc_task_t *));
3530         postsign();
3531         verifyzone();
3532
3533         if (outputformat != dns_masterformat_text) {
3534                 result = dns_master_dumptostream2(mctx, gdb, gversion,
3535                                                   masterstyle, outputformat,
3536                                                   fp);
3537                 check_result(result, "dns_master_dumptostream2");
3538         }
3539
3540         result = isc_stdio_close(fp);
3541         check_result(result, "isc_stdio_close");
3542         removefile = ISC_FALSE;
3543
3544         result = isc_file_rename(tempfile, output);
3545         if (result != ISC_R_SUCCESS)
3546                 fatal("failed to rename temp file to %s: %s\n",
3547                       output, isc_result_totext(result));
3548
3549         DESTROYLOCK(&namelock);
3550         if (printstats)
3551                 DESTROYLOCK(&statslock);
3552
3553         printf("%s\n", output);
3554
3555         dns_db_closeversion(gdb, &gversion, ISC_FALSE);
3556         dns_db_detach(&gdb);
3557
3558         while (!ISC_LIST_EMPTY(keylist)) {
3559                 key = ISC_LIST_HEAD(keylist);
3560                 ISC_LIST_UNLINK(keylist, key, link);
3561                 dst_key_free(&key->key);
3562                 isc_mem_put(mctx, key, sizeof(signer_key_t));
3563         }
3564
3565         isc_mem_put(mctx, tempfile, tempfilelen);
3566
3567         if (free_output)
3568                 isc_mem_free(mctx, output);
3569
3570         dns_master_styledestroy(&dsstyle, mctx);
3571
3572         cleanup_logging(&log);
3573         dst_lib_destroy();
3574         isc_hash_destroy();
3575         cleanup_entropy(&ectx);
3576         dns_name_destroy();
3577         if (verbose > 10)
3578                 isc_mem_stats(mctx, stdout);
3579         isc_mem_destroy(&mctx);
3580
3581         (void) isc_app_finish();
3582
3583         if (printstats) {
3584                 TIME_NOW(&timer_finish);
3585                 print_stats(&timer_start, &timer_finish);
3586         }
3587
3588         return (0);
3589 }