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