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