dnssectool.c 51.9 KB
Newer Older
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4 5 6
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 8 9
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
10 11
 */

12 13 14 15 16
/*! \file */

/*%
 * DNSSEC Support Routines.
 */
David Lawrence's avatar
David Lawrence committed
17

18 19 20 21
#include <config.h>

#include <stdlib.h>

22 23 24 25
#ifdef _WIN32
#include <Winsock2.h>
#endif

26
#include <isc/base32.h>
27
#include <isc/buffer.h>
28
#include <isc/commandline.h>
29
#include <isc/dir.h>
30
#include <isc/file.h>
31
#include <isc/heap.h>
32 33
#include <isc/list.h>
#include <isc/mem.h>
Evan Hunt's avatar
Evan Hunt committed
34
#include <isc/platform.h>
35
#include <isc/print.h>
36
#include <isc/string.h>
37
#include <isc/time.h>
38 39
#include <isc/util.h>

40 41
#include <dns/db.h>
#include <dns/dbiterator.h>
42
#include <dns/dnssec.h>
43
#include <dns/fixedname.h>
44
#include <dns/keyvalues.h>
45 46
#include <dns/log.h>
#include <dns/name.h>
47 48
#include <dns/nsec.h>
#include <dns/nsec3.h>
49
#include <dns/rdatastruct.h>
50
#include <dns/rdataclass.h>
51 52
#include <dns/rdataset.h>
#include <dns/rdatasetiter.h>
53 54 55
#include <dns/rdatatype.h>
#include <dns/result.h>
#include <dns/secalg.h>
56
#include <dns/time.h>
57 58 59

#include "dnssectool.h"

60 61 62 63 64 65 66 67 68 69 70 71
static isc_heap_t *expected_chains, *found_chains;

struct nsec3_chain_fixed {
	isc_uint8_t	hash;
	isc_uint8_t	salt_length;
	isc_uint8_t	next_length;
	isc_uint16_t	iterations;
	/* unsigned char salt[0]; */
	/* unsigned char owner[0]; */
	/* unsigned char next[0]; */
};

72
extern int verbose;
David Lawrence's avatar
David Lawrence committed
73
extern const char *program;
74

75
static fatalcallback_t *fatalcallback = NULL;
76

77
void
David Lawrence's avatar
David Lawrence committed
78
fatal(const char *format, ...) {
79 80
	va_list args;

81
	fprintf(stderr, "%s: fatal: ", program);
82 83 84 85
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	fprintf(stderr, "\n");
86 87
	if (fatalcallback != NULL)
		(*fatalcallback)();
88 89 90
	exit(1);
}

91 92 93 94 95
void
setfatalcallback(fatalcallback_t *callback) {
	fatalcallback = callback;
}

96
void
David Lawrence's avatar
David Lawrence committed
97
check_result(isc_result_t result, const char *message) {
98 99
	if (result != ISC_R_SUCCESS)
		fatal("%s: %s", message, isc_result_totext(result));
100 101 102 103 104 105 106 107 108 109 110 111 112
}

void
vbprintf(int level, const char *fmt, ...) {
	va_list ap;
	if (level > verbose)
		return;
	va_start(ap, fmt);
	fprintf(stderr, "%s: ", program);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
}

113
void
114 115
version(const char *name) {
	fprintf(stderr, "%s %s\n", name, VERSION);
116 117 118
	exit(0);
}

119 120
void
type_format(const dns_rdatatype_t type, char *cp, unsigned int size) {
121 122 123 124
	isc_buffer_t b;
	isc_region_t r;
	isc_result_t result;

125
	isc_buffer_init(&b, cp, size - 1);
126 127 128 129 130 131
	result = dns_rdatatype_totext(type, &b);
	check_result(result, "dns_rdatatype_totext()");
	isc_buffer_usedregion(&b, &r);
	r.base[r.length] = 0;
}

132
void
133
sig_format(dns_rdata_rrsig_t *sig, char *cp, unsigned int size) {
134 135
	char namestr[DNS_NAME_FORMATSIZE];
	char algstr[DNS_NAME_FORMATSIZE];
136

Andreas Gustafsson's avatar
Andreas Gustafsson committed
137
	dns_name_format(&sig->signer, namestr, sizeof(namestr));
138
	dns_secalg_format(sig->algorithm, algstr, sizeof(algstr));
139 140
	snprintf(cp, size, "%s/%s/%d", namestr, algstr, sig->keyid);
}
141

142
void
143
setup_logging(isc_mem_t *mctx, isc_log_t **logp) {
144 145
	isc_result_t result;
	isc_logdestination_t destination;
Andreas Gustafsson's avatar
Andreas Gustafsson committed
146 147
	isc_logconfig_t *logconfig = NULL;
	isc_log_t *log = NULL;
148 149
	int level;

150 151
	if (verbose < 0)
		verbose = 0;
152
	switch (verbose) {
Brian Wellington's avatar
Brian Wellington committed
153 154
	case 0:
		/*
155 156 157 158 159 160 161 162 163 164 165 166
		 * We want to see warnings about things like out-of-zone
		 * data in the master file even when not verbose.
		 */
		level = ISC_LOG_WARNING;
		break;
	case 1:
		level = ISC_LOG_INFO;
		break;
	default:
		level = ISC_LOG_DEBUG(verbose - 2 + 1);
		break;
	}
167

168 169 170 171 172
	RUNTIME_CHECK(isc_log_create(mctx, &log, &logconfig) == ISC_R_SUCCESS);
	isc_log_setcontext(log);
	dns_log_init(log);
	dns_log_setcontext(log);

David Lawrence's avatar
David Lawrence committed
173 174
	RUNTIME_CHECK(isc_log_settag(logconfig, program) == ISC_R_SUCCESS);

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	/*
	 * Set up a channel similar to default_stderr except:
	 *  - the logging level is passed in
	 *  - the program name and logging level are printed
	 *  - no time stamp is printed
	 */
	destination.file.stream = stderr;
	destination.file.name = NULL;
	destination.file.versions = ISC_LOG_ROLLNEVER;
	destination.file.maximum_size = 0;
	result = isc_log_createchannel(logconfig, "stderr",
				       ISC_LOG_TOFILEDESC,
				       level,
				       &destination,
				       ISC_LOG_PRINTTAG|ISC_LOG_PRINTLEVEL);
	check_result(result, "isc_log_createchannel()");
191

192 193 194 195 196 197
	RUNTIME_CHECK(isc_log_usechannel(logconfig, "stderr",
					 NULL, NULL) == ISC_R_SUCCESS);

	*logp = log;
}

Brian Wellington's avatar
Brian Wellington committed
198 199 200 201 202 203 204
void
cleanup_logging(isc_log_t **logp) {
	isc_log_t *log;

	REQUIRE(logp != NULL);

	log = *logp;
Mark Andrews's avatar
Mark Andrews committed
205 206
	*logp = NULL;

Brian Wellington's avatar
Brian Wellington committed
207 208
	if (log == NULL)
		return;
Mark Andrews's avatar
Mark Andrews committed
209

Brian Wellington's avatar
Brian Wellington committed
210 211 212 213 214
	isc_log_destroy(&log);
	isc_log_setcontext(NULL);
	dns_log_setcontext(NULL);
}

