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