1 /* 2 * checkconf/unbound-control.c - remote control utility for unbound. 3 * 4 * Copyright (c) 2008, 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 unbound 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_GETOPT_H 46 #include <getopt.h> 47 #endif 48 #ifdef HAVE_OPENSSL_SSL_H 49 #include <openssl/ssl.h> 50 #endif 51 #ifdef HAVE_OPENSSL_ERR_H 52 #include <openssl/err.h> 53 #endif 54 #ifdef HAVE_OPENSSL_RAND_H 55 #include <openssl/rand.h> 56 #endif 57 #include "util/log.h" 58 #include "util/config_file.h" 59 #include "util/locks.h" 60 #include "util/net_help.h" 61 62 /** Give unbound-control usage, and exit (1). */ 63 static void 64 usage() 65 { 66 printf("Usage: unbound-control [options] command\n"); 67 printf(" Remote control utility for unbound server.\n"); 68 printf("Options:\n"); 69 printf(" -c file config file, default is %s\n", CONFIGFILE); 70 printf(" -s ip[@port] server address, if omitted config is used.\n"); 71 printf(" -q quiet (don't print anything if it works ok).\n"); 72 printf(" -h show this usage help.\n"); 73 printf("Commands:\n"); 74 printf(" start start server; runs unbound(8)\n"); 75 printf(" stop stops the server\n"); 76 printf(" reload reloads the server\n"); 77 printf(" (this flushes data, stats, requestlist)\n"); 78 printf(" stats print statistics\n"); 79 printf(" stats_noreset peek at statistics\n"); 80 printf(" status display status of server\n"); 81 printf(" verbosity <number> change logging detail\n"); 82 printf(" log_reopen close and open the logfile\n"); 83 printf(" local_zone <name> <type> add new local zone\n"); 84 printf(" local_zone_remove <name> remove local zone and its contents\n"); 85 printf(" local_data <RR data...> add local data, for example\n"); 86 printf(" local_data www.example.com A 192.0.2.1\n"); 87 printf(" local_data_remove <name> remove local RR data from name\n"); 88 printf(" dump_cache print cache to stdout\n"); 89 printf(" load_cache load cache from stdin\n"); 90 printf(" lookup <name> print nameservers for name\n"); 91 printf(" flush <name> flushes common types for name from cache\n"); 92 printf(" types: A, AAAA, MX, PTR, NS,\n"); 93 printf(" SOA, CNAME, DNAME, SRV, NAPTR\n"); 94 printf(" flush_type <name> <type> flush name, type from cache\n"); 95 printf(" flush_zone <name> flush everything at or under name\n"); 96 printf(" from rr and dnssec caches\n"); 97 printf(" flush_bogus flush all bogus data\n"); 98 printf(" flush_stats flush statistics, make zero\n"); 99 printf(" flush_requestlist drop queries that are worked on\n"); 100 printf(" dump_requestlist show what is worked on\n"); 101 printf(" flush_infra [all | ip] remove ping, edns for one IP or all\n"); 102 printf(" dump_infra show ping and edns entries\n"); 103 printf(" set_option opt: val set option to value, no reload\n"); 104 printf(" get_option opt get option value\n"); 105 printf(" list_stubs list stub-zones and root hints in use\n"); 106 printf(" list_forwards list forward-zones in use\n"); 107 printf(" list_local_zones list local-zones in use\n"); 108 printf(" list_local_data list local-data RRs in use\n"); 109 printf(" insecure_add zone add domain-insecure zone\n"); 110 printf(" insecure_remove zone remove domain-insecure zone\n"); 111 printf(" forward_add [+i] zone addr.. add forward-zone with servers\n"); 112 printf(" forward_remove [+i] zone remove forward zone\n"); 113 printf(" stub_add [+ip] zone addr.. add stub-zone with servers\n"); 114 printf(" stub_remove [+i] zone remove stub zone\n"); 115 printf(" +i also do dnssec insecure point\n"); 116 printf(" +p set stub to use priming\n"); 117 printf(" forward [off | addr ...] without arg show forward setup\n"); 118 printf(" or off to turn off root forwarding\n"); 119 printf(" or give list of ip addresses\n"); 120 printf("Version %s\n", PACKAGE_VERSION); 121 printf("BSD licensed, see LICENSE in source package for details.\n"); 122 printf("Report bugs to %s\n", PACKAGE_BUGREPORT); 123 exit(1); 124 } 125 126 /** exit with ssl error */ 127 static void ssl_err(const char* s) 128 { 129 fprintf(stderr, "error: %s\n", s); 130 ERR_print_errors_fp(stderr); 131 exit(1); 132 } 133 134 /** setup SSL context */ 135 static SSL_CTX* 136 setup_ctx(struct config_file* cfg) 137 { 138 char* s_cert, *c_key, *c_cert; 139 SSL_CTX* ctx; 140 141 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1); 142 c_key = fname_after_chroot(cfg->control_key_file, cfg, 1); 143 c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1); 144 if(!s_cert || !c_key || !c_cert) 145 fatal_exit("out of memory"); 146 ctx = SSL_CTX_new(SSLv23_client_method()); 147 if(!ctx) 148 ssl_err("could not allocate SSL_CTX pointer"); 149 if(!(SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)) 150 ssl_err("could not set SSL_OP_NO_SSLv2"); 151 if(!SSL_CTX_use_certificate_file(ctx,c_cert,SSL_FILETYPE_PEM) || 152 !SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM) 153 || !SSL_CTX_check_private_key(ctx)) 154 ssl_err("Error setting up SSL_CTX client key and cert"); 155 if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1) 156 ssl_err("Error setting up SSL_CTX verify, server cert"); 157 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); 158 159 free(s_cert); 160 free(c_key); 161 free(c_cert); 162 return ctx; 163 } 164 165 /** contact the server with TCP connect */ 166 static int 167 contact_server(const char* svr, struct config_file* cfg, int statuscmd) 168 { 169 struct sockaddr_storage addr; 170 socklen_t addrlen; 171 int fd; 172 /* use svr or the first config entry */ 173 if(!svr) { 174 if(cfg->control_ifs) 175 svr = cfg->control_ifs->str; 176 else svr = "127.0.0.1"; 177 /* config 0 addr (everything), means ask localhost */ 178 if(strcmp(svr, "0.0.0.0") == 0) 179 svr = "127.0.0.1"; 180 else if(strcmp(svr, "::0") == 0 || 181 strcmp(svr, "0::0") == 0 || 182 strcmp(svr, "0::") == 0 || 183 strcmp(svr, "::") == 0) 184 svr = "::1"; 185 } 186 if(strchr(svr, '@')) { 187 if(!extstrtoaddr(svr, &addr, &addrlen)) 188 fatal_exit("could not parse IP@port: %s", svr); 189 } else { 190 if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen)) 191 fatal_exit("could not parse IP: %s", svr); 192 } 193 fd = socket(addr_is_ip6(&addr, addrlen)?AF_INET6:AF_INET, 194 SOCK_STREAM, 0); 195 if(fd == -1) { 196 #ifndef USE_WINSOCK 197 fatal_exit("socket: %s", strerror(errno)); 198 #else 199 fatal_exit("socket: %s", wsa_strerror(WSAGetLastError())); 200 #endif 201 } 202 if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) { 203 log_addr(0, "address", &addr, addrlen); 204 #ifndef USE_WINSOCK 205 log_err("connect: %s", strerror(errno)); 206 if(errno == ECONNREFUSED && statuscmd) { 207 printf("unbound is stopped\n"); 208 exit(3); 209 } 210 #else 211 log_err("connect: %s", wsa_strerror(WSAGetLastError())); 212 if(WSAGetLastError() == WSAECONNREFUSED && statuscmd) { 213 printf("unbound is stopped\n"); 214 exit(3); 215 } 216 #endif 217 exit(1); 218 } 219 return fd; 220 } 221 222 /** setup SSL on the connection */ 223 static SSL* 224 setup_ssl(SSL_CTX* ctx, int fd) 225 { 226 SSL* ssl; 227 X509* x; 228 int r; 229 230 ssl = SSL_new(ctx); 231 if(!ssl) 232 ssl_err("could not SSL_new"); 233 SSL_set_connect_state(ssl); 234 (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); 235 if(!SSL_set_fd(ssl, fd)) 236 ssl_err("could not SSL_set_fd"); 237 while(1) { 238 ERR_clear_error(); 239 if( (r=SSL_do_handshake(ssl)) == 1) 240 break; 241 r = SSL_get_error(ssl, r); 242 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) 243 ssl_err("SSL handshake failed"); 244 /* wants to be called again */ 245 } 246 247 /* check authenticity of server */ 248 if(SSL_get_verify_result(ssl) != X509_V_OK) 249 ssl_err("SSL verification failed"); 250 x = SSL_get_peer_certificate(ssl); 251 if(!x) 252 ssl_err("Server presented no peer certificate"); 253 X509_free(x); 254 return ssl; 255 } 256 257 /** send stdin to server */ 258 static void 259 send_file(SSL* ssl, FILE* in, char* buf, size_t sz) 260 { 261 while(fgets(buf, (int)sz, in)) { 262 if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) 263 ssl_err("could not SSL_write contents"); 264 } 265 } 266 267 /** send command and display result */ 268 static int 269 go_cmd(SSL* ssl, int quiet, int argc, char* argv[]) 270 { 271 char pre[10]; 272 const char* space=" "; 273 const char* newline="\n"; 274 int was_error = 0, first_line = 1; 275 int r, i; 276 char buf[1024]; 277 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION); 278 if(SSL_write(ssl, pre, (int)strlen(pre)) <= 0) 279 ssl_err("could not SSL_write"); 280 for(i=0; i<argc; i++) { 281 if(SSL_write(ssl, space, (int)strlen(space)) <= 0) 282 ssl_err("could not SSL_write"); 283 if(SSL_write(ssl, argv[i], (int)strlen(argv[i])) <= 0) 284 ssl_err("could not SSL_write"); 285 } 286 if(SSL_write(ssl, newline, (int)strlen(newline)) <= 0) 287 ssl_err("could not SSL_write"); 288 289 if(argc == 1 && strcmp(argv[0], "load_cache") == 0) { 290 send_file(ssl, stdin, buf, sizeof(buf)); 291 } 292 293 while(1) { 294 ERR_clear_error(); 295 if((r = SSL_read(ssl, buf, (int)sizeof(buf)-1)) <= 0) { 296 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) { 297 /* EOF */ 298 break; 299 } 300 ssl_err("could not SSL_read"); 301 } 302 buf[r] = 0; 303 if(first_line && strncmp(buf, "error", 5) == 0) { 304 printf("%s", buf); 305 was_error = 1; 306 } else if (!quiet) 307 printf("%s", buf); 308 309 first_line = 0; 310 } 311 return was_error; 312 } 313 314 /** go ahead and read config, contact server and perform command and display */ 315 static int 316 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[]) 317 { 318 struct config_file* cfg; 319 int fd, ret; 320 SSL_CTX* ctx; 321 SSL* ssl; 322 323 /* read config */ 324 if(!(cfg = config_create())) 325 fatal_exit("out of memory"); 326 if(!config_read(cfg, cfgfile, NULL)) 327 fatal_exit("could not read config file"); 328 if(!cfg->remote_control_enable) 329 log_warn("control-enable is 'no' in the config file."); 330 ctx = setup_ctx(cfg); 331 332 /* contact server */ 333 fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0); 334 ssl = setup_ssl(ctx, fd); 335 336 /* send command */ 337 ret = go_cmd(ssl, quiet, argc, argv); 338 339 SSL_free(ssl); 340 #ifndef USE_WINSOCK 341 close(fd); 342 #else 343 closesocket(fd); 344 #endif 345 SSL_CTX_free(ctx); 346 config_delete(cfg); 347 return ret; 348 } 349 350 /** getopt global, in case header files fail to declare it. */ 351 extern int optind; 352 /** getopt global, in case header files fail to declare it. */ 353 extern char* optarg; 354 355 /** Main routine for unbound-control */ 356 int main(int argc, char* argv[]) 357 { 358 int c, ret; 359 int quiet = 0; 360 const char* cfgfile = CONFIGFILE; 361 char* svr = NULL; 362 #ifdef USE_WINSOCK 363 int r; 364 WSADATA wsa_data; 365 #endif 366 #ifdef USE_THREAD_DEBUG 367 /* stop the file output from unbound-control, overwites the servers */ 368 extern int check_locking_order; 369 check_locking_order = 0; 370 #endif /* USE_THREAD_DEBUG */ 371 log_ident_set("unbound-control"); 372 log_init(NULL, 0, NULL); 373 checklock_start(); 374 #ifdef USE_WINSOCK 375 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) 376 fatal_exit("WSAStartup failed: %s", wsa_strerror(r)); 377 /* use registry config file in preference to compiletime location */ 378 if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile"))) 379 cfgfile = CONFIGFILE; 380 #endif 381 382 ERR_load_crypto_strings(); 383 ERR_load_SSL_strings(); 384 OpenSSL_add_all_algorithms(); 385 (void)SSL_library_init(); 386 387 if(!RAND_status()) { 388 /* try to seed it */ 389 unsigned char buf[256]; 390 unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid(); 391 unsigned int v = seed; 392 size_t i; 393 for(i=0; i<256/sizeof(v); i++) { 394 memmove(buf+i*sizeof(v), &v, sizeof(v)); 395 v = v*seed + (unsigned int)i; 396 } 397 RAND_seed(buf, 256); 398 log_warn("no entropy, seeding openssl PRNG with time\n"); 399 } 400 401 /* parse the options */ 402 while( (c=getopt(argc, argv, "c:s:qh")) != -1) { 403 switch(c) { 404 case 'c': 405 cfgfile = optarg; 406 break; 407 case 's': 408 svr = optarg; 409 break; 410 case 'q': 411 quiet = 1; 412 break; 413 case '?': 414 case 'h': 415 default: 416 usage(); 417 } 418 } 419 argc -= optind; 420 argv += optind; 421 if(argc == 0) 422 usage(); 423 if(argc >= 1 && strcmp(argv[0], "start")==0) { 424 if(execlp("unbound", "unbound", "-c", cfgfile, 425 (char*)NULL) < 0) { 426 fatal_exit("could not exec unbound: %s", 427 strerror(errno)); 428 } 429 } 430 431 ret = go(cfgfile, svr, quiet, argc, argv); 432 433 #ifdef USE_WINSOCK 434 WSACleanup(); 435 #endif 436 checklock_stop(); 437 return ret; 438 } 439