Automatic Updater's avatar
Automatic Updater committed
215
static isc_stdtime_t
216 217
time_units(isc_stdtime_t offset, char *suffix, const char *str) {
	switch (suffix[0]) {
218 219 220
	    case 'Y': case 'y':
		return (offset * (365 * 24 * 3600));
	    case 'M': case 'm':
221 222 223 224 225 226 227 228 229 230 231
		switch (suffix[1]) {
		    case 'O': case 'o':
			return (offset * (30 * 24 * 3600));
		    case 'I': case 'i':
			return (offset * 60);
		    case '\0':
			fatal("'%s' ambiguous: use 'mi' for minutes "
			      "or 'mo' for months", str);
		    default:
			fatal("time value %s is invalid", str);
		}
Evan Hunt's avatar
Evan Hunt committed
232
		/* NOTREACHED */
233
		break;
234 235 236 237 238 239 240 241 242 243 244
	    case 'W': case 'w':
		return (offset * (7 * 24 * 3600));
	    case 'D': case 'd':
		return (offset * (24 * 3600));
	    case 'H': case 'h':
		return (offset * 3600);
	    case 'S': case 's': case '\0':
		return (offset);
	    default:
		fatal("time value %s is invalid", str);
	}
Evan Hunt's avatar
Evan Hunt committed
245
	/* NOTREACHED */
246 247 248
	return(0); /* silence compiler warning */
}

Evan Hunt's avatar
Evan Hunt committed
249 250 251 252 253 254
static inline isc_boolean_t
isnone(const char *str) {
	return (ISC_TF((strcasecmp(str, "none") == 0) ||
		       (strcasecmp(str, "never") == 0)));
}

255 256 257 258 259 260
dns_ttl_t
strtottl(const char *str) {
	const char *orig = str;
	dns_ttl_t ttl;
	char *endp;

Evan Hunt's avatar
Evan Hunt committed
261 262 263
	if (isnone(str))
		return ((dns_ttl_t) 0);

264
	ttl = strtol(str, &endp, 0);
Automatic Updater's avatar
Automatic Updater committed
265 266
	if (ttl == 0 && endp == str)
		fatal("TTL must be numeric");
267 268 269 270
	ttl = time_units(ttl, endp, orig);
	return (ttl);
}

271
isc_stdtime_t
Evan Hunt's avatar
Evan Hunt committed
272 273 274
strtotime(const char *str, isc_int64_t now, isc_int64_t base,
	  isc_boolean_t *setp)
{
275 276
	isc_int64_t val, offset;
	isc_result_t result;
277
	const char *orig = str;
278
	char *endp;
279
	size_t n;
280

Evan Hunt's avatar
Evan Hunt committed
281 282 283 284 285 286 287 288 289
	if (isnone(str)) {
		if (setp != NULL)
			*setp = ISC_FALSE;
		return ((isc_stdtime_t) 0);
	}

	if (setp != NULL)
		*setp = ISC_TRUE;

Mark Andrews's avatar
Mark Andrews committed
290
	if ((str[0] == '0' || str[0] == '-') && str[1] == '\0')
291 292
		return ((isc_stdtime_t) 0);

293 294 295 296 297 298 299 300
	/*
	 * We accept times in the following formats:
	 *   now([+-]offset)
	 *   YYYYMMDD([+-]offset)
	 *   YYYYMMDDhhmmss([+-]offset)
	 *   [+-]offset
	 */
	n = strspn(str, "0123456789");
Mark Andrews's avatar
Mark Andrews committed
301
	if ((n == 8u || n == 14u) &&
302 303 304 305 306 307
	    (str[n] == '\0' || str[n] == '-' || str[n] == '+'))
	{
		char timestr[15];

		strlcpy(timestr, str, sizeof(timestr));
		timestr[n] = 0;
Mark Andrews's avatar
Mark Andrews committed
308
		if (n == 8u)
309 310 311 312 313 314 315 316
			strlcat(timestr, "000000", sizeof(timestr));
		result = dns_time64_fromtext(timestr, &val);
		if (result != ISC_R_SUCCESS)
			fatal("time value %s is invalid: %s", orig,
			      isc_result_totext(result));
		base = val;
		str += n;
	} else if (strncmp(str, "now", 3) == 0) {
317 318 319 320 321 322 323
		base = now;
		str += 3;
	}

	if (str[0] == '\0')
		return ((isc_stdtime_t) base);
	else if (str[0] == '+') {
324
		offset = strtol(str + 1, &endp, 0);
Evan Hunt's avatar
Evan Hunt committed
325
		offset = time_units((isc_stdtime_t) offset, endp, orig);
326
		val = base + offset;
327 328
	} else if (str[0] == '-') {
		offset = strtol(str + 1, &endp, 0);
Evan Hunt's avatar
Evan Hunt committed
329
		offset = time_units((isc_stdtime_t) offset, endp, orig);
330
		val = base - offset;
331 332
	} else
		fatal("time value %s is invalid", orig);
333 334 335

	return ((isc_stdtime_t) val);
}
336 337 338

dns_rdataclass_t
strtoclass(const char *str) {
Mark Andrews's avatar
Mark Andrews committed
339
	isc_textregion_t r;
340 341 342 343 344
	dns_rdataclass_t rdclass;
	isc_result_t ret;

	if (str == NULL)
		return dns_rdataclass_in;
Mark Andrews's avatar
Mark Andrews committed
345
	DE_CONST(str, r.base);
346
	r.length = strlen(str);
Mark Andrews's avatar
Mark Andrews committed
347
	ret = dns_rdataclass_fromtext(&rdclass, &r);
348 349 350 351
	if (ret != ISC_R_SUCCESS)
		fatal("unknown class %s", str);
	return (rdclass);
}
352

Evan Hunt's avatar
Evan Hunt committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
unsigned int
strtodsdigest(const char *algname) {
	if (strcasecmp(algname, "SHA1") == 0 ||
	    strcasecmp(algname, "SHA-1") == 0)
	{
		return (DNS_DSDIGEST_SHA1);
	} else if (strcasecmp(algname, "SHA256") == 0 ||
		   strcasecmp(algname, "SHA-256") == 0)
	{
		return (DNS_DSDIGEST_SHA256);
#if defined(HAVE_OPENSSL_GOST) || defined(HAVE_PKCS11_GOST)
	} else if (strcasecmp(algname, "GOST") == 0) {
		return (DNS_DSDIGEST_GOST);
#endif
	} else if (strcasecmp(algname, "SHA384") == 0 ||
		   strcasecmp(algname, "SHA-384") == 0)
	{
		return (DNS_DSDIGEST_SHA384);
	} else {
		fatal("unknown algorithm %s", algname);
	}
}

376 377 378 379 380 381 382 383 384 385 386 387
isc_result_t
try_dir(const char *dirname) {
	isc_result_t result;
	isc_dir_t d;

	isc_dir_init(&d);
	result = isc_dir_open(&d, dirname);
	if (result == ISC_R_SUCCESS) {
		isc_dir_close(&d);
	}
	return (result);
}
388 389 390 391 392 393 394 395

