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