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