/*
 * Check private key version compatibility.
 */
void
check_keyversion(dst_key_t *key, char *keystr) {
	int major, minor;
	dst_key_getprivateformat(key, &major, &minor);
Automatic Updater's avatar
Automatic Updater committed
396
	INSIST(major <= DST_MAJOR_VERSION); /* invalid private key */
397

Automatic Updater's avatar
Automatic Updater committed
398
	if (major < DST_MAJOR_VERSION || minor < DST_MINOR_VERSION)
399 400 401 402 403 404 405 406 407 408 409 410 411
		fatal("Key %s has incompatible format version %d.%d, "
		      "use -f to force upgrade to new version.",
		      keystr, major, minor);
	if (minor > DST_MINOR_VERSION)
		fatal("Key %s has incompatible format version %d.%d, "
		      "use -f to force downgrade to current version.",
		      keystr, major, minor);
}

void
set_keyversion(dst_key_t *key) {
	int major, minor;
	dst_key_getprivateformat(key, &major, &minor);
Automatic Updater's avatar
Automatic Updater committed
412
	INSIST(major <= DST_MAJOR_VERSION);
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

	if (major != DST_MAJOR_VERSION || minor != DST_MINOR_VERSION)
		dst_key_setprivateformat(key, DST_MAJOR_VERSION,
					 DST_MINOR_VERSION);

	/*
	 * If the key is from a version older than 1.3, set
	 * set the creation date
	 */
	if (major < 1 || (major == 1 && minor <= 2)) {
		isc_stdtime_t now;
		isc_stdtime_get(&now);
		dst_key_settime(key, DST_TIME_CREATED, now);
	}
}
428 429

isc_boolean_t
430 431
key_collision(dst_key_t *dstkey, dns_name_t *name, const char *dir,
	      isc_mem_t *mctx, isc_boolean_t *exact)
432 433 434 435 436
{
	isc_result_t result;
	isc_boolean_t conflict = ISC_FALSE;
	dns_dnsseckeylist_t matchkeys;
	dns_dnsseckey_t *key = NULL;
437
	isc_uint16_t id, oldid;
438 439
	isc_uint32_t rid, roldid;
	dns_secalg_t alg;
440 441
	char filename[ISC_DIR_NAMEMAX];
	isc_buffer_t fileb;
442
	isc_stdtime_t now;
443 444 445

	if (exact != NULL)
		*exact = ISC_FALSE;
Automatic Updater's avatar
Automatic Updater committed
446

447 448 449
	id = dst_key_id(dstkey);
	rid = dst_key_rid(dstkey);
	alg = dst_key_alg(dstkey);
450

451
	/*
452 453 454
	 * For Diffie Hellman just check if there is a direct collision as
	 * they can't be revoked.  Additionally dns_dnssec_findmatchingkeys
	 * only handles DNSKEY which is not used for HMAC.
455
	 */
456
	if (alg == DST_ALG_DH) {
457 458 459 460 461 462 463 464
		isc_buffer_init(&fileb, filename, sizeof(filename));
		result = dst_key_buildfilename(dstkey, DST_TYPE_PRIVATE,
					       dir, &fileb);
		if (result != ISC_R_SUCCESS)
			return (ISC_TRUE);
		return (isc_file_exists(filename));
	}

465
	ISC_LIST_INIT(matchkeys);
466 467
	isc_stdtime_get(&now);
	result = dns_dnssec_findmatchingkeys(name, dir, now, mctx, &matchkeys);
468 469 470 471 472 473 474 475 476
	if (result == ISC_R_NOTFOUND)
		return (ISC_FALSE);

	while (!ISC_LIST_EMPTY(matchkeys) && !conflict) {
		key = ISC_LIST_HEAD(matchkeys);
		if (dst_key_alg(key->key) != alg)
			goto next;

		oldid = dst_key_id(key->key);
477 478 479
		roldid = dst_key_rid(key->key);

		if (oldid == rid || roldid == id || id == oldid) {
480
			conflict = ISC_TRUE;
481
			if (id != oldid) {
482
				if (verbose > 1)
Automatic Updater's avatar
Automatic Updater committed
483
					fprintf(stderr, "Key ID %d could "
484 485 486 487 488 489
						"collide with %d\n",
						id, oldid);
			} else {
				if (exact != NULL)
					*exact = ISC_TRUE;
				if (verbose > 1)
Automatic Updater's avatar
Automatic Updater committed
490
					fprintf(stderr, "Key ID %d exists\n",
491
						id);
Automatic Updater's avatar
Automatic Updater committed
492
			}
493 494 495 496 497 498 499
		}

 next:
		ISC_LIST_UNLINK(matchkeys, key, link);
		dns_dnsseckey_destroy(mctx, &key);
	}

Automatic Updater's avatar
Automatic Updater committed
500
	/* Finish freeing the list */
501 502 503 504 505 506 507 508
	while (!ISC_LIST_EMPTY(matchkeys)) {
		key = ISC_LIST_HEAD(matchkeys);
		ISC_LIST_UNLINK(matchkeys, key, link);
		dns_dnsseckey_destroy(mctx, &key);
	}

	return (conflict);
}
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540

isc_boolean_t
is_delegation(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	      dns_name_t *name, dns_dbnode_t *node, isc_uint32_t *ttlp)
{
	dns_rdataset_t nsset;
	isc_result_t result;

	if (dns_name_equal(name, origin))
		return (ISC_FALSE);

	dns_rdataset_init(&nsset);
	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_ns,
				     0, 0, &nsset, NULL);
	if (dns_rdataset_isassociated(&nsset)) {
		if (ttlp != NULL)
			*ttlp = nsset.ttl;
		dns_rdataset_disassociate(&nsset);
	}

	return (ISC_TF(result == ISC_R_SUCCESS));
}

