Remove building with NOCRYPTO option
[minix.git] / external / bsd / bind / dist / lib / dns / dnssec.c
blob6a315a0be9027ef6a5443a76d66142d33a8ea06d
1 /* $NetBSD: dnssec.c,v 1.11 2015/07/08 17:28:58 christos Exp $ */
3 /*
4 * Copyright (C) 2004-2015 Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (C) 1999-2003 Internet Software Consortium.
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 * PERFORMANCE OF THIS SOFTWARE.
21 * Id
24 /*! \file */
26 #include <config.h>
28 #include <stdlib.h>
30 #include <isc/buffer.h>
31 #include <isc/dir.h>
32 #include <isc/mem.h>
33 #include <isc/serial.h>
34 #include <isc/string.h>
35 #include <isc/util.h>
37 #include <dns/db.h>
38 #include <dns/diff.h>
39 #include <dns/dnssec.h>
40 #include <dns/fixedname.h>
41 #include <dns/keyvalues.h>
42 #include <dns/log.h>
43 #include <dns/message.h>
44 #include <dns/rdata.h>
45 #include <dns/rdatalist.h>
46 #include <dns/rdataset.h>
47 #include <dns/rdatastruct.h>
48 #include <dns/result.h>
49 #include <dns/stats.h>
50 #include <dns/tsig.h> /* for DNS_TSIG_FUDGE */
52 #include <dst/result.h>
54 LIBDNS_EXTERNAL_DATA isc_stats_t *dns_dnssec_stats;
56 #define is_response(msg) (msg->flags & DNS_MESSAGEFLAG_QR)
58 #define RETERR(x) do { \
59 result = (x); \
60 if (result != ISC_R_SUCCESS) \
61 goto failure; \
62 } while (/*CONSTCOND*/0)
65 #define TYPE_SIGN 0
66 #define TYPE_VERIFY 1
68 static isc_result_t
69 digest_callback(void *arg, isc_region_t *data);
71 static int
72 rdata_compare_wrapper(const void *rdata1, const void *rdata2);
74 static isc_result_t
75 rdataset_to_sortedarray(dns_rdataset_t *set, isc_mem_t *mctx,
76 dns_rdata_t **rdata, int *nrdata);
78 static isc_result_t
79 digest_callback(void *arg, isc_region_t *data) {
80 dst_context_t *ctx = arg;
82 return (dst_context_adddata(ctx, data));
85 static inline void
86 inc_stat(isc_statscounter_t counter) {
87 if (dns_dnssec_stats != NULL)
88 isc_stats_increment(dns_dnssec_stats, counter);
92 * Make qsort happy.
94 static int
95 rdata_compare_wrapper(const void *rdata1, const void *rdata2) {
96 return (dns_rdata_compare((const dns_rdata_t *)rdata1,
97 (const dns_rdata_t *)rdata2));
101 * Sort the rdataset into an array.
103 static isc_result_t
104 rdataset_to_sortedarray(dns_rdataset_t *set, isc_mem_t *mctx,
105 dns_rdata_t **rdata, int *nrdata)
107 isc_result_t ret;
108 int i = 0, n;
109 dns_rdata_t *data;
110 dns_rdataset_t rdataset;
112 n = dns_rdataset_count(set);
114 data = isc_mem_get(mctx, n * sizeof(dns_rdata_t));
115 if (data == NULL)
116 return (ISC_R_NOMEMORY);
118 dns_rdataset_init(&rdataset);
119 dns_rdataset_clone(set, &rdataset);
120 ret = dns_rdataset_first(&rdataset);
121 if (ret != ISC_R_SUCCESS) {
122 dns_rdataset_disassociate(&rdataset);
123 isc_mem_put(mctx, data, n * sizeof(dns_rdata_t));
124 return (ret);
128 * Put them in the array.
130 do {
131 dns_rdata_init(&data[i]);
132 dns_rdataset_current(&rdataset, &data[i++]);
133 } while (dns_rdataset_next(&rdataset) == ISC_R_SUCCESS);
136 * Sort the array.
138 qsort(data, n, sizeof(dns_rdata_t), rdata_compare_wrapper);
139 *rdata = data;
140 *nrdata = n;
141 dns_rdataset_disassociate(&rdataset);
142 return (ISC_R_SUCCESS);
145 isc_result_t
146 dns_dnssec_keyfromrdata(dns_name_t *name, dns_rdata_t *rdata, isc_mem_t *mctx,
147 dst_key_t **key)
149 isc_buffer_t b;
150 isc_region_t r;
152 INSIST(name != NULL);
153 INSIST(rdata != NULL);
154 INSIST(mctx != NULL);
155 INSIST(key != NULL);
156 INSIST(*key == NULL);
157 REQUIRE(rdata->type == dns_rdatatype_key ||
158 rdata->type == dns_rdatatype_dnskey);
160 dns_rdata_toregion(rdata, &r);
161 isc_buffer_init(&b, r.base, r.length);
162 isc_buffer_add(&b, r.length);
163 return (dst_key_fromdns(name, rdata->rdclass, &b, mctx, key));
166 static isc_result_t
167 digest_sig(dst_context_t *ctx, isc_boolean_t downcase, dns_rdata_t *sigrdata,
168 dns_rdata_rrsig_t *rrsig)
170 isc_region_t r;
171 isc_result_t ret;
172 dns_fixedname_t fname;
174 dns_rdata_toregion(sigrdata, &r);
175 INSIST(r.length >= 19);
177 r.length = 18;
178 ret = dst_context_adddata(ctx, &r);
179 if (ret != ISC_R_SUCCESS)
180 return (ret);
181 if (downcase) {
182 dns_fixedname_init(&fname);
184 RUNTIME_CHECK(dns_name_downcase(&rrsig->signer,
185 dns_fixedname_name(&fname),
186 NULL) == ISC_R_SUCCESS);
187 dns_name_toregion(dns_fixedname_name(&fname), &r);
188 } else
189 dns_name_toregion(&rrsig->signer, &r);
191 return (dst_context_adddata(ctx, &r));
194 isc_result_t
195 dns_dnssec_sign(dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
196 isc_stdtime_t *inception, isc_stdtime_t *expire,
197 isc_mem_t *mctx, isc_buffer_t *buffer, dns_rdata_t *sigrdata)
199 dns_rdata_rrsig_t sig;
200 dns_rdata_t tmpsigrdata;
201 dns_rdata_t *rdatas;
202 int nrdatas, i;
203 isc_buffer_t sigbuf, envbuf;
204 isc_region_t r;
205 dst_context_t *ctx = NULL;
206 isc_result_t ret;
207 isc_buffer_t *databuf = NULL;
208 char data[256 + 8];
209 isc_uint32_t flags;
210 unsigned int sigsize;
211 dns_fixedname_t fnewname;
212 dns_fixedname_t fsigner;
214 REQUIRE(name != NULL);
215 REQUIRE(dns_name_countlabels(name) <= 255);
216 REQUIRE(set != NULL);
217 REQUIRE(key != NULL);
218 REQUIRE(inception != NULL);
219 REQUIRE(expire != NULL);
220 REQUIRE(mctx != NULL);
221 REQUIRE(sigrdata != NULL);
223 if (*inception >= *expire)
224 return (DNS_R_INVALIDTIME);
227 * Is the key allowed to sign data?
229 flags = dst_key_flags(key);
230 if (flags & DNS_KEYTYPE_NOAUTH)
231 return (DNS_R_KEYUNAUTHORIZED);
232 if ((flags & DNS_KEYFLAG_OWNERMASK) != DNS_KEYOWNER_ZONE)
233 return (DNS_R_KEYUNAUTHORIZED);
235 sig.mctx = mctx;
236 sig.common.rdclass = set->rdclass;
237 sig.common.rdtype = dns_rdatatype_rrsig;
238 ISC_LINK_INIT(&sig.common, link);
241 * Downcase signer.
243 dns_name_init(&sig.signer, NULL);
244 dns_fixedname_init(&fsigner);
245 RUNTIME_CHECK(dns_name_downcase(dst_key_name(key),
246 dns_fixedname_name(&fsigner), NULL) == ISC_R_SUCCESS);
247 dns_name_clone(dns_fixedname_name(&fsigner), &sig.signer);
249 sig.covered = set->type;
250 sig.algorithm = dst_key_alg(key);
251 sig.labels = dns_name_countlabels(name) - 1;
252 if (dns_name_iswildcard(name))
253 sig.labels--;
254 sig.originalttl = set->ttl;
255 sig.timesigned = *inception;
256 sig.timeexpire = *expire;
257 sig.keyid = dst_key_id(key);
258 ret = dst_key_sigsize(key, &sigsize);
259 if (ret != ISC_R_SUCCESS)
260 return (ret);
261 sig.siglen = sigsize;
263 * The actual contents of sig.signature are not important yet, since
264 * they're not used in digest_sig().
266 sig.signature = isc_mem_get(mctx, sig.siglen);
267 if (sig.signature == NULL)
268 return (ISC_R_NOMEMORY);
270 ret = isc_buffer_allocate(mctx, &databuf, sigsize + 256 + 18);
271 if (ret != ISC_R_SUCCESS)
272 goto cleanup_signature;
274 dns_rdata_init(&tmpsigrdata);
275 ret = dns_rdata_fromstruct(&tmpsigrdata, sig.common.rdclass,
276 sig.common.rdtype, &sig, databuf);
277 if (ret != ISC_R_SUCCESS)
278 goto cleanup_databuf;
280 ret = dst_context_create3(key, mctx,
281 DNS_LOGCATEGORY_DNSSEC, ISC_TRUE, &ctx);
282 if (ret != ISC_R_SUCCESS)
283 goto cleanup_databuf;
286 * Digest the SIG rdata.
288 ret = digest_sig(ctx, ISC_FALSE, &tmpsigrdata, &sig);
289 if (ret != ISC_R_SUCCESS)
290 goto cleanup_context;
292 dns_fixedname_init(&fnewname);
293 RUNTIME_CHECK(dns_name_downcase(name, dns_fixedname_name(&fnewname),
294 NULL) == ISC_R_SUCCESS);
295 dns_name_toregion(dns_fixedname_name(&fnewname), &r);
298 * Create an envelope for each rdata: <name|type|class|ttl>.
300 isc_buffer_init(&envbuf, data, sizeof(data));
301 memmove(data, r.base, r.length);
302 isc_buffer_add(&envbuf, r.length);
303 isc_buffer_putuint16(&envbuf, set->type);
304 isc_buffer_putuint16(&envbuf, set->rdclass);
305 isc_buffer_putuint32(&envbuf, set->ttl);
307 ret = rdataset_to_sortedarray(set, mctx, &rdatas, &nrdatas);
308 if (ret != ISC_R_SUCCESS)
309 goto cleanup_context;
310 isc_buffer_usedregion(&envbuf, &r);
312 for (i = 0; i < nrdatas; i++) {
313 isc_uint16_t len;
314 isc_buffer_t lenbuf;
315 isc_region_t lenr;
318 * Skip duplicates.
320 if (i > 0 && dns_rdata_compare(&rdatas[i], &rdatas[i-1]) == 0)
321 continue;
324 * Digest the envelope.
326 ret = dst_context_adddata(ctx, &r);
327 if (ret != ISC_R_SUCCESS)
328 goto cleanup_array;
331 * Digest the length of the rdata.
333 isc_buffer_init(&lenbuf, &len, sizeof(len));
334 INSIST(rdatas[i].length < 65536);
335 isc_buffer_putuint16(&lenbuf, (isc_uint16_t)rdatas[i].length);
336 isc_buffer_usedregion(&lenbuf, &lenr);
337 ret = dst_context_adddata(ctx, &lenr);
338 if (ret != ISC_R_SUCCESS)
339 goto cleanup_array;
342 * Digest the rdata.
344 ret = dns_rdata_digest(&rdatas[i], digest_callback, ctx);
345 if (ret != ISC_R_SUCCESS)
346 goto cleanup_array;
349 isc_buffer_init(&sigbuf, sig.signature, sig.siglen);
350 ret = dst_context_sign(ctx, &sigbuf);
351 if (ret != ISC_R_SUCCESS)
352 goto cleanup_array;
353 isc_buffer_usedregion(&sigbuf, &r);
354 if (r.length != sig.siglen) {
355 ret = ISC_R_NOSPACE;
356 goto cleanup_array;
359 ret = dns_rdata_fromstruct(sigrdata, sig.common.rdclass,
360 sig.common.rdtype, &sig, buffer);
362 cleanup_array:
363 isc_mem_put(mctx, rdatas, nrdatas * sizeof(dns_rdata_t));
364 cleanup_context:
365 dst_context_destroy(&ctx);
366 cleanup_databuf:
367 isc_buffer_free(&databuf);
368 cleanup_signature:
369 isc_mem_put(mctx, sig.signature, sig.siglen);
371 return (ret);
374 isc_result_t
375 dns_dnssec_verify2(dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
376 isc_boolean_t ignoretime, isc_mem_t *mctx,
377 dns_rdata_t *sigrdata, dns_name_t *wild)
379 return (dns_dnssec_verify3(name, set, key, ignoretime, 0, mctx,
380 sigrdata, wild));
383 isc_result_t
384 dns_dnssec_verify3(dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
385 isc_boolean_t ignoretime, unsigned int maxbits,
386 isc_mem_t *mctx, dns_rdata_t *sigrdata, dns_name_t *wild)
388 dns_rdata_rrsig_t sig;
389 dns_fixedname_t fnewname;
390 isc_region_t r;
391 isc_buffer_t envbuf;
392 dns_rdata_t *rdatas;
393 int nrdatas, i;
394 isc_stdtime_t now;
395 isc_result_t ret;
396 unsigned char data[300];
397 dst_context_t *ctx = NULL;
398 int labels = 0;
399 isc_uint32_t flags;
400 isc_boolean_t downcase = ISC_FALSE;
402 REQUIRE(name != NULL);
403 REQUIRE(set != NULL);
404 REQUIRE(key != NULL);
405 REQUIRE(mctx != NULL);
406 REQUIRE(sigrdata != NULL && sigrdata->type == dns_rdatatype_rrsig);
408 ret = dns_rdata_tostruct(sigrdata, &sig, NULL);
409 if (ret != ISC_R_SUCCESS)
410 return (ret);
412 if (set->type != sig.covered)
413 return (DNS_R_SIGINVALID);
415 if (isc_serial_lt(sig.timeexpire, sig.timesigned)) {
416 inc_stat(dns_dnssecstats_fail);
417 return (DNS_R_SIGINVALID);
420 if (!ignoretime) {
421 isc_stdtime_get(&now);
424 * Is SIG temporally valid?
426 if (isc_serial_lt((isc_uint32_t)now, sig.timesigned)) {
427 inc_stat(dns_dnssecstats_fail);
428 return (DNS_R_SIGFUTURE);
429 } else if (isc_serial_lt(sig.timeexpire, (isc_uint32_t)now)) {
430 inc_stat(dns_dnssecstats_fail);
431 return (DNS_R_SIGEXPIRED);
436 * NS, SOA and DNSSKEY records are signed by their owner.
437 * DS records are signed by the parent.
439 switch (set->type) {
440 case dns_rdatatype_ns:
441 case dns_rdatatype_soa:
442 case dns_rdatatype_dnskey:
443 if (!dns_name_equal(name, &sig.signer)) {
444 inc_stat(dns_dnssecstats_fail);
445 return (DNS_R_SIGINVALID);
447 break;
448 case dns_rdatatype_ds:
449 if (dns_name_equal(name, &sig.signer)) {
450 inc_stat(dns_dnssecstats_fail);
451 return (DNS_R_SIGINVALID);
453 /* FALLTHROUGH */
454 default:
455 if (!dns_name_issubdomain(name, &sig.signer)) {
456 inc_stat(dns_dnssecstats_fail);
457 return (DNS_R_SIGINVALID);
459 break;
463 * Is the key allowed to sign data?
465 flags = dst_key_flags(key);
466 if (flags & DNS_KEYTYPE_NOAUTH) {
467 inc_stat(dns_dnssecstats_fail);
468 return (DNS_R_KEYUNAUTHORIZED);
470 if ((flags & DNS_KEYFLAG_OWNERMASK) != DNS_KEYOWNER_ZONE) {
471 inc_stat(dns_dnssecstats_fail);
472 return (DNS_R_KEYUNAUTHORIZED);
475 again:
476 ret = dst_context_create4(key, mctx, DNS_LOGCATEGORY_DNSSEC,
477 ISC_FALSE, maxbits, &ctx);
478 if (ret != ISC_R_SUCCESS)
479 goto cleanup_struct;
482 * Digest the SIG rdata (not including the signature).
484 ret = digest_sig(ctx, downcase, sigrdata, &sig);
485 if (ret != ISC_R_SUCCESS)
486 goto cleanup_context;
489 * If the name is an expanded wildcard, use the wildcard name.
491 dns_fixedname_init(&fnewname);
492 labels = dns_name_countlabels(name) - 1;
493 RUNTIME_CHECK(dns_name_downcase(name, dns_fixedname_name(&fnewname),
494 NULL) == ISC_R_SUCCESS);
495 if (labels - sig.labels > 0)
496 dns_name_split(dns_fixedname_name(&fnewname), sig.labels + 1,
497 NULL, dns_fixedname_name(&fnewname));
499 dns_name_toregion(dns_fixedname_name(&fnewname), &r);
502 * Create an envelope for each rdata: <name|type|class|ttl>.
504 isc_buffer_init(&envbuf, data, sizeof(data));
505 if (labels - sig.labels > 0) {
506 isc_buffer_putuint8(&envbuf, 1);
507 isc_buffer_putuint8(&envbuf, '*');
508 memmove(data + 2, r.base, r.length);
510 else
511 memmove(data, r.base, r.length);
512 isc_buffer_add(&envbuf, r.length);
513 isc_buffer_putuint16(&envbuf, set->type);
514 isc_buffer_putuint16(&envbuf, set->rdclass);
515 isc_buffer_putuint32(&envbuf, sig.originalttl);
517 ret = rdataset_to_sortedarray(set, mctx, &rdatas, &nrdatas);
518 if (ret != ISC_R_SUCCESS)
519 goto cleanup_context;
521 isc_buffer_usedregion(&envbuf, &r);
523 for (i = 0; i < nrdatas; i++) {
524 isc_uint16_t len;
525 isc_buffer_t lenbuf;
526 isc_region_t lenr;
529 * Skip duplicates.
531 if (i > 0 && dns_rdata_compare(&rdatas[i], &rdatas[i-1]) == 0)
532 continue;
535 * Digest the envelope.
537 ret = dst_context_adddata(ctx, &r);
538 if (ret != ISC_R_SUCCESS)
539 goto cleanup_array;
542 * Digest the rdata length.
544 isc_buffer_init(&lenbuf, &len, sizeof(len));
545 INSIST(rdatas[i].length < 65536);
546 isc_buffer_putuint16(&lenbuf, (isc_uint16_t)rdatas[i].length);
547 isc_buffer_usedregion(&lenbuf, &lenr);
550 * Digest the rdata.
552 ret = dst_context_adddata(ctx, &lenr);
553 if (ret != ISC_R_SUCCESS)
554 goto cleanup_array;
555 ret = dns_rdata_digest(&rdatas[i], digest_callback, ctx);
556 if (ret != ISC_R_SUCCESS)
557 goto cleanup_array;
560 r.base = sig.signature;
561 r.length = sig.siglen;
562 ret = dst_context_verify2(ctx, maxbits, &r);
563 if (ret == ISC_R_SUCCESS && downcase) {
564 char namebuf[DNS_NAME_FORMATSIZE];
565 dns_name_format(&sig.signer, namebuf, sizeof(namebuf));
566 isc_log_write(dns_lctx, DNS_LOGCATEGORY_DNSSEC,
567 DNS_LOGMODULE_DNSSEC, ISC_LOG_DEBUG(1),
568 "successfully validated after lower casing "
569 "signer '%s'", namebuf);
570 inc_stat(dns_dnssecstats_downcase);
571 } else if (ret == ISC_R_SUCCESS)
572 inc_stat(dns_dnssecstats_asis);
574 cleanup_array:
575 isc_mem_put(mctx, rdatas, nrdatas * sizeof(dns_rdata_t));
576 cleanup_context:
577 dst_context_destroy(&ctx);
578 if (ret == DST_R_VERIFYFAILURE && !downcase) {
579 downcase = ISC_TRUE;
580 goto again;
582 cleanup_struct:
583 dns_rdata_freestruct(&sig);
585 if (ret == DST_R_VERIFYFAILURE)
586 ret = DNS_R_SIGINVALID;
588 if (ret != ISC_R_SUCCESS)
589 inc_stat(dns_dnssecstats_fail);
591 if (ret == ISC_R_SUCCESS && labels - sig.labels > 0) {
592 if (wild != NULL)
593 RUNTIME_CHECK(dns_name_concatenate(dns_wildcardname,
594 dns_fixedname_name(&fnewname),
595 wild, NULL) == ISC_R_SUCCESS);
596 inc_stat(dns_dnssecstats_wildcard);
597 ret = DNS_R_FROMWILDCARD;
599 return (ret);
602 isc_result_t
603 dns_dnssec_verify(dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
604 isc_boolean_t ignoretime, isc_mem_t *mctx,
605 dns_rdata_t *sigrdata)
607 isc_result_t result;
609 result = dns_dnssec_verify2(name, set, key, ignoretime, mctx,
610 sigrdata, NULL);
611 if (result == DNS_R_FROMWILDCARD)
612 result = ISC_R_SUCCESS;
613 return (result);
616 isc_boolean_t
617 dns_dnssec_keyactive(dst_key_t *key, isc_stdtime_t now) {
618 isc_result_t result;
619 isc_stdtime_t publish, active, revoke, inactive, delete;
620 isc_boolean_t pubset = ISC_FALSE, actset = ISC_FALSE;
621 isc_boolean_t revset = ISC_FALSE, inactset = ISC_FALSE;
622 isc_boolean_t delset = ISC_FALSE;
623 int major, minor;
625 /* Is this an old-style key? */
626 result = dst_key_getprivateformat(key, &major, &minor);
627 RUNTIME_CHECK(result == ISC_R_SUCCESS);
630 * Smart signing started with key format 1.3; prior to that, all
631 * keys are assumed active
633 if (major == 1 && minor <= 2)
634 return (ISC_TRUE);
636 result = dst_key_gettime(key, DST_TIME_PUBLISH, &publish);
637 if (result == ISC_R_SUCCESS)
638 pubset = ISC_TRUE;
640 result = dst_key_gettime(key, DST_TIME_ACTIVATE, &active);
641 if (result == ISC_R_SUCCESS)
642 actset = ISC_TRUE;
644 result = dst_key_gettime(key, DST_TIME_REVOKE, &revoke);
645 if (result == ISC_R_SUCCESS)
646 revset = ISC_TRUE;
648 result = dst_key_gettime(key, DST_TIME_INACTIVE, &inactive);
649 if (result == ISC_R_SUCCESS)
650 inactset = ISC_TRUE;
652 result = dst_key_gettime(key, DST_TIME_DELETE, &delete);
653 if (result == ISC_R_SUCCESS)
654 delset = ISC_TRUE;
656 if ((inactset && inactive <= now) || (delset && delete <= now))
657 return (ISC_FALSE);
659 if (revset && revoke <= now && pubset && publish <= now)
660 return (ISC_TRUE);
662 if (actset && active <= now)
663 return (ISC_TRUE);
665 return (ISC_FALSE);
668 #define is_zone_key(key) ((dst_key_flags(key) & DNS_KEYFLAG_OWNERMASK) \
669 == DNS_KEYOWNER_ZONE)
671 isc_result_t
672 dns_dnssec_findzonekeys2(dns_db_t *db, dns_dbversion_t *ver,
673 dns_dbnode_t *node, dns_name_t *name,
674 const char *directory, isc_mem_t *mctx,
675 unsigned int maxkeys, dst_key_t **keys,
676 unsigned int *nkeys)
678 dns_rdataset_t rdataset;
679 dns_rdata_t rdata = DNS_RDATA_INIT;
680 isc_result_t result;
681 dst_key_t *pubkey = NULL;
682 unsigned int count = 0;
683 isc_stdtime_t now;
685 REQUIRE(nkeys != NULL);
686 REQUIRE(keys != NULL);
688 isc_stdtime_get(&now);
690 *nkeys = 0;
691 memset(keys, 0, sizeof(*keys) * maxkeys);
692 dns_rdataset_init(&rdataset);
693 RETERR(dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey, 0, 0,
694 &rdataset, NULL));
695 RETERR(dns_rdataset_first(&rdataset));
696 while (result == ISC_R_SUCCESS && count < maxkeys) {
697 pubkey = NULL;
698 dns_rdataset_current(&rdataset, &rdata);
699 RETERR(dns_dnssec_keyfromrdata(name, &rdata, mctx, &pubkey));
700 dst_key_setttl(pubkey, rdataset.ttl);
702 if (!is_zone_key(pubkey) ||
703 (dst_key_flags(pubkey) & DNS_KEYTYPE_NOAUTH) != 0)
704 goto next;
705 /* Corrupted .key file? */
706 if (!dns_name_equal(name, dst_key_name(pubkey)))
707 goto next;
708 keys[count] = NULL;
709 result = dst_key_fromfile(dst_key_name(pubkey),
710 dst_key_id(pubkey),
711 dst_key_alg(pubkey),
712 DST_TYPE_PUBLIC|DST_TYPE_PRIVATE,
713 directory,
714 mctx, &keys[count]);
717 * If the key was revoked and the private file
718 * doesn't exist, maybe it was revoked internally
719 * by named. Try loading the unrevoked version.
721 if (result == ISC_R_FILENOTFOUND) {
722 isc_uint32_t flags;
723 flags = dst_key_flags(pubkey);
724 if ((flags & DNS_KEYFLAG_REVOKE) != 0) {
725 dst_key_setflags(pubkey,
726 flags & ~DNS_KEYFLAG_REVOKE);
727 result = dst_key_fromfile(dst_key_name(pubkey),
728 dst_key_id(pubkey),
729 dst_key_alg(pubkey),
730 DST_TYPE_PUBLIC|
731 DST_TYPE_PRIVATE,
732 directory,
733 mctx, &keys[count]);
734 if (result == ISC_R_SUCCESS &&
735 dst_key_pubcompare(pubkey, keys[count],
736 ISC_FALSE)) {
737 dst_key_setflags(keys[count], flags);
739 dst_key_setflags(pubkey, flags);
743 if (result != ISC_R_SUCCESS) {
744 char keybuf[DNS_NAME_FORMATSIZE];
745 char algbuf[DNS_SECALG_FORMATSIZE];
746 dns_name_format(dst_key_name(pubkey), keybuf,
747 sizeof(keybuf));
748 dns_secalg_format(dst_key_alg(pubkey), algbuf,
749 sizeof(algbuf));
750 isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
751 DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
752 "dns_dnssec_findzonekeys2: error "
753 "reading private key file %s/%s/%d: %s",
754 keybuf, algbuf, dst_key_id(pubkey),
755 isc_result_totext(result));
758 if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
759 keys[count] = pubkey;
760 pubkey = NULL;
761 count++;
762 goto next;
765 if (result != ISC_R_SUCCESS)
766 goto failure;
769 * If a key is marked inactive, skip it
771 if (!dns_dnssec_keyactive(keys[count], now)) {
772 dst_key_setinactive(pubkey, ISC_TRUE);
773 dst_key_free(&keys[count]);
774 keys[count] = pubkey;
775 pubkey = NULL;
776 count++;
777 goto next;
781 * Whatever the key's default TTL may have
782 * been, the rdataset TTL takes priority.
784 dst_key_setttl(keys[count], rdataset.ttl);
786 if ((dst_key_flags(keys[count]) & DNS_KEYTYPE_NOAUTH) != 0) {
787 /* We should never get here. */
788 dst_key_free(&keys[count]);
789 goto next;
791 count++;
792 next:
793 if (pubkey != NULL)
794 dst_key_free(&pubkey);
795 dns_rdata_reset(&rdata);
796 result = dns_rdataset_next(&rdataset);
798 if (result != ISC_R_NOMORE)
799 goto failure;
800 if (count == 0)
801 result = ISC_R_NOTFOUND;
802 else
803 result = ISC_R_SUCCESS;
805 failure:
806 if (dns_rdataset_isassociated(&rdataset))
807 dns_rdataset_disassociate(&rdataset);
808 if (pubkey != NULL)
809 dst_key_free(&pubkey);
810 if (result != ISC_R_SUCCESS)
811 while (count > 0)
812 dst_key_free(&keys[--count]);
813 *nkeys = count;
814 return (result);
817 isc_result_t
818 dns_dnssec_findzonekeys(dns_db_t *db, dns_dbversion_t *ver,
819 dns_dbnode_t *node, dns_name_t *name, isc_mem_t *mctx,
820 unsigned int maxkeys, dst_key_t **keys,
821 unsigned int *nkeys)
823 return (dns_dnssec_findzonekeys2(db, ver, node, name, NULL, mctx,
824 maxkeys, keys, nkeys));
827 isc_result_t
828 dns_dnssec_signmessage(dns_message_t *msg, dst_key_t *key) {
829 dns_rdata_sig_t sig; /* SIG(0) */
830 unsigned char data[512];
831 unsigned char header[DNS_MESSAGE_HEADERLEN];
832 isc_buffer_t headerbuf, databuf, sigbuf;
833 unsigned int sigsize;
834 isc_buffer_t *dynbuf = NULL;
835 dns_rdata_t *rdata;
836 dns_rdatalist_t *datalist;
837 dns_rdataset_t *dataset;
838 isc_region_t r;
839 isc_stdtime_t now;
840 dst_context_t *ctx = NULL;
841 isc_mem_t *mctx;
842 isc_result_t result;
843 isc_boolean_t signeedsfree = ISC_TRUE;
845 REQUIRE(msg != NULL);
846 REQUIRE(key != NULL);
848 if (is_response(msg))
849 REQUIRE(msg->query.base != NULL);
851 mctx = msg->mctx;
853 memset(&sig, 0, sizeof(sig));
855 sig.mctx = mctx;
856 sig.common.rdclass = dns_rdataclass_any;
857 sig.common.rdtype = dns_rdatatype_sig; /* SIG(0) */
858 ISC_LINK_INIT(&sig.common, link);
860 sig.covered = 0;
861 sig.algorithm = dst_key_alg(key);
862 sig.labels = 0; /* the root name */
863 sig.originalttl = 0;
865 isc_stdtime_get(&now);
866 sig.timesigned = now - DNS_TSIG_FUDGE;
867 sig.timeexpire = now + DNS_TSIG_FUDGE;
869 sig.keyid = dst_key_id(key);
871 dns_name_init(&sig.signer, NULL);
872 dns_name_clone(dst_key_name(key), &sig.signer);
874 sig.siglen = 0;
875 sig.signature = NULL;
877 isc_buffer_init(&databuf, data, sizeof(data));
879 RETERR(dst_context_create3(key, mctx,
880 DNS_LOGCATEGORY_DNSSEC, ISC_TRUE, &ctx));
883 * Digest the fields of the SIG - we can cheat and use
884 * dns_rdata_fromstruct. Since siglen is 0, the digested data
885 * is identical to dns format.
887 RETERR(dns_rdata_fromstruct(NULL, dns_rdataclass_any,
888 dns_rdatatype_sig /* SIG(0) */,
889 &sig, &databuf));
890 isc_buffer_usedregion(&databuf, &r);
891 RETERR(dst_context_adddata(ctx, &r));
894 * If this is a response, digest the query.
896 if (is_response(msg))
897 RETERR(dst_context_adddata(ctx, &msg->query));
900 * Digest the header.
902 isc_buffer_init(&headerbuf, header, sizeof(header));
903 dns_message_renderheader(msg, &headerbuf);
904 isc_buffer_usedregion(&headerbuf, &r);
905 RETERR(dst_context_adddata(ctx, &r));
908 * Digest the remainder of the message.
910 isc_buffer_usedregion(msg->buffer, &r);
911 isc_region_consume(&r, DNS_MESSAGE_HEADERLEN);
912 RETERR(dst_context_adddata(ctx, &r));
914 RETERR(dst_key_sigsize(key, &sigsize));
915 sig.siglen = sigsize;
916 sig.signature = (unsigned char *) isc_mem_get(mctx, sig.siglen);
917 if (sig.signature == NULL) {
918 result = ISC_R_NOMEMORY;
919 goto failure;
922 isc_buffer_init(&sigbuf, sig.signature, sig.siglen);
923 RETERR(dst_context_sign(ctx, &sigbuf));
924 dst_context_destroy(&ctx);
926 rdata = NULL;
927 RETERR(dns_message_gettemprdata(msg, &rdata));
928 RETERR(isc_buffer_allocate(msg->mctx, &dynbuf, 1024));
929 RETERR(dns_rdata_fromstruct(rdata, dns_rdataclass_any,
930 dns_rdatatype_sig /* SIG(0) */,
931 &sig, dynbuf));
933 isc_mem_put(mctx, sig.signature, sig.siglen);
934 signeedsfree = ISC_FALSE;
936 dns_message_takebuffer(msg, &dynbuf);
938 datalist = NULL;
939 RETERR(dns_message_gettemprdatalist(msg, &datalist));
940 datalist->rdclass = dns_rdataclass_any;
941 datalist->type = dns_rdatatype_sig; /* SIG(0) */
942 datalist->covers = 0;
943 datalist->ttl = 0;
944 ISC_LIST_INIT(datalist->rdata);
945 ISC_LIST_APPEND(datalist->rdata, rdata, link);
946 dataset = NULL;
947 RETERR(dns_message_gettemprdataset(msg, &dataset));
948 RUNTIME_CHECK(dns_rdatalist_tordataset(datalist, dataset) == ISC_R_SUCCESS);
949 msg->sig0 = dataset;
951 return (ISC_R_SUCCESS);
953 failure:
954 if (dynbuf != NULL)
955 isc_buffer_free(&dynbuf);
956 if (signeedsfree)
957 isc_mem_put(mctx, sig.signature, sig.siglen);
958 if (ctx != NULL)
959 dst_context_destroy(&ctx);
961 return (result);
964 isc_result_t
965 dns_dnssec_verifymessage(isc_buffer_t *source, dns_message_t *msg,
966 dst_key_t *key)
968 dns_rdata_sig_t sig; /* SIG(0) */
969 unsigned char header[DNS_MESSAGE_HEADERLEN];
970 dns_rdata_t rdata = DNS_RDATA_INIT;
971 isc_region_t r, source_r, sig_r, header_r;
972 isc_stdtime_t now;
973 dst_context_t *ctx = NULL;
974 isc_mem_t *mctx;
975 isc_result_t result;
976 isc_uint16_t addcount;
977 isc_boolean_t signeedsfree = ISC_FALSE;
979 REQUIRE(source != NULL);
980 REQUIRE(msg != NULL);
981 REQUIRE(key != NULL);
983 mctx = msg->mctx;
985 msg->verify_attempted = 1;
987 if (is_response(msg)) {
988 if (msg->query.base == NULL)
989 return (DNS_R_UNEXPECTEDTSIG);
992 isc_buffer_usedregion(source, &source_r);
994 RETERR(dns_rdataset_first(msg->sig0));
995 dns_rdataset_current(msg->sig0, &rdata);
997 RETERR(dns_rdata_tostruct(&rdata, &sig, NULL));
998 signeedsfree = ISC_TRUE;
1000 if (sig.labels != 0) {
1001 result = DNS_R_SIGINVALID;
1002 goto failure;
1005 if (isc_serial_lt(sig.timeexpire, sig.timesigned)) {
1006 result = DNS_R_SIGINVALID;
1007 msg->sig0status = dns_tsigerror_badtime;
1008 goto failure;
1011 isc_stdtime_get(&now);
1012 if (isc_serial_lt((isc_uint32_t)now, sig.timesigned)) {
1013 result = DNS_R_SIGFUTURE;
1014 msg->sig0status = dns_tsigerror_badtime;
1015 goto failure;
1017 else if (isc_serial_lt(sig.timeexpire, (isc_uint32_t)now)) {
1018 result = DNS_R_SIGEXPIRED;
1019 msg->sig0status = dns_tsigerror_badtime;
1020 goto failure;
1023 if (!dns_name_equal(dst_key_name(key), &sig.signer)) {
1024 result = DNS_R_SIGINVALID;
1025 msg->sig0status = dns_tsigerror_badkey;
1026 goto failure;
1029 RETERR(dst_context_create3(key, mctx,
1030 DNS_LOGCATEGORY_DNSSEC, ISC_FALSE, &ctx));
1033 * Digest the SIG(0) record, except for the signature.
1035 dns_rdata_toregion(&rdata, &r);
1036 r.length -= sig.siglen;
1037 RETERR(dst_context_adddata(ctx, &r));
1040 * If this is a response, digest the query.
1042 if (is_response(msg))
1043 RETERR(dst_context_adddata(ctx, &msg->query));
1046 * Extract the header.
1048 memmove(header, source_r.base, DNS_MESSAGE_HEADERLEN);
1051 * Decrement the additional field counter.
1053 memmove(&addcount, &header[DNS_MESSAGE_HEADERLEN - 2], 2);
1054 addcount = htons((isc_uint16_t)(ntohs(addcount) - 1));
1055 memmove(&header[DNS_MESSAGE_HEADERLEN - 2], &addcount, 2);
1058 * Digest the modified header.
1060 header_r.base = (unsigned char *) header;
1061 header_r.length = DNS_MESSAGE_HEADERLEN;
1062 RETERR(dst_context_adddata(ctx, &header_r));
1065 * Digest all non-SIG(0) records.
1067 r.base = source_r.base + DNS_MESSAGE_HEADERLEN;
1068 r.length = msg->sigstart - DNS_MESSAGE_HEADERLEN;
1069 RETERR(dst_context_adddata(ctx, &r));
1071 sig_r.base = sig.signature;
1072 sig_r.length = sig.siglen;
1073 result = dst_context_verify(ctx, &sig_r);
1074 if (result != ISC_R_SUCCESS) {
1075 msg->sig0status = dns_tsigerror_badsig;
1076 goto failure;
1079 msg->verified_sig = 1;
1081 dst_context_destroy(&ctx);
1082 dns_rdata_freestruct(&sig);
1084 return (ISC_R_SUCCESS);
1086 failure:
1087 if (signeedsfree)
1088 dns_rdata_freestruct(&sig);
1089 if (ctx != NULL)
1090 dst_context_destroy(&ctx);
1092 return (result);
1096 * Does this key ('rdata') self sign the rrset ('rdataset')?
1098 isc_boolean_t
1099 dns_dnssec_selfsigns(dns_rdata_t *rdata, dns_name_t *name,
1100 dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
1101 isc_boolean_t ignoretime, isc_mem_t *mctx)
1103 INSIST(rdataset->type == dns_rdatatype_key ||
1104 rdataset->type == dns_rdatatype_dnskey);
1105 if (rdataset->type == dns_rdatatype_key) {
1106 INSIST(sigrdataset->type == dns_rdatatype_sig);
1107 INSIST(sigrdataset->covers == dns_rdatatype_key);
1108 } else {
1109 INSIST(sigrdataset->type == dns_rdatatype_rrsig);
1110 INSIST(sigrdataset->covers == dns_rdatatype_dnskey);
1113 return (dns_dnssec_signs(rdata, name, rdataset, sigrdataset,
1114 ignoretime, mctx));
1118 isc_boolean_t
1119 dns_dnssec_signs(dns_rdata_t *rdata, dns_name_t *name,
1120 dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
1121 isc_boolean_t ignoretime, isc_mem_t *mctx)
1123 dst_key_t *dstkey = NULL;
1124 dns_keytag_t keytag;
1125 dns_rdata_dnskey_t key;
1126 dns_rdata_rrsig_t sig;
1127 dns_rdata_t sigrdata = DNS_RDATA_INIT;
1128 isc_result_t result;
1130 INSIST(sigrdataset->type == dns_rdatatype_rrsig);
1131 if (sigrdataset->covers != rdataset->type)
1132 return (ISC_FALSE);
1134 result = dns_dnssec_keyfromrdata(name, rdata, mctx, &dstkey);
1135 if (result != ISC_R_SUCCESS)
1136 return (ISC_FALSE);
1137 result = dns_rdata_tostruct(rdata, &key, NULL);
1138 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1140 keytag = dst_key_id(dstkey);
1141 for (result = dns_rdataset_first(sigrdataset);
1142 result == ISC_R_SUCCESS;
1143 result = dns_rdataset_next(sigrdataset))
1145 dns_rdata_reset(&sigrdata);
1146 dns_rdataset_current(sigrdataset, &sigrdata);
1147 result = dns_rdata_tostruct(&sigrdata, &sig, NULL);
1148 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1150 if (sig.algorithm == key.algorithm &&
1151 sig.keyid == keytag) {
1152 result = dns_dnssec_verify2(name, rdataset, dstkey,
1153 ignoretime, mctx,
1154 &sigrdata, NULL);
1155 if (result == ISC_R_SUCCESS) {
1156 dst_key_free(&dstkey);
1157 return (ISC_TRUE);
1161 dst_key_free(&dstkey);
1162 return (ISC_FALSE);
1165 isc_result_t
1166 dns_dnsseckey_create(isc_mem_t *mctx, dst_key_t **dstkey,
1167 dns_dnsseckey_t **dkp)
1169 isc_result_t result;
1170 dns_dnsseckey_t *dk;
1171 int major, minor;
1173 REQUIRE(dkp != NULL && *dkp == NULL);
1174 dk = isc_mem_get(mctx, sizeof(dns_dnsseckey_t));
1175 if (dk == NULL)
1176 return (ISC_R_NOMEMORY);
1178 dk->key = *dstkey;
1179 *dstkey = NULL;
1180 dk->force_publish = ISC_FALSE;
1181 dk->force_sign = ISC_FALSE;
1182 dk->hint_publish = ISC_FALSE;
1183 dk->hint_sign = ISC_FALSE;
1184 dk->hint_remove = ISC_FALSE;
1185 dk->first_sign = ISC_FALSE;
1186 dk->is_active = ISC_FALSE;
1187 dk->prepublish = 0;
1188 dk->source = dns_keysource_unknown;
1189 dk->index = 0;
1191 /* KSK or ZSK? */
1192 dk->ksk = ISC_TF((dst_key_flags(dk->key) & DNS_KEYFLAG_KSK) != 0);
1194 /* Is this an old-style key? */
1195 result = dst_key_getprivateformat(dk->key, &major, &minor);
1196 INSIST(result == ISC_R_SUCCESS);
1198 /* Smart signing started with key format 1.3 */
1199 dk->legacy = ISC_TF(major == 1 && minor <= 2);
1201 ISC_LINK_INIT(dk, link);
1202 *dkp = dk;
1203 return (ISC_R_SUCCESS);
1206 void
1207 dns_dnsseckey_destroy(isc_mem_t *mctx, dns_dnsseckey_t **dkp) {
1208 dns_dnsseckey_t *dk;
1210 REQUIRE(dkp != NULL && *dkp != NULL);
1211 dk = *dkp;
1212 if (dk->key != NULL)
1213 dst_key_free(&dk->key);
1214 isc_mem_put(mctx, dk, sizeof(dns_dnsseckey_t));
1215 *dkp = NULL;
1218 static void
1219 get_hints(dns_dnsseckey_t *key, isc_stdtime_t now) {
1220 isc_result_t result;
1221 isc_stdtime_t publish, active, revoke, inactive, delete;
1222 isc_boolean_t pubset = ISC_FALSE, actset = ISC_FALSE;
1223 isc_boolean_t revset = ISC_FALSE, inactset = ISC_FALSE;
1224 isc_boolean_t delset = ISC_FALSE;
1226 REQUIRE(key != NULL && key->key != NULL);
1228 result = dst_key_gettime(key->key, DST_TIME_PUBLISH, &publish);
1229 if (result == ISC_R_SUCCESS)
1230 pubset = ISC_TRUE;
1232 result = dst_key_gettime(key->key, DST_TIME_ACTIVATE, &active);
1233 if (result == ISC_R_SUCCESS)
1234 actset = ISC_TRUE;
1236 result = dst_key_gettime(key->key, DST_TIME_REVOKE, &revoke);
1237 if (result == ISC_R_SUCCESS)
1238 revset = ISC_TRUE;
1240 result = dst_key_gettime(key->key, DST_TIME_INACTIVE, &inactive);
1241 if (result == ISC_R_SUCCESS)
1242 inactset = ISC_TRUE;
1244 result = dst_key_gettime(key->key, DST_TIME_DELETE, &delete);
1245 if (result == ISC_R_SUCCESS)
1246 delset = ISC_TRUE;
1248 /* Metadata says publish (but possibly not activate) */
1249 if (pubset && publish <= now)
1250 key->hint_publish = ISC_TRUE;
1252 /* Metadata says activate (so we must also publish) */
1253 if (actset && active <= now) {
1254 key->hint_sign = ISC_TRUE;
1256 /* Only publish if publish time has already passed. */
1257 if (pubset && publish <= now)
1258 key->hint_publish = ISC_TRUE;
1262 * Activation date is set (maybe in the future), but
1263 * publication date isn't. Most likely the user wants to
1264 * publish now and activate later.
1266 if (actset && !pubset)
1267 key->hint_publish = ISC_TRUE;
1270 * If activation date is in the future, make note of how far off
1272 if (key->hint_publish && actset && active > now) {
1273 key->prepublish = active - now;
1277 * Key has been marked inactive: we can continue publishing,
1278 * but don't sign.
1280 if (key->hint_publish && inactset && inactive <= now) {
1281 key->hint_sign = ISC_FALSE;
1285 * Metadata says revoke. If the key is published,
1286 * we *have to* sign with it per RFC5011--even if it was
1287 * not active before.
1289 * If it hasn't already been done, we should also revoke it now.
1291 if (key->hint_publish && (revset && revoke <= now)) {
1292 isc_uint32_t flags;
1293 key->hint_sign = ISC_TRUE;
1294 flags = dst_key_flags(key->key);
1295 if ((flags & DNS_KEYFLAG_REVOKE) == 0) {
1296 flags |= DNS_KEYFLAG_REVOKE;
1297 dst_key_setflags(key->key, flags);
1302 * Metadata says delete, so don't publish this key or sign with it.
1304 if (delset && delete <= now) {
1305 key->hint_publish = ISC_FALSE;
1306 key->hint_sign = ISC_FALSE;
1307 key->hint_remove = ISC_TRUE;
1312 * Get a list of DNSSEC keys from the key repository
1314 isc_result_t
1315 dns_dnssec_findmatchingkeys(dns_name_t *origin, const char *directory,
1316 isc_mem_t *mctx, dns_dnsseckeylist_t *keylist)
1318 isc_result_t result = ISC_R_SUCCESS;
1319 isc_boolean_t dir_open = ISC_FALSE;
1320 dns_dnsseckeylist_t list;
1321 isc_dir_t dir;
1322 dns_dnsseckey_t *key = NULL;
1323 dst_key_t *dstkey = NULL;
1324 char namebuf[DNS_NAME_FORMATSIZE];
1325 isc_buffer_t b;
1326 unsigned int len, i;
1327 isc_stdtime_t now;
1329 REQUIRE(keylist != NULL);
1330 ISC_LIST_INIT(list);
1331 isc_dir_init(&dir);
1333 isc_buffer_init(&b, namebuf, sizeof(namebuf) - 1);
1334 RETERR(dns_name_tofilenametext(origin, ISC_FALSE, &b));
1335 len = isc_buffer_usedlength(&b);
1336 namebuf[len] = '\0';
1338 if (directory == NULL)
1339 directory = ".";
1340 RETERR(isc_dir_open(&dir, directory));
1341 dir_open = ISC_TRUE;
1343 isc_stdtime_get(&now);
1345 while (isc_dir_read(&dir) == ISC_R_SUCCESS) {
1346 if (dir.entry.name[0] != 'K' ||
1347 dir.entry.length < len + 1 ||
1348 dir.entry.name[len + 1] != '+' ||
1349 strncasecmp(dir.entry.name + 1, namebuf, len) != 0)
1350 continue;
1352 for (i = len + 1 + 1; i < dir.entry.length ; i++)
1353 if (dir.entry.name[i] < '0' || dir.entry.name[i] > '9')
1354 break;
1356 if (i == len + 1 + 1 || i >= dir.entry.length ||
1357 dir.entry.name[i] != '+')
1358 continue;
1360 for (i++ ; i < dir.entry.length ; i++)
1361 if (dir.entry.name[i] < '0' || dir.entry.name[i] > '9')
1362 break;
1364 if (strcmp(dir.entry.name + i, ".private") != 0)
1365 continue;
1367 dstkey = NULL;
1368 result = dst_key_fromnamedfile(dir.entry.name,
1369 directory,
1370 DST_TYPE_PUBLIC |
1371 DST_TYPE_PRIVATE,
1372 mctx, &dstkey);
1374 if (result != ISC_R_SUCCESS) {
1375 isc_log_write(dns_lctx,
1376 DNS_LOGCATEGORY_GENERAL,
1377 DNS_LOGMODULE_DNSSEC,
1378 ISC_LOG_WARNING,
1379 "dns_dnssec_findmatchingkeys: "
1380 "error reading key file %s: %s",
1381 dir.entry.name,
1382 isc_result_totext(result));
1383 continue;
1386 RETERR(dns_dnsseckey_create(mctx, &dstkey, &key));
1387 key->source = dns_keysource_repository;
1388 get_hints(key, now);
1390 if (key->legacy) {
1391 dns_dnsseckey_destroy(mctx, &key);
1392 } else {
1393 ISC_LIST_APPEND(list, key, link);
1394 key = NULL;
1398 if (!ISC_LIST_EMPTY(list)) {
1399 result = ISC_R_SUCCESS;
1400 ISC_LIST_APPENDLIST(*keylist, list, link);
1401 } else
1402 result = ISC_R_NOTFOUND;
1404 failure:
1405 if (dir_open)
1406 isc_dir_close(&dir);
1407 INSIST(key == NULL);
1408 while ((key = ISC_LIST_HEAD(list)) != NULL) {
1409 ISC_LIST_UNLINK(list, key, link);
1410 INSIST(key->key != NULL);
1411 dst_key_free(&key->key);
1412 dns_dnsseckey_destroy(mctx, &key);
1414 if (dstkey != NULL)
1415 dst_key_free(&dstkey);
1416 return (result);
1420 * Add 'newkey' to 'keylist' if it's not already there.
1422 * If 'savekeys' is ISC_TRUE, then we need to preserve all
1423 * the keys in the keyset, regardless of whether they have
1424 * metadata indicating they should be deactivated or removed.
1426 static isc_result_t
1427 addkey(dns_dnsseckeylist_t *keylist, dst_key_t **newkey,
1428 isc_boolean_t savekeys, isc_mem_t *mctx)
1430 dns_dnsseckey_t *key;
1431 isc_result_t result;
1433 /* Skip duplicates */
1434 for (key = ISC_LIST_HEAD(*keylist);
1435 key != NULL;
1436 key = ISC_LIST_NEXT(key, link)) {
1437 if (dst_key_id(key->key) == dst_key_id(*newkey) &&
1438 dst_key_alg(key->key) == dst_key_alg(*newkey) &&
1439 dns_name_equal(dst_key_name(key->key),
1440 dst_key_name(*newkey)))
1441 break;
1444 if (key != NULL) {
1446 * Found a match. If the old key was only public and the
1447 * new key is private, replace the old one; otherwise
1448 * leave it. But either way, mark the key as having
1449 * been found in the zone.
1451 if (dst_key_isprivate(key->key)) {
1452 dst_key_free(newkey);
1453 } else if (dst_key_isprivate(*newkey)) {
1454 dst_key_free(&key->key);
1455 key->key = *newkey;
1458 key->source = dns_keysource_zoneapex;
1459 return (ISC_R_SUCCESS);
1462 result = dns_dnsseckey_create(mctx, newkey, &key);
1463 if (result != ISC_R_SUCCESS)
1464 return (result);
1465 if (key->legacy || savekeys) {
1466 key->force_publish = ISC_TRUE;
1467 key->force_sign = dst_key_isprivate(key->key);
1469 key->source = dns_keysource_zoneapex;
1470 ISC_LIST_APPEND(*keylist, key, link);
1471 *newkey = NULL;
1472 return (ISC_R_SUCCESS);
1477 * Mark all keys which signed the DNSKEY/SOA RRsets as "active",
1478 * for future reference.
1480 static isc_result_t
1481 mark_active_keys(dns_dnsseckeylist_t *keylist, dns_rdataset_t *rrsigs) {
1482 isc_result_t result = ISC_R_SUCCESS;
1483 dns_rdata_t rdata = DNS_RDATA_INIT;
1484 dns_rdataset_t sigs;
1485 dns_dnsseckey_t *key;
1487 REQUIRE(rrsigs != NULL && dns_rdataset_isassociated(rrsigs));
1489 dns_rdataset_init(&sigs);
1490 dns_rdataset_clone(rrsigs, &sigs);
1491 for (key = ISC_LIST_HEAD(*keylist);
1492 key != NULL;
1493 key = ISC_LIST_NEXT(key, link)) {
1494 isc_uint16_t keyid, sigid;
1495 dns_secalg_t keyalg, sigalg;
1496 keyid = dst_key_id(key->key);
1497 keyalg = dst_key_alg(key->key);
1499 for (result = dns_rdataset_first(&sigs);
1500 result == ISC_R_SUCCESS;
1501 result = dns_rdataset_next(&sigs)) {
1502 dns_rdata_rrsig_t sig;
1504 dns_rdata_reset(&rdata);
1505 dns_rdataset_current(&sigs, &rdata);
1506 result = dns_rdata_tostruct(&rdata, &sig, NULL);
1507 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1508 sigalg = sig.algorithm;
1509 sigid = sig.keyid;
1510 if (keyid == sigid && keyalg == sigalg) {
1511 key->is_active = ISC_TRUE;
1512 break;
1517 if (result == ISC_R_NOMORE)
1518 result = ISC_R_SUCCESS;
1520 if (dns_rdataset_isassociated(&sigs))
1521 dns_rdataset_disassociate(&sigs);
1522 return (result);
1526 * Add the contents of a DNSKEY rdataset 'keyset' to 'keylist'.
1528 isc_result_t
1529 dns_dnssec_keylistfromrdataset(dns_name_t *origin,
1530 const char *directory, isc_mem_t *mctx,
1531 dns_rdataset_t *keyset, dns_rdataset_t *keysigs,
1532 dns_rdataset_t *soasigs, isc_boolean_t savekeys,
1533 isc_boolean_t publickey,
1534 dns_dnsseckeylist_t *keylist)
1536 dns_rdataset_t keys;
1537 dns_rdata_t rdata = DNS_RDATA_INIT;
1538 dst_key_t *pubkey = NULL, *privkey = NULL;
1539 isc_result_t result;
1541 REQUIRE(keyset != NULL && dns_rdataset_isassociated(keyset));
1543 dns_rdataset_init(&keys);
1545 dns_rdataset_clone(keyset, &keys);
1546 for (result = dns_rdataset_first(&keys);
1547 result == ISC_R_SUCCESS;
1548 result = dns_rdataset_next(&keys)) {
1549 dns_rdata_reset(&rdata);
1550 dns_rdataset_current(&keys, &rdata);
1551 RETERR(dns_dnssec_keyfromrdata(origin, &rdata, mctx, &pubkey));
1552 dst_key_setttl(pubkey, keys.ttl);
1554 if (!is_zone_key(pubkey) ||
1555 (dst_key_flags(pubkey) & DNS_KEYTYPE_NOAUTH) != 0)
1556 goto skip;
1558 /* Corrupted .key file? */
1559 if (!dns_name_equal(origin, dst_key_name(pubkey)))
1560 goto skip;
1562 if (publickey) {
1563 RETERR(addkey(keylist, &pubkey, savekeys, mctx));
1564 goto skip;
1567 result = dst_key_fromfile(dst_key_name(pubkey),
1568 dst_key_id(pubkey),
1569 dst_key_alg(pubkey),
1570 DST_TYPE_PUBLIC|DST_TYPE_PRIVATE,
1571 directory, mctx, &privkey);
1574 * If the key was revoked and the private file
1575 * doesn't exist, maybe it was revoked internally
1576 * by named. Try loading the unrevoked version.
1578 if (result == ISC_R_FILENOTFOUND) {
1579 isc_uint32_t flags;
1580 flags = dst_key_flags(pubkey);
1581 if ((flags & DNS_KEYFLAG_REVOKE) != 0) {
1582 dst_key_setflags(pubkey,
1583 flags & ~DNS_KEYFLAG_REVOKE);
1584 result = dst_key_fromfile(dst_key_name(pubkey),
1585 dst_key_id(pubkey),
1586 dst_key_alg(pubkey),
1587 DST_TYPE_PUBLIC|
1588 DST_TYPE_PRIVATE,
1589 directory,
1590 mctx, &privkey);
1591 if (result == ISC_R_SUCCESS &&
1592 dst_key_pubcompare(pubkey, privkey,
1593 ISC_FALSE)) {
1594 dst_key_setflags(privkey, flags);
1596 dst_key_setflags(pubkey, flags);
1600 if (result != ISC_R_SUCCESS) {
1601 char keybuf[DNS_NAME_FORMATSIZE];
1602 char algbuf[DNS_SECALG_FORMATSIZE];
1603 dns_name_format(dst_key_name(pubkey), keybuf,
1604 sizeof(keybuf));
1605 dns_secalg_format(dst_key_alg(pubkey), algbuf,
1606 sizeof(algbuf));
1607 isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
1608 DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
1609 "dns_dnssec_keylistfromrdataset: error "
1610 "reading private key file %s/%s/%d: %s",
1611 keybuf, algbuf, dst_key_id(pubkey),
1612 isc_result_totext(result));
1615 if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
1616 RETERR(addkey(keylist, &pubkey, savekeys, mctx));
1617 goto skip;
1619 RETERR(result);
1621 /* This should never happen. */
1622 if ((dst_key_flags(privkey) & DNS_KEYTYPE_NOAUTH) != 0)
1623 goto skip;
1626 * Whatever the key's default TTL may have
1627 * been, the rdataset TTL takes priority.
1629 dst_key_setttl(privkey, dst_key_getttl(pubkey));
1631 RETERR(addkey(keylist, &privkey, savekeys, mctx));
1632 skip:
1633 if (pubkey != NULL)
1634 dst_key_free(&pubkey);
1635 if (privkey != NULL)
1636 dst_key_free(&privkey);
1639 if (result != ISC_R_NOMORE)
1640 RETERR(result);
1642 if (keysigs != NULL && dns_rdataset_isassociated(keysigs))
1643 RETERR(mark_active_keys(keylist, keysigs));
1645 if (soasigs != NULL && dns_rdataset_isassociated(soasigs))
1646 RETERR(mark_active_keys(keylist, soasigs));
1648 result = ISC_R_SUCCESS;
1650 failure:
1651 if (dns_rdataset_isassociated(&keys))
1652 dns_rdataset_disassociate(&keys);
1653 if (pubkey != NULL)
1654 dst_key_free(&pubkey);
1655 if (privkey != NULL)
1656 dst_key_free(&privkey);
1657 return (result);
1660 static isc_result_t
1661 make_dnskey(dst_key_t *key, unsigned char *buf, int bufsize,
1662 dns_rdata_t *target)
1664 isc_result_t result;
1665 isc_buffer_t b;
1666 isc_region_t r;
1668 isc_buffer_init(&b, buf, bufsize);
1669 result = dst_key_todns(key, &b);
1670 if (result != ISC_R_SUCCESS)
1671 return (result);
1673 dns_rdata_reset(target);
1674 isc_buffer_usedregion(&b, &r);
1675 dns_rdata_fromregion(target, dst_key_class(key),
1676 dns_rdatatype_dnskey, &r);
1677 return (ISC_R_SUCCESS);
1680 static isc_result_t
1681 publish_key(dns_diff_t *diff, dns_dnsseckey_t *key, dns_name_t *origin,
1682 dns_ttl_t ttl, isc_mem_t *mctx, isc_boolean_t allzsk,
1683 void (*report)(const char *, ...))
1685 isc_result_t result;
1686 dns_difftuple_t *tuple = NULL;
1687 unsigned char buf[DST_KEY_MAXSIZE];
1688 dns_rdata_t dnskey = DNS_RDATA_INIT;
1689 char alg[80];
1691 dns_rdata_reset(&dnskey);
1692 RETERR(make_dnskey(key->key, buf, sizeof(buf), &dnskey));
1694 dns_secalg_format(dst_key_alg(key->key), alg, sizeof(alg));
1695 report("Fetching %s %d/%s from key %s.",
1696 key->ksk ? (allzsk ? "KSK/ZSK" : "KSK") : "ZSK",
1697 dst_key_id(key->key), alg,
1698 key->source == dns_keysource_user ? "file" : "repository");
1700 if (key->prepublish && ttl > key->prepublish) {
1701 char keystr[DST_KEY_FORMATSIZE];
1702 isc_stdtime_t now;
1704 dst_key_format(key->key, keystr, sizeof(keystr));
1705 report("Key %s: Delaying activation to match the DNSKEY TTL.\n",
1706 keystr, ttl);
1708 isc_stdtime_get(&now);
1709 dst_key_settime(key->key, DST_TIME_ACTIVATE, now + ttl);
1712 /* publish key */
1713 RETERR(dns_difftuple_create(mctx, DNS_DIFFOP_ADD, origin, ttl,
1714 &dnskey, &tuple));
1715 dns_diff_appendminimal(diff, &tuple);
1716 result = ISC_R_SUCCESS;
1718 failure:
1719 return (result);
1722 static isc_result_t
1723 remove_key(dns_diff_t *diff, dns_dnsseckey_t *key, dns_name_t *origin,
1724 dns_ttl_t ttl, isc_mem_t *mctx, const char *reason,
1725 void (*report)(const char *, ...))
1727 isc_result_t result;
1728 dns_difftuple_t *tuple = NULL;
1729 unsigned char buf[DST_KEY_MAXSIZE];
1730 dns_rdata_t dnskey = DNS_RDATA_INIT;
1731 char alg[80];
1733 dns_secalg_format(dst_key_alg(key->key), alg, sizeof(alg));
1734 report("Removing %s key %d/%s from DNSKEY RRset.",
1735 reason, dst_key_id(key->key), alg);
1737 RETERR(make_dnskey(key->key, buf, sizeof(buf), &dnskey));
1738 RETERR(dns_difftuple_create(mctx, DNS_DIFFOP_DEL, origin, ttl, &dnskey,
1739 &tuple));
1740 dns_diff_appendminimal(diff, &tuple);
1741 result = ISC_R_SUCCESS;
1743 failure:
1744 return (result);
1748 * Update 'keys' with information from 'newkeys'.
1750 * If 'removed' is not NULL, any keys that are being removed from
1751 * the zone will be added to the list for post-removal processing.
1753 isc_result_t
1754 dns_dnssec_updatekeys(dns_dnsseckeylist_t *keys, dns_dnsseckeylist_t *newkeys,
1755 dns_dnsseckeylist_t *removed, dns_name_t *origin,
1756 dns_ttl_t hint_ttl, dns_diff_t *diff,
1757 isc_boolean_t allzsk, isc_mem_t *mctx,
1758 void (*report)(const char *, ...))
1760 isc_result_t result;
1761 dns_dnsseckey_t *key, *key1, *key2, *next;
1762 isc_boolean_t found_ttl = ISC_FALSE;
1763 dns_ttl_t ttl = hint_ttl;
1766 * First, look through the existing key list to find keys
1767 * supplied from the command line which are not in the zone.
1768 * Update the zone to include them.
1770 * Also, if there are keys published in the zone already,
1771 * use their TTL for all subsequent published keys.
1773 for (key = ISC_LIST_HEAD(*keys);
1774 key != NULL;
1775 key = ISC_LIST_NEXT(key, link)) {
1776 if (key->source == dns_keysource_user &&
1777 (key->hint_publish || key->force_publish)) {
1778 RETERR(publish_key(diff, key, origin, ttl,
1779 mctx, allzsk, report));
1781 if (key->source == dns_keysource_zoneapex) {
1782 ttl = dst_key_getttl(key->key);
1783 found_ttl = ISC_TRUE;
1788 * If there were no existing keys, use the smallest nonzero
1789 * TTL of the keys found in the repository.
1791 if (!found_ttl && !ISC_LIST_EMPTY(*newkeys)) {
1792 dns_ttl_t shortest = 0;
1794 for (key = ISC_LIST_HEAD(*newkeys);
1795 key != NULL;
1796 key = ISC_LIST_NEXT(key, link)) {
1797 dns_ttl_t thisttl = dst_key_getttl(key->key);
1798 if (thisttl != 0 &&
1799 (shortest == 0 || thisttl < shortest))
1800 shortest = thisttl;
1803 if (shortest != 0)
1804 ttl = shortest;
1808 * Second, scan the list of newly found keys looking for matches
1809 * with known keys, and update accordingly.
1811 for (key1 = ISC_LIST_HEAD(*newkeys); key1 != NULL; key1 = next) {
1812 isc_boolean_t key_revoked = ISC_FALSE;
1814 next = ISC_LIST_NEXT(key1, link);
1816 for (key2 = ISC_LIST_HEAD(*keys);
1817 key2 != NULL;
1818 key2 = ISC_LIST_NEXT(key2, link)) {
1819 int f1 = dst_key_flags(key1->key);
1820 int f2 = dst_key_flags(key2->key);
1821 int nr1 = f1 & ~DNS_KEYFLAG_REVOKE;
1822 int nr2 = f2 & ~DNS_KEYFLAG_REVOKE;
1823 if (nr1 == nr2 &&
1824 dst_key_alg(key1->key) == dst_key_alg(key2->key) &&
1825 dst_key_pubcompare(key1->key, key2->key,
1826 ISC_TRUE)) {
1827 int r1, r2;
1828 r1 = dst_key_flags(key1->key) &
1829 DNS_KEYFLAG_REVOKE;
1830 r2 = dst_key_flags(key2->key) &
1831 DNS_KEYFLAG_REVOKE;
1832 key_revoked = ISC_TF(r1 != r2);
1833 break;
1837 /* No match found in keys; add the new key. */
1838 if (key2 == NULL) {
1839 ISC_LIST_UNLINK(*newkeys, key1, link);
1840 ISC_LIST_APPEND(*keys, key1, link);
1842 if (key1->source != dns_keysource_zoneapex &&
1843 (key1->hint_publish || key1->force_publish)) {
1844 RETERR(publish_key(diff, key1, origin, ttl,
1845 mctx, allzsk, report));
1846 if (key1->hint_sign || key1->force_sign)
1847 key1->first_sign = ISC_TRUE;
1850 continue;
1853 /* Match found: remove or update it as needed */
1854 if (key1->hint_remove) {
1855 RETERR(remove_key(diff, key2, origin, ttl, mctx,
1856 "expired", report));
1857 ISC_LIST_UNLINK(*keys, key2, link);
1858 if (removed != NULL)
1859 ISC_LIST_APPEND(*removed, key2, link);
1860 else
1861 dns_dnsseckey_destroy(mctx, &key2);
1862 } else if (key_revoked &&
1863 (dst_key_flags(key1->key) & DNS_KEYFLAG_REVOKE) != 0) {
1866 * A previously valid key has been revoked.
1867 * We need to remove the old version and pull
1868 * in the new one.
1870 RETERR(remove_key(diff, key2, origin, ttl, mctx,
1871 "revoked", report));
1872 ISC_LIST_UNLINK(*keys, key2, link);
1873 if (removed != NULL)
1874 ISC_LIST_APPEND(*removed, key2, link);
1875 else
1876 dns_dnsseckey_destroy(mctx, &key2);
1878 RETERR(publish_key(diff, key1, origin, ttl,
1879 mctx, allzsk, report));
1880 ISC_LIST_UNLINK(*newkeys, key1, link);
1881 ISC_LIST_APPEND(*keys, key1, link);
1884 * XXX: The revoke flag is only defined for trust
1885 * anchors. Setting the flag on a non-KSK is legal,
1886 * but not defined in any RFC. It seems reasonable
1887 * to treat it the same as a KSK: keep it in the
1888 * zone, sign the DNSKEY set with it, but not
1889 * sign other records with it.
1891 key1->ksk = ISC_TRUE;
1892 continue;
1893 } else {
1894 if (!key2->is_active &&
1895 (key1->hint_sign || key1->force_sign))
1896 key2->first_sign = ISC_TRUE;
1897 key2->hint_sign = key1->hint_sign;
1898 key2->hint_publish = key1->hint_publish;
1902 /* Free any leftover keys in newkeys */
1903 while (!ISC_LIST_EMPTY(*newkeys)) {
1904 key1 = ISC_LIST_HEAD(*newkeys);
1905 ISC_LIST_UNLINK(*newkeys, key1, link);
1906 dns_dnsseckey_destroy(mctx, &key1);
1909 result = ISC_R_SUCCESS;
1911 failure:
1912 return (result);