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