static isc_boolean_t
goodsig(dns_name_t *origin, dns_rdata_t *sigrdata, dns_name_t *name,
	dns_rdataset_t *keyrdataset, dns_rdataset_t *rdataset, isc_mem_t *mctx)
{
	dns_rdata_dnskey_t key;
	dns_rdata_rrsig_t sig;
	dst_key_t *dstkey = NULL;
	isc_result_t result;

541 542
	result = dns_rdata_tostruct(sigrdata, &sig, NULL);
	check_result(result, "dns_rdata_tostruct()");
543 544 545 546 547 548

	for (result = dns_rdataset_first(keyrdataset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(keyrdataset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;
		dns_rdataset_current(keyrdataset, &rdata);
549 550
		result = dns_rdata_tostruct(&rdata, &key, NULL);
		check_result(result, "dns_rdata_tostruct()");
551 552 553 554 555 556 557 558 559 560 561
		result = dns_dnssec_keyfromrdata(origin, &rdata, mctx,
						 &dstkey);
		if (result != ISC_R_SUCCESS)
			return (ISC_FALSE);
		if (sig.algorithm != key.algorithm ||
		    sig.keyid != dst_key_id(dstkey) ||
		    !dns_name_equal(&sig.signer, origin)) {
			dst_key_free(&dstkey);
			continue;
		}
		result = dns_dnssec_verify(name, rdataset, dstkey, ISC_FALSE,
562
					   0, mctx, sigrdata, NULL);
563
		dst_key_free(&dstkey);
564
		if (result == ISC_R_SUCCESS || result == DNS_R_FROMWILDCARD) {
565
			return(ISC_TRUE);
566
		}
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
	}
	return (ISC_FALSE);
}

static isc_result_t
verifynsec(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
	   dns_dbnode_t *node, dns_name_t *nextname)
{
	unsigned char buffer[DNS_NSEC_BUFFERSIZE];
	char namebuf[DNS_NAME_FORMATSIZE];
	char nextbuf[DNS_NAME_FORMATSIZE];
	char found[DNS_NAME_FORMATSIZE];
	dns_rdataset_t rdataset;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dns_rdata_t tmprdata = DNS_RDATA_INIT;
	dns_rdata_nsec_t nsec;
	isc_result_t result;

	dns_rdataset_init(&rdataset);
	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec,
				     0, 0, &rdataset, NULL);
	if (result != ISC_R_SUCCESS) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		fprintf(stderr, "Missing NSEC record for %s\n", namebuf);
		goto failure;
	}

	result = dns_rdataset_first(&rdataset);
	check_result(result, "dns_rdataset_first()");

	dns_rdataset_current(&rdataset, &rdata);
	result = dns_rdata_tostruct(&rdata, &nsec, NULL);
	check_result(result, "dns_rdata_tostruct()");
	/* Check bit next name is consistent */
	if (!dns_name_equal(&nsec.next, nextname)) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		dns_name_format(nextname, nextbuf, sizeof(nextbuf));
		dns_name_format(&nsec.next, found, sizeof(found));
Evan Hunt's avatar
Evan Hunt committed
605
		fprintf(stderr, "Bad NSEC record for %s, next name "
606 607 608 609 610 611 612 613 614 615
				"mismatch (expected:%s, found:%s)\n", namebuf,
				nextbuf, found);
		goto failure;
	}
	/* Check bit map is consistent */
	result = dns_nsec_buildrdata(db, ver, node, nextname, buffer,
				     &tmprdata);
	check_result(result, "dns_nsec_buildrdata()");
	if (dns_rdata_compare(&rdata, &tmprdata) != 0) {
		dns_name_format(name, namebuf, sizeof(namebuf));
Evan Hunt's avatar
Evan Hunt committed
616
		fprintf(stderr, "Bad NSEC record for %s, bit map "
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
				"mismatch\n", namebuf);
		goto failure;
	}
	result = dns_rdataset_next(&rdataset);
	if (result != ISC_R_NOMORE) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		fprintf(stderr, "Multipe NSEC records for %s\n", namebuf);
		goto failure;

	}
	dns_rdataset_disassociate(&rdataset);
	return (ISC_R_SUCCESS);
 failure:
	if (dns_rdataset_isassociated(&rdataset))
		dns_rdataset_disassociate(&rdataset);
	return (ISC_R_FAILURE);
}

static void
check_no_rrsig(dns_db_t *db, dns_dbversion_t *ver, dns_rdataset_t *rdataset,
	       dns_name_t *name, dns_dbnode_t *node)
{
	char namebuf[DNS_NAME_FORMATSIZE];
	char typebuf[80];
	dns_rdataset_t sigrdataset;
	dns_rdatasetiter_t *rdsiter = NULL;
	isc_result_t result;

	dns_rdataset_init(&sigrdataset);
	result = dns_db_allrdatasets(db, node, ver, 0, &rdsiter);
	check_result(result, "dns_db_allrdatasets()");
	for (result = dns_rdatasetiter_first(rdsiter);
	     result == ISC_R_SUCCESS;
	     result = dns_rdatasetiter_next(rdsiter)) {
		dns_rdatasetiter_current(rdsiter, &sigrdataset);
		if (sigrdataset.type == dns_rdatatype_rrsig &&
		    sigrdataset.covers == rdataset->type)
			break;
		dns_rdataset_disassociate(&sigrdataset);
	}
	if (result == ISC_R_SUCCESS) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		type_format(rdataset->type, typebuf, sizeof(typebuf));
		fprintf(stderr, "Warning: Found unexpected signatures for "
			"%s/%s\n", namebuf, typebuf);
	}
	if (dns_rdataset_isassociated(&sigrdataset))
		dns_rdataset_disassociate(&sigrdataset);
	dns_rdatasetiter_destroy(&rdsiter);
}

static isc_boolean_t
chain_compare(void *arg1, void *arg2) {
	struct nsec3_chain_fixed *e1 = arg1, *e2 = arg2;
	size_t len;

	/*
	 * Do each element in turn to get a stable sort.
	 */
	if (e1->hash < e2->hash)
		return (ISC_TRUE);
	if (e1->hash > e2->hash)
		return (ISC_FALSE);
	if (e1->iterations < e2->iterations)
		return (ISC_TRUE);
	if (e1->iterations > e2->iterations)
		return (ISC_FALSE);
	if (e1->salt_length < e2->salt_length)
		return (ISC_TRUE);
	if (e1->salt_length > e2->salt_length)
		return (ISC_FALSE);
	if (e1->next_length < e2->next_length)
		return (ISC_TRUE);
	if (e1->next_length > e2->next_length)
		return (ISC_FALSE);
	len = e1->salt_length + 2 * e1->next_length;
	if (memcmp(e1 + 1, e2 + 1, len) < 0)
		return (ISC_TRUE);
	return (ISC_FALSE);
}

static isc_boolean_t
chain_equal(struct nsec3_chain_fixed *e1, struct nsec3_chain_fixed *e2) {
	size_t len;

	if (e1->hash != e2->hash)
		return (ISC_FALSE);
	if (e1->iterations != e2->iterations)
		return (ISC_FALSE);
	if (e1->salt_length != e2->salt_length)
		return (ISC_FALSE);
	if (e1->next_length != e2->next_length)
		return (ISC_FALSE);
	len = e1->salt_length + 2 * e1->next_length;
	if (memcmp(e1 + 1, e2 + 1, len) != 0)
		return (ISC_FALSE);
	return (ISC_TRUE);
}

static isc_result_t
record_nsec3(const unsigned char *rawhash, const dns_rdata_nsec3_t *nsec3,
	     isc_mem_t *mctx, isc_heap_t *chains)
{
	struct nsec3_chain_fixed *element;
	size_t len;
	unsigned char *cp;
	isc_result_t result;

	len = sizeof(*element) + nsec3->next_length * 2 + nsec3->salt_length;

	element = isc_mem_get(mctx, len);
	if (element == NULL)
		return (ISC_R_NOMEMORY);
	memset(element, 0, len);
	element->hash = nsec3->hash;
	element->salt_length = nsec3->salt_length;
	element->next_length = nsec3->next_length;
	element->iterations = nsec3->iterations;
	cp = (unsigned char *)(element + 1);
736
	memmove(cp, nsec3->salt, nsec3->salt_length);
737
	cp += nsec3->salt_length;
738
	memmove(cp, rawhash, nsec3->next_length);
739
	cp += nsec3->next_length;
740
	memmove(cp, nsec3->next, nsec3->next_length);
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
	result = isc_heap_insert(chains, element);
	if (result != ISC_R_SUCCESS) {
		fprintf(stderr, "isc_heap_insert failed: %s\n",
			isc_result_totext(result));
		isc_mem_put(mctx, element, len);
	}
	return (result);
}

