xref: /openbsd/usr.sbin/nsd/nsd-control.c (revision 3cab2bb3)
1 /*
2  * nsd-control.c - remote control utility for nsd.
3  *
4  * Copyright (c) 2011, 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  * The remote control utility contacts the nsd server over ssl and
40  * sends the command, receives the answer, and displays the result
41  * from the commandline.
42  */
43 
44 #include "config.h"
45 #include <stdio.h>
46 #ifdef HAVE_SSL
47 #include <sys/types.h>
48 #include <unistd.h>
49 #include <string.h>
50 #ifdef HAVE_OPENSSL_SSL_H
51 #include <openssl/ssl.h>
52 #endif
53 #ifdef HAVE_OPENSSL_ERR_H
54 #include <openssl/err.h>
55 #endif
56 #ifdef HAVE_OPENSSL_RAND_H
57 #include <openssl/rand.h>
58 #endif
59 #ifdef HAVE_SYS_UN_H
60 #include <sys/un.h>
61 #endif
62 #include "util.h"
63 #include "tsig.h"
64 #include "options.h"
65 
66 static void usage() ATTR_NORETURN;
67 static void ssl_err(const char* s) ATTR_NORETURN;
68 static void ssl_path_err(const char* s, const char *path) ATTR_NORETURN;
69 
70 /** Give nsd-control usage, and exit (1). */
71 static void
72 usage()
73 {
74 	printf("Usage:	nsd-control [options] command\n");
75 	printf("	Remote control utility for nsd server.\n");
76 	printf("Version %s. Report bugs to <%s>.\n",
77 		PACKAGE_VERSION, PACKAGE_BUGREPORT);
78 	printf("Options:\n");
79 	printf("  -c file	config file, default is %s\n", CONFIGFILE);
80 	printf("  -s ip[@port]	server address, if omitted config is used.\n");
81 	printf("  -h		show this usage help.\n");
82 	printf("Commands:\n");
83 	printf("  start				start server; runs nsd(8)\n");
84 	printf("  stop				stops the server\n");
85 	printf("  reload [<zone>]		reload modified zonefiles from disk\n");
86 	printf("  reconfig			reload the config file\n");
87 	printf("  repattern			the same as reconfig\n");
88 	printf("  log_reopen			reopen logfile (for log rotate)\n");
89 	printf("  status			display status of server\n");
90 	printf("  stats				print statistics\n");
91 	printf("  stats_noreset			peek at statistics\n");
92 	printf("  addzone <name> <pattern>	add a new zone\n");
93 	printf("  delzone <name>		remove a zone\n");
94 	printf("  changezone <name> <pattern>	change zone to use pattern\n");
95 	printf("  addzones			add zone list on stdin {name space pattern newline}\n");
96 	printf("  delzones			remove zone list on stdin {name newline}\n");
97 	printf("  write [<zone>]		write changed zonefiles to disk\n");
98 	printf("  notify [<zone>]		send NOTIFY messages to slave servers\n");
99 	printf("  transfer [<zone>]		try to update slave zones to newer serial\n");
100 	printf("  force_transfer [<zone>]	update slave zones with AXFR, no serial check\n");
101 	printf("  zonestatus [<zone>]		print state, serial, activity\n");
102 	printf("  serverpid			get pid of server process\n");
103 	printf("  verbosity <number>		change logging detail\n");
104 	printf("  print_tsig [<key_name>]	print tsig with <name> the secret and algo\n");
105 	printf("  update_tsig <name> <secret>	change existing tsig with <name> to a new <secret>\n");
106 	printf("  add_tsig <name> <secret> [algo] add new key with the given parameters\n");
107 	printf("  assoc_tsig <zone> <key_name>	associate <zone> with given tsig <key_name> name\n");
108 	printf("  del_tsig <key_name>		delete tsig <key_name> from configuration\n");
109 	exit(1);
110 }
111 
112 /** exit with ssl error */
113 static void ssl_err(const char* s)
114 {
115 	fprintf(stderr, "error: %s\n", s);
116 	ERR_print_errors_fp(stderr);
117 	exit(1);
118 }
119 
120 /** exit with ssl error related to a file path */
121 static void ssl_path_err(const char* s, const char *path)
122 {
123 	unsigned long err;
124 	err = ERR_peek_error();
125 	if (ERR_GET_LIB(err) == ERR_LIB_SYS &&
126 		(ERR_GET_FUNC(err) == SYS_F_FOPEN ||
127 		 ERR_GET_FUNC(err) == SYS_F_FREAD) ) {
128 		fprintf(stderr, "error: %s\n%s: %s\n",
129 			s, path, ERR_reason_error_string(err));
130 		exit(1);
131 	} else {
132 		ssl_err(s);
133 	}
134 }
135 
136 /** setup SSL context */
137 static SSL_CTX*
138 setup_ctx(struct nsd_options* cfg)
139 {
140 	char* s_cert, *c_key, *c_cert;
141 	SSL_CTX* ctx;
142 
143 	if(!options_remote_is_address(cfg))
144 		return NULL;
145 	s_cert = cfg->server_cert_file;
146 	c_key = cfg->control_key_file;
147 	c_cert = cfg->control_cert_file;
148 
149 	/* filenames may be relative to zonesdir */
150 	if (cfg->zonesdir && cfg->zonesdir[0] &&
151 		(s_cert[0] != '/' || c_key[0] != '/' || c_cert[0] != '/')) {
152 		if(chdir(cfg->zonesdir))
153 			error("could not chdir to zonesdir: %s %s",
154 				cfg->zonesdir, strerror(errno));
155 	}
156 
157         ctx = SSL_CTX_new(SSLv23_client_method());
158 	if(!ctx)
159 		ssl_err("could not allocate SSL_CTX pointer");
160 #if SSL_OP_NO_SSLv2 != 0
161         if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
162 		!= SSL_OP_NO_SSLv2)
163 		ssl_err("could not set SSL_OP_NO_SSLv2");
164 #endif
165         if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
166 		!= SSL_OP_NO_SSLv3)
167 		ssl_err("could not set SSL_OP_NO_SSLv3");
168 #if defined(SSL_OP_NO_RENEGOTIATION)
169 	/* disable client renegotiation */
170 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
171 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION)
172 		ssl_err("could not set SSL_OP_NO_RENEGOTIATION");
173 #endif
174 	if(!SSL_CTX_use_certificate_file(ctx,c_cert,SSL_FILETYPE_PEM))
175 		ssl_path_err("Error setting up SSL_CTX client cert", c_cert);
176 	if(!SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM))
177 		ssl_path_err("Error setting up SSL_CTX client key", c_key);
178 	if(!SSL_CTX_check_private_key(ctx))
179 		ssl_err("Error setting up SSL_CTX client key");
180 	if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
181 		ssl_path_err("Error setting up SSL_CTX verify, server cert",
182 			s_cert);
183 	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
184 
185 	return ctx;
186 }
187 
188 /** contact the server with TCP connect */
189 static int
190 contact_server(const char* svr, struct nsd_options* cfg, int statuscmd)
191 {
192 #ifdef INET6
193 	struct sockaddr_storage addr;
194 #else
195 	struct sockaddr_in addr;
196 #endif
197 	socklen_t addrlen;
198 	int fd;
199 	int port = cfg->control_port;
200 	int addrfamily = 0;
201 	/* use svr or a config entry */
202 	if(!svr) {
203 		if(cfg->control_interface) {
204 			svr = cfg->control_interface->address;
205 		} else if(cfg->do_ip4) {
206 			svr = "127.0.0.1";
207 		} else {
208 			svr = "::1";
209 		}
210 		/* config 0 addr (everything), means ask localhost */
211 		if(strcmp(svr, "0.0.0.0") == 0)
212 			svr = "127.0.0.1";
213 		else if(strcmp(svr, "::0") == 0 ||
214 			strcmp(svr, "0::0") == 0 ||
215 			strcmp(svr, "0::") == 0 ||
216 			strcmp(svr, "::") == 0)
217 			svr = "::1";
218 	}
219 	if(strchr(svr, '@')) {
220 		char* ps = strchr(svr, '@');
221 		*ps++ = 0;
222 		port = atoi(ps);
223 		if(!port) {
224 			fprintf(stderr, "could not parse port %s\n", ps);
225 			exit(1);
226 		}
227 	}
228 	if(svr[0] == '/') {
229 #ifdef HAVE_SYS_UN_H
230 		struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
231 		usock->sun_family = AF_LOCAL;
232 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
233 		usock->sun_len = (unsigned)sizeof(usock);
234 #endif
235 		(void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
236 		addrlen = (socklen_t)sizeof(struct sockaddr_un);
237 		addrfamily = AF_LOCAL;
238 		port = 0;
239 #endif
240 #ifdef INET6
241 	} else if(strchr(svr, ':')) {
242 		struct sockaddr_in6 sa;
243 		addrlen = (socklen_t)sizeof(struct sockaddr_in6);
244 		memset(&sa, 0, addrlen);
245 		sa.sin6_family = AF_INET6;
246 		sa.sin6_port = (in_port_t)htons((uint16_t)port);
247 		if(inet_pton((int)sa.sin6_family, svr, &sa.sin6_addr) <= 0) {
248 			fprintf(stderr, "could not parse IP: %s\n", svr);
249 			exit(1);
250 		}
251 		memcpy(&addr, &sa, addrlen);
252 		addrfamily = AF_INET6;
253 #endif
254 	} else { /* ip4 */
255 		struct sockaddr_in sa;
256 		addrlen = (socklen_t)sizeof(struct sockaddr_in);
257 		memset(&sa, 0, addrlen);
258 		sa.sin_family = AF_INET;
259 		sa.sin_port = (in_port_t)htons((uint16_t)port);
260 		if(inet_pton((int)sa.sin_family, svr, &sa.sin_addr) <= 0) {
261 			fprintf(stderr, "could not parse IP: %s\n", svr);
262 			exit(1);
263 		}
264 		memcpy(&addr, &sa, addrlen);
265 		addrfamily = AF_INET;
266 	}
267 
268 	fd = socket(addrfamily, SOCK_STREAM, 0);
269 	if(fd == -1) {
270 		fprintf(stderr, "socket: %s\n", strerror(errno));
271 		exit(1);
272 	}
273 	if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
274 		int err = errno;
275 		if(!port) fprintf(stderr, "error: connect (%s): %s\n", svr,
276 			strerror(err));
277 		else fprintf(stderr, "error: connect (%s@%d): %s\n", svr, port,
278 			strerror(err));
279 		if(err == ECONNREFUSED && statuscmd) {
280 			printf("nsd is stopped\n");
281 			exit(3);
282 		}
283 		exit(1);
284 	}
285 	return fd;
286 }
287 
288 /** setup SSL on the connection */
289 static SSL*
290 setup_ssl(SSL_CTX* ctx, int fd)
291 {
292 	SSL* ssl;
293 	X509* x;
294 	int r;
295 
296 	if(!ctx) return NULL;
297 	ssl = SSL_new(ctx);
298 	if(!ssl)
299 		ssl_err("could not SSL_new");
300 	SSL_set_connect_state(ssl);
301 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
302 	if(!SSL_set_fd(ssl, fd))
303 		ssl_err("could not SSL_set_fd");
304 	while(1) {
305 		ERR_clear_error();
306 		if( (r=SSL_do_handshake(ssl)) == 1)
307 			break;
308 		r = SSL_get_error(ssl, r);
309 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
310 			ssl_err("SSL handshake failed");
311 		/* wants to be called again */
312 	}
313 
314 	/* check authenticity of server */
315 	if(SSL_get_verify_result(ssl) != X509_V_OK)
316 		ssl_err("SSL verification failed");
317 	x = SSL_get_peer_certificate(ssl);
318 	if(!x)
319 		ssl_err("Server presented no peer certificate");
320 	X509_free(x);
321 	return ssl;
322 }
323 
324 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
325 static int
326 remote_read(SSL* ssl, int fd, char* buf, size_t len)
327 {
328 	if(ssl) {
329 		int r;
330 		ERR_clear_error();
331 		if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
332 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
333 				/* EOF */
334 				return 0;
335 			}
336 			ssl_err("could not SSL_read");
337 		}
338 		buf[r] = 0;
339 	} else {
340 		ssize_t rr = read(fd, buf, len-1);
341 		if(rr <= 0) {
342 			if(rr == 0) {
343 				/* EOF */
344 				return 0;
345 			}
346 			fprintf(stderr, "could not read: %s\n",
347 				strerror(errno));
348 			exit(1);
349 		}
350 		buf[rr] = 0;
351 	}
352 	return 1;
353 }
354 
355 /** write to ssl or fd, fatalexit on error */
356 static void
357 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
358 {
359 	if(ssl) {
360 		if(SSL_write(ssl, buf, (int)len) <= 0)
361 			ssl_err("could not SSL_write");
362 	} else {
363 		if(write(fd, buf, len) < (ssize_t)len) {
364 			fprintf(stderr, "could not write: %s\n",
365 				strerror(errno));
366 			exit(1);
367 		}
368 	}
369 }
370 
371 /** send stdin to server */
372 static void
373 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
374 {
375 	char e[] = {0x04, 0x0a};
376 	while(fgets(buf, (int)sz, in)) {
377 		remote_write(ssl, fd, buf, strlen(buf));
378 	}
379 	/* send end-of-file marker */
380 	remote_write(ssl, fd, e, sizeof(e));
381 }
382 
383 /** send command and display result */
384 static int
385 go_cmd(SSL* ssl, int fd, int argc, char* argv[])
386 {
387 	char pre[10];
388 	const char* space=" ";
389 	const char* newline="\n";
390 	int was_error = 0, first_line = 1;
391 	int i;
392 	char buf[1024];
393 	snprintf(pre, sizeof(pre), "NSDCT%d ", NSD_CONTROL_VERSION);
394 	remote_write(ssl, fd, pre, strlen(pre));
395 	for(i=0; i<argc; i++) {
396 		remote_write(ssl, fd, space, strlen(space));
397 		remote_write(ssl, fd, argv[i], strlen(argv[i]));
398 	}
399 	remote_write(ssl, fd, newline, strlen(newline));
400 
401 	/* send contents to server */
402 	if(argc == 1 && (strcmp(argv[0], "addzones") == 0 ||
403 		strcmp(argv[0], "delzones") == 0)) {
404 		send_file(ssl, fd, stdin, buf, sizeof(buf));
405 	}
406 
407 	while(1) {
408 		if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
409 			break; /* EOF */
410 		}
411 		printf("%s", buf);
412 		if(first_line && strncmp(buf, "error", 5) == 0)
413 			was_error = 1;
414 		first_line = 0;
415 	}
416 	return was_error;
417 }
418 
419 /** go ahead and read config, contact server and perform command and display */
420 static int
421 go(const char* cfgfile, char* svr, int argc, char* argv[])
422 {
423 	struct nsd_options* opt;
424 	int fd, ret;
425 	SSL_CTX* ctx;
426 	SSL* ssl;
427 
428 	/* read config */
429 	if(!(opt = nsd_options_create(region_create(xalloc, free)))) {
430 		fprintf(stderr, "out of memory\n");
431 		exit(1);
432 	}
433 	tsig_init(opt->region);
434 	if(!parse_options_file(opt, cfgfile, NULL, NULL)) {
435 		fprintf(stderr, "could not read config file\n");
436 		exit(1);
437 	}
438 	if(!opt->control_enable)
439 		fprintf(stderr, "warning: control-enable is 'no' in the config file.\n");
440 	ctx = setup_ctx(opt);
441 
442 	/* contact server */
443 	fd = contact_server(svr, opt, argc>0&&strcmp(argv[0],"status")==0);
444 	ssl = setup_ssl(ctx, fd);
445 
446 	/* send command */
447 	ret = go_cmd(ssl, fd, argc, argv);
448 
449 	if(ssl) SSL_free(ssl);
450 	close(fd);
451 	if(ctx) SSL_CTX_free(ctx);
452 	region_destroy(opt->region);
453 	return ret;
454 }
455 
456 /** getopt global, in case header files fail to declare it. */
457 extern int optind;
458 /** getopt global, in case header files fail to declare it. */
459 extern char* optarg;
460 
461 /** Main routine for nsd-control */
462 int main(int argc, char* argv[])
463 {
464 	int c;
465 	const char* cfgfile = CONFIGFILE;
466 	char* svr = NULL;
467 #ifdef USE_WINSOCK
468 	int r;
469 	WSADATA wsa_data;
470 #endif
471 	log_init("nsd-control");
472 
473 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
474 	ERR_load_crypto_strings();
475 #endif
476 	ERR_load_SSL_strings();
477 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
478 	OpenSSL_add_all_algorithms();
479 #else
480 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
481 		| OPENSSL_INIT_ADD_ALL_DIGESTS
482 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
483 #endif
484 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
485 	(void)SSL_library_init();
486 #else
487 	OPENSSL_init_ssl(0, NULL);
488 #endif
489 
490 	if(!RAND_status()) {
491                 /* try to seed it */
492                 unsigned char buf[256];
493                 unsigned int v, seed=(unsigned)time(NULL) ^ (unsigned)getpid();
494                 size_t i;
495 		v = seed;
496                 for(i=0; i<256/sizeof(v); i++) {
497                         memmove(buf+i*sizeof(v), &v, sizeof(v));
498                         v = v*seed + (unsigned int)i;
499                 }
500                 RAND_seed(buf, 256);
501 		fprintf(stderr, "warning: no entropy, seeding openssl PRNG with time\n");
502 	}
503 
504 	/* parse the options */
505 	while( (c=getopt(argc, argv, "c:s:h")) != -1) {
506 		switch(c) {
507 		case 'c':
508 			cfgfile = optarg;
509 			break;
510 		case 's':
511 			svr = optarg;
512 			break;
513 		case '?':
514 		case 'h':
515 		default:
516 			usage();
517 		}
518 	}
519 	argc -= optind;
520 	argv += optind;
521 	if(argc == 0)
522 		usage();
523 	if(argc >= 1 && strcmp(argv[0], "start")==0) {
524 		if(execl(NSD_START_PATH, "nsd", "-c", cfgfile,
525 			(char*)NULL) < 0) {
526 			fprintf(stderr, "could not exec %s: %s\n",
527 				NSD_START_PATH, strerror(errno));
528 			exit(1);
529 		}
530 	}
531 
532 	return go(cfgfile, svr, argc, argv);
533 }
534 
535 #else /* HAVE_SSL */
536 int main(void)
537 {
538 	printf("error: NSD was compiled without SSL.\n");
539 	return 1;
540 }
541 #endif /* HAVE_SSL */
542