xref: /freebsd/contrib/unbound/smallapp/unbound-host.c (revision 19261079b74319502c6ffa1249920079f0f69a72)
1 /*
2  * smallapp/unbound-host.c - replacement for host that supports validation.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file performs functionality like 'host', and also supports validation.
40  * It uses the libunbound library.
41  */
42 
43 #include "config.h"
44 #ifdef HAVE_GETOPT_H
45 #include <getopt.h>
46 #endif
47 /* remove alloc checks, not in this part of the code */
48 #ifdef UNBOUND_ALLOC_STATS
49 #undef malloc
50 #undef calloc
51 #undef free
52 #undef realloc
53 #endif
54 #ifdef UNBOUND_ALLOC_LITE
55 #undef malloc
56 #undef calloc
57 #undef free
58 #undef realloc
59 #undef strdup
60 #define unbound_lite_wrapstr(s) s
61 #endif
62 #include "libunbound/unbound.h"
63 #include "sldns/rrdef.h"
64 #include "sldns/wire2str.h"
65 #ifdef HAVE_NSS
66 /* nss3 */
67 #include "nss.h"
68 #endif
69 #ifdef HAVE_SSL
70 #ifdef HAVE_OPENSSL_SSL_H
71 #include <openssl/ssl.h>
72 #endif
73 #ifdef HAVE_OPENSSL_ERR_H
74 #include <openssl/err.h>
75 #endif
76 #endif /* HAVE_SSL */
77 
78 /** verbosity for unbound-host app */
79 static int verb = 0;
80 
81 /** Give unbound-host usage, and exit (1). */
82 static void
83 usage(void)
84 {
85 	printf("Usage:	unbound-host [-C configfile] [-vdhr46] [-c class] [-t type]\n");
86 	printf("                     [-y key] [-f keyfile] [-F namedkeyfile] hostname\n");
87 	printf("  Queries the DNS for information.\n");
88 	printf("  The hostname is looked up for IP4, IP6 and mail.\n");
89 	printf("  If an ip-address is given a reverse lookup is done.\n");
90 	printf("  Use the -v option to see DNSSEC security information.\n");
91 	printf("    -t type		what type to look for.\n");
92 	printf("    -c class		what class to look for, if not class IN.\n");
93 	printf("    -y 'keystring'	specify trust anchor, DS or DNSKEY, like\n");
94 	printf("			-y 'example.com DS 31560 5 1 1CFED8478...'\n");
95 	printf("    -D			DNSSEC enable with default root anchor\n");
96 	printf("    			from %s\n", ROOT_ANCHOR_FILE);
97 	printf("    -f keyfile		read trust anchors from file, with lines as -y.\n");
98 	printf("    -F keyfile		read named.conf-style trust anchors.\n");
99 	printf("    -C config		use the specified unbound.conf (none read by default)\n");
100 	printf("			pass as first argument if you want to override some\n");
101 	printf("			options with further arguments\n");
102 	printf("    -r			read forwarder information from /etc/resolv.conf\n");
103 	printf("      			breaks validation if the forwarder does not do DNSSEC.\n");
104 	printf("    -v			be more verbose, shows nodata and security.\n");
105 	printf("    -d			debug, traces the action, -d -d shows more.\n");
106 	printf("    -4			use ipv4 network, avoid ipv6.\n");
107 	printf("    -6			use ipv6 network, avoid ipv4.\n");
108 	printf("    -h			show this usage help.\n");
109 	printf("Version %s\n", PACKAGE_VERSION);
110 	printf("BSD licensed, see LICENSE in source package for details.\n");
111 	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
112 	exit(1);
113 }
114 
115 /** determine if str is ip4 and put into reverse lookup format */
116 static int
117 isip4(const char* nm, char** res)
118 {
119 	struct in_addr addr;
120 	/* ddd.ddd.ddd.ddd.in-addr.arpa. is less than 32 */
121 	char buf[32];
122 	if(inet_pton(AF_INET, nm, &addr) <= 0) {
123 		return 0;
124 	}
125 	snprintf(buf, sizeof(buf), "%u.%u.%u.%u.in-addr.arpa",
126 		(unsigned)((uint8_t*)&addr)[3], (unsigned)((uint8_t*)&addr)[2],
127 		(unsigned)((uint8_t*)&addr)[1], (unsigned)((uint8_t*)&addr)[0]);
128 	*res = strdup(buf);
129 	return 1;
130 }
131 
132 /** determine if str is ip6 and put into reverse lookup format */
133 static int
134 isip6(const char* nm, char** res)
135 {
136 	struct in6_addr addr;
137 	/* [nibble.]{32}.ip6.arpa. is less than 128 */
138 	const char* hex = "0123456789abcdef";
139 	char buf[128];
140 	char *p;
141 	int i;
142 	if(inet_pton(AF_INET6, nm, &addr) <= 0) {
143 		return 0;
144 	}
145 	p = buf;
146 	for(i=15; i>=0; i--) {
147 		uint8_t b = ((uint8_t*)&addr)[i];
148 		*p++ = hex[ (b&0x0f) ];
149 		*p++ = '.';
150 		*p++ = hex[ (b&0xf0) >> 4 ];
151 		*p++ = '.';
152 	}
153 	snprintf(buf+16*4, sizeof(buf)-16*4, "ip6.arpa");
154 	*res = strdup(buf);
155 	if(!*res) {
156 		fprintf(stderr, "error: out of memory\n");
157 		exit(1);
158 	}
159 	return 1;
160 }
161 
162 /** massage input name */
163 static char*
164 massage_qname(const char* nm, int* reverse)
165 {
166 	/* recognise IP4 and IP6, create reverse addresses if needed */
167 	char* res;
168 	if(isip4(nm, &res)) {
169 		*reverse = 1;
170 	} else if(isip6(nm, &res)) {
171 		*reverse = 1;
172 	} else {
173 		res = strdup(nm);
174 	}
175 	if(!res) {
176 		fprintf(stderr, "error: out of memory\n");
177 		exit(1);
178 	}
179 	return res;
180 }
181 
182 /** massage input type */
183 static int
184 massage_type(const char* t, int reverse, int* multi)
185 {
186 	if(t) {
187 		int r = sldns_get_rr_type_by_name(t);
188 		if(r == 0 && strcasecmp(t, "TYPE0") != 0 &&
189 			strcmp(t, "") != 0) {
190 			fprintf(stderr, "error unknown type %s\n", t);
191 			exit(1);
192 		}
193 		return r;
194 	}
195 	if(!t && reverse)
196 		return LDNS_RR_TYPE_PTR;
197 	*multi = 1;
198 	return LDNS_RR_TYPE_A;
199 }
200 
201 /** massage input class */
202 static int
203 massage_class(const char* c)
204 {
205 	if(c) {
206 		int r = sldns_get_rr_class_by_name(c);
207 		if(r == 0 && strcasecmp(c, "CLASS0") != 0 &&
208 			strcmp(c, "") != 0) {
209 			fprintf(stderr, "error unknown class %s\n", c);
210 			exit(1);
211 		}
212 		return r;
213 	}
214 	return LDNS_RR_CLASS_IN;
215 }
216 
217 /** nice security status string */
218 static const char*
219 secure_str(struct ub_result* result)
220 {
221 	if(result->rcode != 0 && result->rcode != 3) return "(error)";
222 	if(result->secure) return "(secure)";
223 	if(result->bogus) return "(BOGUS (security failure))";
224 	return "(insecure)";
225 }
226 
227 /** nice string for type */
228 static void
229 pretty_type(char* s, size_t len, int t)
230 {
231 	char d[16];
232 	sldns_wire2str_type_buf((uint16_t)t, d, sizeof(d));
233 	snprintf(s, len, "%s", d);
234 }
235 
236 /** nice string for class */
237 static void
238 pretty_class(char* s, size_t len, int c)
239 {
240 	char d[16];
241 	sldns_wire2str_class_buf((uint16_t)c, d, sizeof(d));
242 	snprintf(s, len, "%s", d);
243 }
244 
245 /** nice string for rcode */
246 static void
247 pretty_rcode(char* s, size_t len, int r)
248 {
249 	char d[16];
250 	sldns_wire2str_rcode_buf(r, d, sizeof(d));
251 	snprintf(s, len, "%s", d);
252 }
253 
254 /** convert and print rdata */
255 static void
256 print_rd(int t, char* data, size_t len)
257 {
258 	char s[65535];
259 	sldns_wire2str_rdata_buf((uint8_t*)data, len, s, sizeof(s), (uint16_t)t);
260 	printf(" %s", s);
261 }
262 
263 /** pretty line of RR data for results */
264 static void
265 pretty_rdata(char* q, char* cstr, char* tstr, int t, const char* sec,
266 	char* data, size_t len)
267 {
268 	printf("%s", q);
269 	if(strcmp(cstr, "IN") != 0)
270 		printf(" in class %s", cstr);
271 	if(t == LDNS_RR_TYPE_A)
272 		printf(" has address");
273 	else if(t == LDNS_RR_TYPE_AAAA)
274 		printf(" has IPv6 address");
275 	else if(t == LDNS_RR_TYPE_MX)
276 		printf(" mail is handled by");
277 	else if(t == LDNS_RR_TYPE_PTR)
278 		printf(" domain name pointer");
279 	else	printf(" has %s record", tstr);
280 	print_rd(t, data, len);
281 	if(verb > 0)
282 		printf(" %s", sec);
283 	printf("\n");
284 }
285 
286 /** pretty line of output for results */
287 static void
288 pretty_output(char* q, int t, int c, struct ub_result* result, int docname)
289 {
290 	int i;
291 	const char *secstatus = secure_str(result);
292 	char tstr[16];
293 	char cstr[16];
294 	char rcodestr[16];
295 	pretty_type(tstr, 16, t);
296 	pretty_class(cstr, 16, c);
297 	pretty_rcode(rcodestr, 16, result->rcode);
298 
299 	if(!result->havedata && result->rcode) {
300 		printf("Host %s not found: %d(%s).",
301 			q, result->rcode, rcodestr);
302 		if(verb > 0)
303 			printf(" %s", secstatus);
304 		printf("\n");
305 		if(result->bogus && result->why_bogus)
306 			printf("%s\n", result->why_bogus);
307 		return;
308 	}
309 	if(docname && result->canonname &&
310 		result->canonname != result->qname) {
311 		printf("%s is an alias for %s", result->qname,
312 			result->canonname);
313 		if(verb > 0)
314 			printf(" %s", secstatus);
315 		printf("\n");
316 	}
317 	/* remove trailing . from long canonnames for nicer output */
318 	if(result->canonname && strlen(result->canonname) > 1 &&
319 		result->canonname[strlen(result->canonname)-1] == '.')
320 		result->canonname[strlen(result->canonname)-1] = 0;
321 	if(!result->havedata) {
322 		if(verb > 0) {
323 			printf("%s", result->canonname?result->canonname:q);
324 			if(strcmp(cstr, "IN") != 0)
325 				printf(" in class %s", cstr);
326 			if(t == LDNS_RR_TYPE_A)
327 				printf(" has no address");
328 			else if(t == LDNS_RR_TYPE_AAAA)
329 				printf(" has no IPv6 address");
330 			else if(t == LDNS_RR_TYPE_PTR)
331 				printf(" has no domain name ptr");
332 			else if(t == LDNS_RR_TYPE_MX)
333 				printf(" has no mail handler record");
334 			else if(t == LDNS_RR_TYPE_ANY) {
335 				char* s = sldns_wire2str_pkt(
336 					result->answer_packet,
337 					(size_t)result->answer_len);
338 				if(!s) {
339 					fprintf(stderr, "alloc failure\n");
340 					exit(1);
341 				}
342 				printf("%s\n", s);
343 				free(s);
344 			} else	printf(" has no %s record", tstr);
345 			printf(" %s\n", secstatus);
346 		}
347 		/* else: emptiness to indicate no data */
348 		if(result->bogus && result->why_bogus)
349 			printf("%s\n", result->why_bogus);
350 		return;
351 	}
352 	i=0;
353 	while(result->data[i])
354 	{
355 		pretty_rdata(
356 			result->canonname?result->canonname:q,
357 			cstr, tstr, t, secstatus, result->data[i],
358 			(size_t)result->len[i]);
359 		i++;
360 	}
361 	if(result->bogus && result->why_bogus)
362 		printf("%s\n", result->why_bogus);
363 }
364 
365 /** perform a lookup and printout return if domain existed */
366 static int
367 dnslook(struct ub_ctx* ctx, char* q, int t, int c, int docname)
368 {
369 	int ret;
370 	struct ub_result* result;
371 
372 	ret = ub_resolve(ctx, q, t, c, &result);
373 	if(ret != 0) {
374 		fprintf(stderr, "resolve error: %s\n", ub_strerror(ret));
375 		exit(1);
376 	}
377 	pretty_output(q, t, c, result, docname);
378 	ret = result->nxdomain;
379 	ub_resolve_free(result);
380 	return ret;
381 }
382 
383 /** perform host lookup */
384 static void
385 lookup(struct ub_ctx* ctx, const char* nm, const char* qt, const char* qc)
386 {
387 	/* massage input into a query name, type and class */
388 	int multi = 0;	 /* no type, so do A, AAAA, MX */
389 	int reverse = 0; /* we are doing a reverse lookup */
390 	char* realq = massage_qname(nm, &reverse);
391 	int t = massage_type(qt, reverse, &multi);
392 	int c = massage_class(qc);
393 
394 	/* perform the query */
395 	if(multi) {
396 		if(!dnslook(ctx, realq, LDNS_RR_TYPE_A, c, 1)) {
397 			/* domain exists, lookup more */
398 			(void)dnslook(ctx, realq, LDNS_RR_TYPE_AAAA, c, 0);
399 			(void)dnslook(ctx, realq, LDNS_RR_TYPE_MX, c, 0);
400 		}
401 	} else {
402 		(void)dnslook(ctx, realq, t, c, 1);
403 	}
404 	ub_ctx_delete(ctx);
405 	free(realq);
406 }
407 
408 /** print error if any */
409 static void
410 check_ub_res(int r)
411 {
412 	if(r != 0) {
413 		fprintf(stderr, "error: %s\n", ub_strerror(r));
414 		exit(1);
415 	}
416 }
417 
418 /** getopt global, in case header files fail to declare it. */
419 extern int optind;
420 /** getopt global, in case header files fail to declare it. */
421 extern char* optarg;
422 
423 /** Main routine for unbound-host */
424 int main(int argc, char* argv[])
425 {
426 	int c;
427 	char* qclass = NULL;
428 	char* qtype = NULL;
429 	char* use_syslog = NULL;
430 	struct ub_ctx* ctx = NULL;
431 	int debuglevel = 0;
432 
433 	ctx = ub_ctx_create();
434 	if(!ctx) {
435 		fprintf(stderr, "error: out of memory\n");
436 		exit(1);
437 	}
438 	/* no need to fetch additional targets, we only do few lookups */
439 	check_ub_res(ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0"));
440 
441 	/* parse the options */
442 	while( (c=getopt(argc, argv, "46DF:c:df:hrt:vy:C:")) != -1) {
443 		switch(c) {
444 		case '4':
445 			check_ub_res(ub_ctx_set_option(ctx, "do-ip6:", "no"));
446 			break;
447 		case '6':
448 			check_ub_res(ub_ctx_set_option(ctx, "do-ip4:", "no"));
449 			break;
450 		case 'c':
451 			qclass = optarg;
452 			break;
453 		case 'C':
454 			check_ub_res(ub_ctx_config(ctx, optarg));
455 			break;
456 		case 'D':
457 			check_ub_res(ub_ctx_add_ta_file(ctx, ROOT_ANCHOR_FILE));
458 			break;
459 		case 'd':
460 			debuglevel++;
461 			if(debuglevel < 2)
462 				debuglevel = 2; /* at least VERB_DETAIL */
463 			break;
464 		case 'r':
465 			check_ub_res(ub_ctx_resolvconf(ctx, "/etc/resolv.conf"));
466 			break;
467 		case 't':
468 			qtype = optarg;
469 			break;
470 		case 'v':
471 			verb++;
472 			break;
473 		case 'y':
474 			check_ub_res(ub_ctx_add_ta(ctx, optarg));
475 			break;
476 		case 'f':
477 			check_ub_res(ub_ctx_add_ta_file(ctx, optarg));
478 			break;
479 		case 'F':
480 			check_ub_res(ub_ctx_trustedkeys(ctx, optarg));
481 			break;
482 		case '?':
483 		case 'h':
484 		default:
485 			usage();
486 		}
487 	}
488 	if(debuglevel != 0) /* set after possible -C options */
489 		check_ub_res(ub_ctx_debuglevel(ctx, debuglevel));
490 	if(ub_ctx_get_option(ctx, "use-syslog", &use_syslog) == 0) {
491 		if(strcmp(use_syslog, "yes") == 0) /* disable use-syslog */
492 			check_ub_res(ub_ctx_set_option(ctx,
493 				"use-syslog:", "no"));
494 		free(use_syslog);
495 	}
496 	argc -= optind;
497 	argv += optind;
498 	if(argc != 1)
499 		usage();
500 
501 #ifdef HAVE_SSL
502 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
503 	ERR_load_crypto_strings();
504 #endif
505 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
506 	ERR_load_SSL_strings();
507 #endif
508 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
509 #  ifndef S_SPLINT_S
510 	OpenSSL_add_all_algorithms();
511 #  endif
512 #else
513 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
514 		| OPENSSL_INIT_ADD_ALL_DIGESTS
515 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
516 #endif
517 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
518 	(void)SSL_library_init();
519 #else
520 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
521 #endif
522 #endif /* HAVE_SSL */
523 #ifdef HAVE_NSS
524         if(NSS_NoDB_Init(".") != SECSuccess) {
525 		fprintf(stderr, "could not init NSS\n");
526 		return 1;
527 	}
528 #endif
529 	lookup(ctx, argv[0], qtype, qclass);
530 	return 0;
531 }
532