dnssectool.c revision 1.10 1 /* $NetBSD: dnssectool.c,v 1.10 2024/09/22 00:13:56 christos Exp $ */
2
3 /*
4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5 *
6 * SPDX-License-Identifier: MPL-2.0
7 *
8 * This Source Code Form is subject to the terms of the Mozilla Public
9 * License, v. 2.0. If a copy of the MPL was not distributed with this
10 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
11 *
12 * See the COPYRIGHT file distributed with this work for additional
13 * information regarding copyright ownership.
14 */
15
16 /*! \file */
17
18 /*%
19 * DNSSEC Support Routines.
20 */
21
22 #include <inttypes.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26
27 #include <isc/base32.h>
28 #include <isc/buffer.h>
29 #include <isc/commandline.h>
30 #include <isc/dir.h>
31 #include <isc/file.h>
32 #include <isc/heap.h>
33 #include <isc/list.h>
34 #include <isc/mem.h>
35 #include <isc/print.h>
36 #include <isc/result.h>
37 #include <isc/string.h>
38 #include <isc/time.h>
39 #include <isc/tm.h>
40 #include <isc/util.h>
41
42 #include <dns/db.h>
43 #include <dns/dbiterator.h>
44 #include <dns/dnssec.h>
45 #include <dns/fixedname.h>
46 #include <dns/keyvalues.h>
47 #include <dns/log.h>
48 #include <dns/name.h>
49 #include <dns/nsec.h>
50 #include <dns/nsec3.h>
51 #include <dns/rdataclass.h>
52 #include <dns/rdataset.h>
53 #include <dns/rdatasetiter.h>
54 #include <dns/rdatastruct.h>
55 #include <dns/rdatatype.h>
56 #include <dns/secalg.h>
57 #include <dns/time.h>
58
59 #include "dnssectool.h"
60
61 #define KEYSTATES_NVALUES 4
62 static const char *keystates[KEYSTATES_NVALUES] = {
63 "hidden",
64 "rumoured",
65 "omnipresent",
66 "unretentive",
67 };
68
69 int verbose = 0;
70 bool quiet = false;
71 dns_dsdigest_t dtype[8];
72
73 static fatalcallback_t *fatalcallback = NULL;
74
75 void
76 fatal(const char *format, ...) {
77 va_list args;
78
79 fprintf(stderr, "%s: fatal: ", program);
80 va_start(args, format);
81 vfprintf(stderr, format, args);
82 va_end(args);
83 fprintf(stderr, "\n");
84 if (fatalcallback != NULL) {
85 (*fatalcallback)();
86 }
87 _exit(EXIT_FAILURE);
88 }
89
90 void
91 setfatalcallback(fatalcallback_t *callback) {
92 fatalcallback = callback;
93 }
94
95 void
96 check_result(isc_result_t result, const char *message) {
97 if (result != ISC_R_SUCCESS) {
98 fatal("%s: %s", message, isc_result_totext(result));
99 }
100 }
101
102 void
103 vbprintf(int level, const char *fmt, ...) {
104 va_list ap;
105 if (level > verbose) {
106 return;
107 }
108 va_start(ap, fmt);
109 fprintf(stderr, "%s: ", program);
110 vfprintf(stderr, fmt, ap);
111 va_end(ap);
112 }
113
114 void
115 version(const char *name) {
116 fprintf(stderr, "%s %s\n", name, PACKAGE_VERSION);
117 exit(EXIT_SUCCESS);
118 }
119
120 void
121 sig_format(dns_rdata_rrsig_t *sig, char *cp, unsigned int size) {
122 char namestr[DNS_NAME_FORMATSIZE];
123 char algstr[DNS_NAME_FORMATSIZE];
124
125 dns_name_format(&sig->signer, namestr, sizeof(namestr));
126 dns_secalg_format(sig->algorithm, algstr, sizeof(algstr));
127 snprintf(cp, size, "%s/%s/%d", namestr, algstr, sig->keyid);
128 }
129
130 void
131 setup_logging(isc_mem_t *mctx, isc_log_t **logp) {
132 isc_logdestination_t destination;
133 isc_logconfig_t *logconfig = NULL;
134 isc_log_t *log = NULL;
135 int level;
136
137 if (verbose < 0) {
138 verbose = 0;
139 }
140 switch (verbose) {
141 case 0:
142 /*
143 * We want to see warnings about things like out-of-zone
144 * data in the master file even when not verbose.
145 */
146 level = ISC_LOG_WARNING;
147 break;
148 case 1:
149 level = ISC_LOG_INFO;
150 break;
151 default:
152 level = ISC_LOG_DEBUG(verbose - 2 + 1);
153 break;
154 }
155
156 isc_log_create(mctx, &log, &logconfig);
157 isc_log_setcontext(log);
158 dns_log_init(log);
159 dns_log_setcontext(log);
160 isc_log_settag(logconfig, program);
161
162 /*
163 * Set up a channel similar to default_stderr except:
164 * - the logging level is passed in
165 * - the program name and logging level are printed
166 * - no time stamp is printed
167 */
168 destination.file.stream = stderr;
169 destination.file.name = NULL;
170 destination.file.versions = ISC_LOG_ROLLNEVER;
171 destination.file.maximum_size = 0;
172 isc_log_createchannel(logconfig, "stderr", ISC_LOG_TOFILEDESC, level,
173 &destination,
174 ISC_LOG_PRINTTAG | ISC_LOG_PRINTLEVEL);
175
176 RUNTIME_CHECK(isc_log_usechannel(logconfig, "stderr", NULL, NULL) ==
177 ISC_R_SUCCESS);
178
179 *logp = log;
180 }
181
182 void
183 cleanup_logging(isc_log_t **logp) {
184 isc_log_t *log;
185
186 REQUIRE(logp != NULL);
187
188 log = *logp;
189 *logp = NULL;
190
191 if (log == NULL) {
192 return;
193 }
194
195 isc_log_destroy(&log);
196 isc_log_setcontext(NULL);
197 dns_log_setcontext(NULL);
198 }
199
200 static isc_stdtime_t
201 time_units(isc_stdtime_t offset, char *suffix, const char *str) {
202 switch (suffix[0]) {
203 case 'Y':
204 case 'y':
205 return (offset * (365 * 24 * 3600));
206 case 'M':
207 case 'm':
208 switch (suffix[1]) {
209 case 'O':
210 case 'o':
211 return (offset * (30 * 24 * 3600));
212 case 'I':
213 case 'i':
214 return (offset * 60);
215 case '\0':
216 fatal("'%s' ambiguous: use 'mi' for minutes "
217 "or 'mo' for months",
218 str);
219 default:
220 fatal("time value %s is invalid", str);
221 }
222 UNREACHABLE();
223 break;
224 case 'W':
225 case 'w':
226 return (offset * (7 * 24 * 3600));
227 case 'D':
228 case 'd':
229 return (offset * (24 * 3600));
230 case 'H':
231 case 'h':
232 return (offset * 3600);
233 case 'S':
234 case 's':
235 case '\0':
236 return (offset);
237 default:
238 fatal("time value %s is invalid", str);
239 }
240 UNREACHABLE();
241 return (0); /* silence compiler warning */
242 }
243
244 static bool
245 isnone(const char *str) {
246 return ((strcasecmp(str, "none") == 0) ||
247 (strcasecmp(str, "never") == 0) ||
248 (strcasecmp(str, "unset") == 0));
249 }
250
251 dns_ttl_t
252 strtottl(const char *str) {
253 const char *orig = str;
254 dns_ttl_t ttl;
255 char *endp;
256
257 if (isnone(str)) {
258 return ((dns_ttl_t)0);
259 }
260
261 ttl = strtol(str, &endp, 0);
262 if (ttl == 0 && endp == str) {
263 fatal("TTL must be numeric");
264 }
265 ttl = time_units(ttl, endp, orig);
266 return (ttl);
267 }
268
269 dst_key_state_t
270 strtokeystate(const char *str) {
271 if (isnone(str)) {
272 return (DST_KEY_STATE_NA);
273 }
274
275 for (int i = 0; i < KEYSTATES_NVALUES; i++) {
276 if (keystates[i] != NULL && strcasecmp(str, keystates[i]) == 0)
277 {
278 return ((dst_key_state_t)i);
279 }
280 }
281 fatal("unknown key state %s", str);
282 }
283
284 isc_stdtime_t
285 strtotime(const char *str, int64_t now, int64_t base, bool *setp) {
286 int64_t val, offset;
287 isc_result_t result;
288 const char *orig = str;
289 char *endp;
290 size_t n;
291 struct tm tm;
292
293 if (isnone(str)) {
294 if (setp != NULL) {
295 *setp = false;
296 }
297 return ((isc_stdtime_t)0);
298 }
299
300 if (setp != NULL) {
301 *setp = true;
302 }
303
304 if ((str[0] == '0' || str[0] == '-') && str[1] == '\0') {
305 return ((isc_stdtime_t)0);
306 }
307
308 /*
309 * We accept times in the following formats:
310 * now([+-]offset)
311 * YYYYMMDD([+-]offset)
312 * YYYYMMDDhhmmss([+-]offset)
313 * Day Mon DD HH:MM:SS YYYY([+-]offset)
314 * 1234567890([+-]offset)
315 * [+-]offset
316 */
317 n = strspn(str, "0123456789");
318 if ((n == 8u || n == 14u) &&
319 (str[n] == '\0' || str[n] == '-' || str[n] == '+'))
320 {
321 char timestr[15];
322
323 strlcpy(timestr, str, sizeof(timestr));
324 timestr[n] = 0;
325 if (n == 8u) {
326 strlcat(timestr, "000000", sizeof(timestr));
327 }
328 result = dns_time64_fromtext(timestr, &val);
329 if (result != ISC_R_SUCCESS) {
330 fatal("time value %s is invalid: %s", orig,
331 isc_result_totext(result));
332 }
333 base = val;
334 str += n;
335 } else if (n == 10u &&
336 (str[n] == '\0' || str[n] == '-' || str[n] == '+'))
337 {
338 base = strtoll(str, &endp, 0);
339 str += 10;
340 } else if (strncmp(str, "now", 3) == 0) {
341 base = now;
342 str += 3;
343 } else if (str[0] >= 'A' && str[0] <= 'Z') {
344 /* parse ctime() format as written by `dnssec-settime -p` */
345 endp = isc_tm_strptime(str, "%a %b %d %H:%M:%S %Y", &tm);
346 if (endp != str + 24) {
347 fatal("time value %s is invalid", orig);
348 }
349 base = mktime(&tm);
350 str += 24;
351 }
352
353 if (str[0] == '\0') {
354 return ((isc_stdtime_t)base);
355 } else if (str[0] == '+') {
356 offset = strtol(str + 1, &endp, 0);
357 offset = time_units((isc_stdtime_t)offset, endp, orig);
358 val = base + offset;
359 } else if (str[0] == '-') {
360 offset = strtol(str + 1, &endp, 0);
361 offset = time_units((isc_stdtime_t)offset, endp, orig);
362 val = base - offset;
363 } else {
364 fatal("time value %s is invalid", orig);
365 }
366
367 return ((isc_stdtime_t)val);
368 }
369
370 dns_rdataclass_t
371 strtoclass(const char *str) {
372 isc_textregion_t r;
373 dns_rdataclass_t rdclass;
374 isc_result_t result;
375
376 if (str == NULL) {
377 return (dns_rdataclass_in);
378 }
379 DE_CONST(str, r.base);
380 r.length = strlen(str);
381 result = dns_rdataclass_fromtext(&rdclass, &r);
382 if (result != ISC_R_SUCCESS) {
383 fatal("unknown class %s", str);
384 }
385 return (rdclass);
386 }
387
388 unsigned int
389 strtodsdigest(const char *str) {
390 isc_textregion_t r;
391 dns_dsdigest_t alg;
392 isc_result_t result;
393
394 DE_CONST(str, r.base);
395 r.length = strlen(str);
396 result = dns_dsdigest_fromtext(&alg, &r);
397 if (result != ISC_R_SUCCESS) {
398 fatal("unknown DS algorithm %s", str);
399 }
400 return (alg);
401 }
402
403 static int
404 cmp_dtype(const void *ap, const void *bp) {
405 int a = *(const uint8_t *)ap;
406 int b = *(const uint8_t *)bp;
407 return (a - b);
408 }
409
410 void
411 add_dtype(unsigned int dt) {
412 unsigned i, n;
413
414 /* ensure there is space for a zero terminator */
415 n = sizeof(dtype) / sizeof(dtype[0]) - 1;
416 for (i = 0; i < n; i++) {
417 if (dtype[i] == dt) {
418 return;
419 }
420 if (dtype[i] == 0) {
421 dtype[i] = dt;
422 qsort(dtype, i + 1, 1, cmp_dtype);
423 return;
424 }
425 }
426 fatal("too many -a digest type arguments");
427 }
428
429 isc_result_t
430 try_dir(const char *dirname) {
431 isc_result_t result;
432 isc_dir_t d;
433
434 isc_dir_init(&d);
435 result = isc_dir_open(&d, dirname);
436 if (result == ISC_R_SUCCESS) {
437 isc_dir_close(&d);
438 }
439 return (result);
440 }
441
442 /*
443 * Check private key version compatibility.
444 */
445 void
446 check_keyversion(dst_key_t *key, char *keystr) {
447 int major, minor;
448 dst_key_getprivateformat(key, &major, &minor);
449 INSIST(major <= DST_MAJOR_VERSION); /* invalid private key */
450
451 if (major < DST_MAJOR_VERSION || minor < DST_MINOR_VERSION) {
452 fatal("Key %s has incompatible format version %d.%d, "
453 "use -f to force upgrade to new version.",
454 keystr, major, minor);
455 }
456 if (minor > DST_MINOR_VERSION) {
457 fatal("Key %s has incompatible format version %d.%d, "
458 "use -f to force downgrade to current version.",
459 keystr, major, minor);
460 }
461 }
462
463 void
464 set_keyversion(dst_key_t *key) {
465 int major, minor;
466 dst_key_getprivateformat(key, &major, &minor);
467 INSIST(major <= DST_MAJOR_VERSION);
468
469 if (major != DST_MAJOR_VERSION || minor != DST_MINOR_VERSION) {
470 dst_key_setprivateformat(key, DST_MAJOR_VERSION,
471 DST_MINOR_VERSION);
472 }
473
474 /*
475 * If the key is from a version older than 1.3, set
476 * set the creation date
477 */
478 if (major < 1 || (major == 1 && minor <= 2)) {
479 isc_stdtime_t now;
480 isc_stdtime_get(&now);
481 dst_key_settime(key, DST_TIME_CREATED, now);
482 }
483 }
484
485 bool
486 key_collision(dst_key_t *dstkey, dns_name_t *name, const char *dir,
487 isc_mem_t *mctx, bool *exact) {
488 isc_result_t result;
489 bool conflict = false;
490 dns_dnsseckeylist_t matchkeys;
491 dns_dnsseckey_t *key = NULL;
492 uint16_t id, oldid;
493 uint32_t rid, roldid;
494 dns_secalg_t alg;
495 char filename[NAME_MAX];
496 isc_buffer_t fileb;
497 isc_stdtime_t now;
498
499 if (exact != NULL) {
500 *exact = false;
501 }
502
503 id = dst_key_id(dstkey);
504 rid = dst_key_rid(dstkey);
505 alg = dst_key_alg(dstkey);
506
507 /*
508 * For Diffie Hellman just check if there is a direct collision as
509 * they can't be revoked. Additionally dns_dnssec_findmatchingkeys
510 * only handles DNSKEY which is not used for HMAC.
511 */
512 if (alg == DST_ALG_DH) {
513 isc_buffer_init(&fileb, filename, sizeof(filename));
514 result = dst_key_buildfilename(dstkey, DST_TYPE_PRIVATE, dir,
515 &fileb);
516 if (result != ISC_R_SUCCESS) {
517 return (true);
518 }
519 return (isc_file_exists(filename));
520 }
521
522 ISC_LIST_INIT(matchkeys);
523 isc_stdtime_get(&now);
524 result = dns_dnssec_findmatchingkeys(name, dir, now, mctx, &matchkeys);
525 if (result == ISC_R_NOTFOUND) {
526 return (false);
527 }
528
529 while (!ISC_LIST_EMPTY(matchkeys) && !conflict) {
530 key = ISC_LIST_HEAD(matchkeys);
531 if (dst_key_alg(key->key) != alg) {
532 goto next;
533 }
534
535 oldid = dst_key_id(key->key);
536 roldid = dst_key_rid(key->key);
537
538 if (oldid == rid || roldid == id || id == oldid) {
539 conflict = true;
540 if (id != oldid) {
541 if (verbose > 1) {
542 fprintf(stderr,
543 "Key ID %d could "
544 "collide with %d\n",
545 id, oldid);
546 }
547 } else {
548 if (exact != NULL) {
549 *exact = true;
550 }
551 if (verbose > 1) {
552 fprintf(stderr, "Key ID %d exists\n",
553 id);
554 }
555 }
556 }
557
558 next:
559 ISC_LIST_UNLINK(matchkeys, key, link);
560 dns_dnsseckey_destroy(mctx, &key);
561 }
562
563 /* Finish freeing the list */
564 while (!ISC_LIST_EMPTY(matchkeys)) {
565 key = ISC_LIST_HEAD(matchkeys);
566 ISC_LIST_UNLINK(matchkeys, key, link);
567 dns_dnsseckey_destroy(mctx, &key);
568 }
569
570 return (conflict);
571 }
572
573 bool
574 isoptarg(const char *arg, char **argv, void (*usage)(void)) {
575 if (!strcasecmp(isc_commandline_argument, arg)) {
576 if (argv[isc_commandline_index] == NULL) {
577 fprintf(stderr, "%s: missing argument -%c %s\n",
578 program, isc_commandline_option,
579 isc_commandline_argument);
580 usage();
581 }
582 isc_commandline_argument = argv[isc_commandline_index];
583 /* skip to next argument */
584 isc_commandline_index++;
585 return (true);
586 }
587 return (false);
588 }
589