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