static isc_result_t
match_nsec3(dns_name_t *name, isc_mem_t *mctx,
	    dns_rdata_nsec3param_t *nsec3param, dns_rdataset_t *rdataset,
	    unsigned char types[8192], unsigned int maxtype,
	    unsigned char *rawhash, size_t rhsize)
{
	unsigned char cbm[8244];
	char namebuf[DNS_NAME_FORMATSIZE];
	dns_rdata_nsec3_t nsec3;
	isc_result_t result;
	unsigned int len;

	/*
	 * Find matching NSEC3 record.
	 */
	for (result = dns_rdataset_first(rdataset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(rdataset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;
		dns_rdataset_current(rdataset, &rdata);
		result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
		check_result(result, "dns_rdata_tostruct()");
		if (nsec3.hash == nsec3param->hash &&
		    nsec3.next_length == rhsize &&
		    nsec3.iterations == nsec3param->iterations &&
		    nsec3.salt_length == nsec3param->salt_length &&
		    memcmp(nsec3.salt, nsec3param->salt,
			   nsec3param->salt_length) == 0)
			break;
	}
	if (result != ISC_R_SUCCESS) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		fprintf(stderr, "Missing NSEC3 record for %s\n", namebuf);
		return (result);
	}

	/*
	 * Check the type list.
	 */
	len = dns_nsec_compressbitmap(cbm, types, maxtype);
	if (nsec3.len != len || memcmp(cbm, nsec3.typebits, len) != 0) {
		dns_name_format(name, namebuf, sizeof(namebuf));
Evan Hunt's avatar
Evan Hunt committed
792
		fprintf(stderr, "Bad NSEC3 record for %s, bit map "
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
				"mismatch\n", namebuf);
		return (ISC_R_FAILURE);
	}

	/*
	 * Record chain.
	 */
	result = record_nsec3(rawhash, &nsec3, mctx, expected_chains);
	check_result(result, "record_nsec3()");

	/*
	 * Make sure there is only one NSEC3 record with this set of
	 * parameters.
	 */
	for (result = dns_rdataset_next(rdataset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(rdataset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;
		dns_rdataset_current(rdataset, &rdata);
		result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
		check_result(result, "dns_rdata_tostruct()");
		if (nsec3.hash == nsec3param->hash &&
		    nsec3.iterations == nsec3param->iterations &&
		    nsec3.salt_length == nsec3param->salt_length &&
		    memcmp(nsec3.salt, nsec3param->salt,
			   nsec3.salt_length) == 0) {
			dns_name_format(name, namebuf, sizeof(namebuf));
			fprintf(stderr, "Multiple NSEC3 records with the "
				"same parameter set for %s", namebuf);
			result = DNS_R_DUPLICATE;
			break;
		}
	}
	if (result != ISC_R_NOMORE)
		return (result);

	result = ISC_R_SUCCESS;
	return (result);
}

static isc_boolean_t
innsec3params(dns_rdata_nsec3_t *nsec3, dns_rdataset_t *nsec3paramset) {
	dns_rdata_nsec3param_t nsec3param;
	isc_result_t result;

	for (result = dns_rdataset_first(nsec3paramset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(nsec3paramset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;

		dns_rdataset_current(nsec3paramset, &rdata);
		result = dns_rdata_tostruct(&rdata, &nsec3param, NULL);
845
		check_result(result, "dns_rdata_tostruct()");
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
		if (nsec3param.flags == 0 &&
		    nsec3param.hash == nsec3->hash &&
		    nsec3param.iterations == nsec3->iterations &&
		    nsec3param.salt_length == nsec3->salt_length &&
		    memcmp(nsec3param.salt, nsec3->salt,
			   nsec3->salt_length) == 0)
			return (ISC_TRUE);
	}
	return (ISC_FALSE);
}

static isc_result_t
record_found(dns_db_t *db, dns_dbversion_t *ver, isc_mem_t *mctx,
	     dns_name_t *name, dns_dbnode_t *node,
	     dns_rdataset_t *nsec3paramset)
{
	unsigned char owner[NSEC3_MAX_HASH_LENGTH];
	dns_rdata_nsec3_t nsec3;
	dns_rdataset_t rdataset;
	dns_label_t hashlabel;
	isc_buffer_t b;
	isc_result_t result;

	if (nsec3paramset == NULL || !dns_rdataset_isassociated(nsec3paramset))
		return (ISC_R_SUCCESS);

	dns_rdataset_init(&rdataset);
	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3,
				     0, 0, &rdataset, NULL);
	if (result != ISC_R_SUCCESS)
		return (ISC_R_SUCCESS);

	dns_name_getlabel(name, 0, &hashlabel);
	isc_region_consume(&hashlabel, 1);
	isc_buffer_init(&b, owner, sizeof(owner));
	result = isc_base32hex_decoderegion(&hashlabel, &b);
	if (result != ISC_R_SUCCESS)
		goto cleanup;

	for (result = dns_rdataset_first(&rdataset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&rdataset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;
		dns_rdataset_current(&rdataset, &rdata);
		result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
		check_result(result, "dns_rdata_tostruct()");
		if (nsec3.next_length != isc_buffer_usedlength(&b))
			continue;
		/*
		 * We only care about NSEC3 records that match a NSEC3PARAM
		 * record.
		 */
		if (!innsec3params(&nsec3, nsec3paramset))
			continue;

		/*
		 * Record chain.
		 */
		result = record_nsec3(owner, &nsec3, mctx, found_chains);
		check_result(result, "record_nsec3()");
	}

 cleanup:
	dns_rdataset_disassociate(&rdataset);
	return (ISC_R_SUCCESS);
}

Evan Hunt's avatar
Evan Hunt committed
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
static isc_boolean_t
isoptout(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	 dns_rdata_t *nsec3rdata)
{
	dns_rdataset_t rdataset;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dns_rdata_nsec3_t nsec3;
	dns_rdata_nsec3param_t nsec3param;
	dns_fixedname_t fixed;
	dns_name_t *hashname;
	isc_result_t result;
	dns_dbnode_t *node = NULL;
	unsigned char rawhash[NSEC3_MAX_HASH_LENGTH];
	size_t rhsize = sizeof(rawhash);
	isc_boolean_t ret;

	result = dns_rdata_tostruct(nsec3rdata, &nsec3param, NULL);
	check_result(result, "dns_rdata_tostruct()");

	dns_fixedname_init(&fixed);
	result = dns_nsec3_hashname(&fixed, rawhash, &rhsize, origin, origin,
				    nsec3param.hash, nsec3param.iterations,
				    nsec3param.salt, nsec3param.salt_length);
	check_result(result, "dns_nsec3_hashname()");

	dns_rdataset_init(&rdataset);
	hashname = dns_fixedname_name(&fixed);
	result = dns_db_findnsec3node(db, hashname, ISC_FALSE, &node);
	if (result == ISC_R_SUCCESS)
		result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3,
					     0, 0, &rdataset, NULL);
	if (result != ISC_R_SUCCESS)
		return (ISC_FALSE);

	result = dns_rdataset_first(&rdataset);
	check_result(result, "dns_rdataset_first()");

	dns_rdataset_current(&rdataset, &rdata);

	result = dns_rdata_tostruct(&rdata, &nsec3, NULL);
	if (result != ISC_R_SUCCESS)
		ret = ISC_FALSE;
	else
		ret = ISC_TF((nsec3.flags & DNS_NSEC3FLAG_OPTOUT) != 0);

	if (dns_rdataset_isassociated(&rdataset))
		dns_rdataset_disassociate(&rdataset);
	if (node != NULL)
		dns_db_detachnode(db, &node);

	return (ret);
}

966 967 968
static isc_result_t
verifynsec3(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	    isc_mem_t *mctx, dns_name_t *name, dns_rdata_t *rdata,
Evan Hunt's avatar
Evan Hunt committed
969 970
	    isc_boolean_t delegation, isc_boolean_t empty,
	    unsigned char types[8192], unsigned int maxtype)
971 972 973 974 975 976 977 978 979 980 981
{
	char namebuf[DNS_NAME_FORMATSIZE];
	char hashbuf[DNS_NAME_FORMATSIZE];
	dns_rdataset_t rdataset;
	dns_rdata_nsec3param_t nsec3param;
	dns_fixedname_t fixed;
	dns_name_t *hashname;
	isc_result_t result;
	dns_dbnode_t *node = NULL;
	unsigned char rawhash[NSEC3_MAX_HASH_LENGTH];
	size_t rhsize = sizeof(rawhash);
Evan Hunt's avatar
Evan Hunt committed
982
	isc_boolean_t optout;
983 984 985 986 987 988 989 990 991 992

	result = dns_rdata_tostruct(rdata, &nsec3param, NULL);
	check_result(result, "dns_rdata_tostruct()");

	if (nsec3param.flags != 0)
		return (ISC_R_SUCCESS);

	if (!dns_nsec3_supportedhash(nsec3param.hash))
		return (ISC_R_SUCCESS);

Evan Hunt's avatar
Evan Hunt committed
993 994
	optout = isoptout(db, ver, origin, rdata);

995 996
	dns_fixedname_init(&fixed);
	result = dns_nsec3_hashname(&fixed, rawhash, &rhsize, name, origin,
Tinderbox User's avatar
Tinderbox User committed
997 998
				    nsec3param.hash, nsec3param.iterations,
				    nsec3param.salt, nsec3param.salt_length);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
	check_result(result, "dns_nsec3_hashname()");

	/*
	 * We don't use dns_db_find() here as it works with the choosen
	 * nsec3 chain and we may also be called with uncommitted data
	 * from dnssec-signzone so the secure status of the zone may not
	 * be up to date.
	 */
	dns_rdataset_init(&rdataset);
	hashname = dns_fixedname_name(&fixed);
	result = dns_db_findnsec3node(db, hashname, ISC_FALSE, &node);
Tinderbox User's avatar
Tinderbox User committed
1010
	if (result == ISC_R_SUCCESS)
1011 1012 1013
		result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3,
					     0, 0, &rdataset, NULL);
	if (result != ISC_R_SUCCESS &&
Evan Hunt's avatar
Evan Hunt committed
1014 1015 1016
	    (!delegation || (empty && !optout) ||
	     (!empty && dns_nsec_isset(types, dns_rdatatype_ds))))
	{
1017 1018 1019 1020
		dns_name_format(name, namebuf, sizeof(namebuf));
		dns_name_format(hashname, hashbuf, sizeof(hashbuf));
		fprintf(stderr, "Missing NSEC3 record for %s (%s)\n",
			namebuf, hashbuf);
Evan Hunt's avatar
Evan Hunt committed
1021 1022 1023 1024
	} else if (result == ISC_R_NOTFOUND &&
		   delegation && (!empty || optout))
	{
		result = ISC_R_SUCCESS;
1025 1026 1027
	} else if (result == ISC_R_SUCCESS) {
		result = match_nsec3(name, mctx, &nsec3param, &rdataset,
				     types, maxtype, rawhash, rhsize);
Evan Hunt's avatar
Evan Hunt committed
1028 1029
	}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	if (dns_rdataset_isassociated(&rdataset))
		dns_rdataset_disassociate(&rdataset);
	if (node != NULL)
		dns_db_detachnode(db, &node);

	return (result);
}

static isc_result_t
verifynsec3s(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	     isc_mem_t *mctx, dns_name_t *name, dns_rdataset_t *nsec3paramset,
Evan Hunt's avatar
Evan Hunt committed
1041 1042
	     isc_boolean_t delegation, isc_boolean_t empty,
	     unsigned char types[8192], unsigned int maxtype)
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
{
	isc_result_t result;

	for (result = dns_rdataset_first(nsec3paramset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(nsec3paramset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;

		dns_rdataset_current(nsec3paramset, &rdata);
		result = verifynsec3(db, ver, origin, mctx, name, &rdata,
Evan Hunt's avatar
Evan Hunt committed
1053
				     delegation, empty, types, maxtype);
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		if (result != ISC_R_SUCCESS)
			break;
	}
	if (result == ISC_R_NOMORE)
		result = ISC_R_SUCCESS;
	return (result);
}

static void
verifyset(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	  isc_mem_t *mctx, dns_rdataset_t *rdataset, dns_name_t *name,
	  dns_dbnode_t *node, dns_rdataset_t *keyrdataset,
	  unsigned char *act_algorithms, unsigned char *bad_algorithms)
{
	unsigned char set_algorithms[256];
	char namebuf[DNS_NAME_FORMATSIZE];
	char algbuf[80];
	char typebuf[80];
	dns_rdataset_t sigrdataset;
	dns_rdatasetiter_t *rdsiter = NULL;
	isc_result_t result;
	int i;

	dns_rdataset_init(&sigrdataset);
	result = dns_db_allrdatasets(db, node, ver, 0, &rdsiter);
	check_result(result, "dns_db_allrdatasets()");
	for (result = dns_rdatasetiter_first(rdsiter);
	     result == ISC_R_SUCCESS;
	     result = dns_rdatasetiter_next(rdsiter)) {
		dns_rdatasetiter_current(rdsiter, &sigrdataset);
		if (sigrdataset.type == dns_rdatatype_rrsig &&
		    sigrdataset.covers == rdataset->type)
			break;
		dns_rdataset_disassociate(&sigrdataset);
	}
	if (result != ISC_R_SUCCESS) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		type_format(rdataset->type, typebuf, sizeof(typebuf));
		fprintf(stderr, "No signatures for %s/%s\n", namebuf, typebuf);
		for (i = 0; i < 256; i++)
			if (act_algorithms[i] != 0)
				bad_algorithms[i] = 1;
		dns_rdatasetiter_destroy(&rdsiter);
		return;
	}

	memset(set_algorithms, 0, sizeof(set_algorithms));
	for (result = dns_rdataset_first(&sigrdataset);
	     result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&sigrdataset)) {
		dns_rdata_t rdata = DNS_RDATA_INIT;
		dns_rdata_rrsig_t sig;

		dns_rdataset_current(&sigrdataset, &rdata);
1108 1109
		result = dns_rdata_tostruct(&rdata, &sig, NULL);
		check_result(result, "dns_rdata_tostruct()");
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
		if (rdataset->ttl != sig.originalttl) {
			dns_name_format(name, namebuf, sizeof(namebuf));
			type_format(rdataset->type, typebuf, sizeof(typebuf));
			fprintf(stderr, "TTL mismatch for %s %s keytag %u\n",
				namebuf, typebuf, sig.keyid);
			continue;
		}
		if ((set_algorithms[sig.algorithm] != 0) ||
		    (act_algorithms[sig.algorithm] == 0))
			continue;
		if (goodsig(origin, &rdata, name, keyrdataset, rdataset, mctx))
			set_algorithms[sig.algorithm] = 1;
	}
	dns_rdatasetiter_destroy(&rdsiter);
	if (memcmp(set_algorithms, act_algorithms, sizeof(set_algorithms))) {
		dns_name_format(name, namebuf, sizeof(namebuf));
		type_format(rdataset->type, typebuf, sizeof(typebuf));
		for (i = 0; i < 256; i++)
			if ((act_algorithms[i] != 0) &&
			    (set_algorithms[i] == 0)) {
				dns_secalg_format(i, algbuf, sizeof(algbuf));
				fprintf(stderr, "No correct %s signature for "
					"%s %s\n", algbuf, namebuf, typebuf);
				bad_algorithms[i] = 1;
			}
	}
	dns_rdataset_disassociate(&sigrdataset);
}

static isc_result_t
verifynode(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
	   isc_mem_t *mctx, dns_name_t *name, dns_dbnode_t *node,
	   isc_boolean_t delegation, dns_rdataset_t *keyrdataset,
	   unsigned char *act_algorithms, unsigned char *bad_algorithms,
	   dns_rdataset_t *nsecset, dns_rdataset_t *nsec3paramset,
	   dns_name_t *nextname)
{
	unsigned char types[8192];
	unsigned int maxtype = 0;
	dns_rdataset_t rdataset; dns_rdatasetiter_t *rdsiter = NULL;
	isc_result_t result, tresult;

	memset(types, 0, sizeof(types));
	result = dns_db_allrdatasets(db, node, ver, 0, &rdsiter);
	check_result(result, "dns_db_allrdatasets()");
	result = dns_rdatasetiter_first(rdsiter);
	dns_rdataset_init(&rdataset);
	while (result == ISC_R_SUCCESS) {
		dns_rdatasetiter_current(rdsiter, &rdataset);
		/*
		 * If we are not at a delegation then everything should be
		 * signed.  If we are at a delegation then only the DS set
		 * is signed.  The NS set is not signed at a delegation but
		 * its existance is recorded in the bit map.  Anything else
		 * other than NSEC and DS is not signed at a delegation.
		 */
		if (rdataset.type != dns_rdatatype_rrsig &&
		    rdataset.type != dns_rdatatype_dnskey &&
		    (!delegation || rdataset.type == dns_rdatatype_ds ||
		     rdataset.type == dns_rdatatype_nsec)) {
			verifyset(db, ver, origin, mctx, &rdataset,
				  name, node, keyrdataset,
				  act_algorithms, bad_algorithms);
			dns_nsec_setbit(types, rdataset.type, 1);
			if (rdataset.type > maxtype)
				maxtype = rdataset.type;
		} else if (rdataset.type != dns_rdatatype_rrsig &&
			   rdataset.type != dns_rdatatype_dnskey) {
			if (rdataset.type == dns_rdatatype_ns)
				dns_nsec_setbit(types, rdataset.type, 1);
			check_no_rrsig(db, ver, &rdataset, name, node);
		} else
			dns_nsec_setbit(types, rdataset.type, 1);
		dns_rdataset_disassociate(&rdataset);
		result = dns_rdatasetiter_next(rdsiter);
	}
	if (result != ISC_R_NOMORE)
		fatal("rdataset iteration failed: %s",
		      isc_result_totext(result));
	dns_rdatasetiter_destroy(&rdsiter);

	result = ISC_R_SUCCESS;

Tinderbox User's avatar
Tinderbox User committed
1193
	if (nsecset != NULL && dns_rdataset_isassociated(nsecset))
1194 1195 1196 1197
		result = verifynsec(db, ver, name, node, nextname);

	if (nsec3paramset != NULL && dns_rdataset_isassociated(nsec3paramset)) {
		tresult = verifynsec3s(db, ver, origin, mctx, name,
Evan Hunt's avatar
Evan Hunt committed
1198 1199
				       nsec3paramset, delegation, ISC_FALSE,
				       types, maxtype);
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
		if (result == ISC_R_SUCCESS && tresult != ISC_R_SUCCESS)
			result = tresult;
	}
	return (result);
}

static isc_boolean_t
is_empty(dns_db_t *db, dns_dbversion_t *ver, dns_dbnode_t *node) {
	dns_rdatasetiter_t *rdsiter = NULL;
	isc_result_t result;

	result = dns_db_allrdatasets(db, node, ver, 0, &rdsiter);
	check_result(result, "dns_db_allrdatasets()");
	result = dns_rdatasetiter_first(rdsiter);
	dns_rdatasetiter_destroy(&rdsiter);
	if (result == ISC_R_NOMORE)
		return (ISC_TRUE);
	return (ISC_FALSE);
}

static void
check_no_nsec(dns_name_t *name, dns_dbnode_t *node, dns_db_t *db,
	      dns_dbversion_t *ver)
{
	dns_rdataset_t rdataset;
	isc_result_t result;

	dns_rdataset_init(&rdataset);
	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec,
				     0, 0, &rdataset, NULL);
	if (result != ISC_R_NOTFOUND) {
		char namebuf[DNS_NAME_FORMATSIZE];
		dns_name_format(name, namebuf, sizeof(namebuf));
		fatal("unexpected NSEC RRset at %s\n", namebuf);
	}

	if (dns_rdataset_isassociated(&rdataset))
		dns_rdataset_disassociate(&rdataset);
}

static isc_boolean_t
newchain(const struct nsec3_chain_fixed *first,
	 const struct nsec3_chain_fixed *e)
{
	if (first->hash != e->hash ||
	    first->iterations != e->iterations ||
	    first->salt_length != e->salt_length ||
	    first->next_length != e->next_length ||
	    memcmp(first + 1, e + 1, first->salt_length) != 0)
		return (ISC_TRUE);
	return (ISC_FALSE);
}

static void
free_element(isc_mem_t *mctx, struct nsec3_chain_fixed *e) {
	size_t len;

	len = sizeof(*e) + e->salt_length + 2 * e->next_length;
	isc_mem_put(mctx, e, len);
}

static isc_boolean_t
checknext(const struct nsec3_chain_fixed *first,
	  const struct nsec3_chain_fixed *e)
{
	char buf[512];
	const unsigned char *d1 = (const unsigned char *)(first + 1);
	const unsigned char *d2 = (const unsigned char *)(e + 1);
	isc_buffer_t b;
	isc_region_t sr;

	d1 += first->salt_length + first->next_length;
	d2 += e->salt_length;

Tinderbox User's avatar
Tinderbox User committed
1274
	if (memcmp(d1, d2, first->next_length) == 0)
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
		return (ISC_TRUE);

	DE_CONST(d1 - first->next_length, sr.base);
	sr.length = first->next_length;
	isc_buffer_init(&b, buf, sizeof(buf));
	isc_base32hex_totext(&sr, 1, "", &b);
	fprintf(stderr, "Break in NSEC3 chain at: %.*s\n",
		(int) isc_buffer_usedlength(&b), buf);

	DE_CONST(d1, sr.base);
	sr.length = first->next_length;
	isc_buffer_init(&b, buf, sizeof(buf));
	isc_base32hex_totext(&sr, 1, "", &b);
	fprintf(stderr, "Expected: %.*s\n", (int) isc_buffer_usedlength(&b),
		buf);

	DE_CONST(d2, sr.base);
	sr.length = first->next_length;
	isc_buffer_init(&b, buf, sizeof(buf));
	isc_base32hex_totext(&sr, 1, "", &b);
	fprintf(stderr, "Found: %.*s\n", (int) isc_buffer_usedlength(&b), buf);

	return (ISC_FALSE);
}

#define EXPECTEDANDFOUND "Expected and found NSEC3 chains not equal\n"

static isc_result_t
verify_nsec3_chains(isc_mem_t *mctx) {
	isc_result_t result = ISC_R_SUCCESS;
	struct nsec3_chain_fixed *e, *f = NULL;
	struct nsec3_chain_fixed *first = NULL, *prev = NULL;

	while ((e = isc_heap_element(expected_chains, 1)) != NULL) {
		isc_heap_delete(expected_chains, 1);
		if (f == NULL)
			f = isc_heap_element(found_chains, 1);
		if (f != NULL) {
			isc_heap_delete(found_chains, 1);

			/*
			 * Check that they match.
			 */
			if (chain_equal(e, f)) {
				free_element(mctx, f);
				f = NULL;
			} else {
				if (result == ISC_R_SUCCESS)
					fprintf(stderr, EXPECTEDANDFOUND);
				result = ISC_R_FAILURE;
				/*
				 * Attempt to resync found_chain.
				 */
				while (f != NULL && !chain_compare(e, f)) {
					free_element(mctx, f);
					f = isc_heap_element(found_chains, 1);
					if (f != NULL)
						isc_heap_delete(found_chains, 1);
					if (f != NULL && chain_equal(e, f)) {
						free_element(mctx, f);
						f = NULL;
						break;
					}
				}
			}
		} else if (result == ISC_R_SUCCESS) {
			fprintf(stderr, EXPECTEDANDFOUND);
			result = ISC_R_FAILURE;
		}
		if (first == NULL || newchain(first, e)) {
			if (prev != NULL) {
				if (!checknext(prev, first))
					result = ISC_R_FAILURE;
				if (prev != first)
					free_element(mctx, prev);
			}
			if (first != NULL)
				free_element(mctx, first);
			prev = first = e;
			continue;
		}
		if (!checknext(prev, e))
			result = ISC_R_FAILURE;
		if (prev != first)
			free_element(mctx, prev);
		prev = e;
	}
	if (prev != NULL) {
		if (!checknext(prev, first))
			result = ISC_R_FAILURE;
		if (prev != first)
			free_element(mctx, prev);
	}
	if (first != NULL)
		free_element(mctx, first);
	do {
		if (f != NULL) {
			if (result == ISC_R_SUCCESS) {
				fprintf(stderr, EXPECTEDANDFOUND);
				result = ISC_R_FAILURE;
			}
			free_element(mctx, f);
		}
		f = isc_heap_element(found_chains, 1);
Tinderbox User's avatar
Tinderbox User committed
1379
		if (f != NULL)
1380 1381 1382 1383 1384 1385 1386 1387
			isc_heap_delete(found_chains, 1);
	} while (f != NULL);

	return (result);
}

static isc_result_t
verifyemptynodes(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *origin,
Evan Hunt's avatar
Evan Hunt committed
1388 1389
		 isc_mem_t *mctx, dns_name_t *name, dns_name_t *prevname,
		 isc_boolean_t isdelegation, dns_rdataset_t *nsec3paramset)
1390 1391 1392 1393 1394 1395 1396
{
	dns_namereln_t reln;
	int order;
	unsigned int labels, nlabels, i;
	dns_name_t suffix;
	isc_result_t result = ISC_R_SUCCESS, tresult;

Evan Hunt's avatar
Evan Hunt committed
1397
	reln = dns_name_fullcompare(prevname, name, &order, &labels);
1398 1399 1400
	if (order >= 0)
		return (result);

Evan Hunt's avatar
Evan Hunt committed
1401
	nlabels = dns_name_countlabels(name);
1402 1403 1404 1405 1406

	if (reln == dns_namereln_commonancestor ||
	    reln == dns_namereln_contains) {
		dns_name_init(&suffix, NULL);
		for (i = labels + 1; i < nlabels; i++) {
Evan Hunt's avatar
Evan Hunt committed
1407
			dns_name_getlabelsequence(name, nlabels - i, i,
1408 1409 1410 1411 1412
						  &suffix);
			if (nsec3paramset != NULL &&
			     dns_rdataset_isassociated(nsec3paramset)) {
				tresult = verifynsec3s(db, ver, origin, mctx,
						       &suffix, nsec3paramset,
Evan Hunt's avatar
Evan Hunt committed
1413 1414
						       isdelegation, ISC_TRUE,
						       NULL, 0);
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
				if (result == ISC_R_SUCCESS &&
				    tresult != ISC_R_SUCCESS)
					result = tresult;
			}
		}
	}
	return (result);
}

/*%
 * Verify that certain things are sane:
 *
 *   The apex has a DNSKEY record with at least one KSK, and at least
 *   one ZSK if the -x flag was not used.
 *
 *   The DNSKEY record was signed with at least one of the KSKs in this
 *   set.
 *
 *   The rest of the zone was signed with at least one of the ZSKs
 *   present in the DNSKEY RRSET.
 */
void
verifyzone(dns_db_t *db, dns_dbversion_t *ver,
	   dns_name_t *origin, isc_mem_t *mctx,
	   isc_boolean_t ignore_kskflag, isc_boolean_t keyset_kskonly)
{
	char algbuf[80];
	dns_dbiterator_t *dbiter = NULL;
	dns_dbnode_t *node = NULL, *nextnode = NULL;
Evan Hunt's avatar
Evan Hunt committed
1444 1445
	dns_fixedname_t fname, fnextname, fprevname, fzonecut;
	dns_name_t *name, *nextname, *prevname, *zonecut;
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536