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