Merge pull request #2045 from RincewindsHat/fix/calloc_argument_order
[monitoring-plugins.git] / plugins / check_dns.c
blobe1e7c00ed953374c5abb50df9b656d55702c83d5
1 /*****************************************************************************
3 * Monitoring check_dns plugin
5 * License: GPL
6 * Copyright (c) 2000-2024 Monitoring Plugins Development Team
8 * Description:
10 * This file contains the check_dns plugin
12 * LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which
13 * will not be picked up by this plugin
16 * This program is free software: you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation, either version 3 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 *****************************************************************************/
32 const char *progname = "check_dns";
33 const char *copyright = "2000-2024";
34 const char *email = "devel@monitoring-plugins.org";
36 #include "common.h"
37 #include "utils.h"
38 #include "utils_base.h"
39 #include "netutils.h"
40 #include "runcmd.h"
42 static int process_arguments(int /*argc*/, char ** /*argv*/);
43 static int validate_arguments(void);
44 static int error_scan(char * /*input_buffer*/, bool *);
45 static bool ip_match_cidr(const char * /*addr*/, const char * /*cidr_ro*/);
46 static unsigned long ip2long(const char * /*src*/);
47 static void print_help(void);
48 void print_usage(void);
50 #define ADDRESS_LENGTH 256
51 static char query_address[ADDRESS_LENGTH] = "";
52 static char dns_server[ADDRESS_LENGTH] = "";
53 static char ptr_server[ADDRESS_LENGTH] = "";
54 static bool verbose = false;
55 static char **expected_address = NULL;
56 static int expected_address_cnt = 0;
57 static bool expect_nxdomain = false;
59 static bool expect_authority = false;
60 static bool all_match = false;
61 static thresholds *time_thresholds = NULL;
63 static int qstrcmp(const void *p1, const void *p2) {
64 /* The actual arguments to this function are "pointers to
65 pointers to char", but strcmp() arguments are "pointers
66 to char", hence the following cast plus dereference */
67 return strcmp(*(char *const *)p1, *(char *const *)p2);
70 int main(int argc, char **argv) {
71 char *command_line = NULL;
72 char input_buffer[MAX_INPUT_BUFFER];
73 char *address = NULL; /* comma separated str with addrs/ptrs (sorted) */
74 char **addresses = NULL;
75 int n_addresses = 0;
76 char *msg = NULL;
77 char *temp_buffer = NULL;
78 bool non_authoritative = false;
79 int result = STATE_UNKNOWN;
80 double elapsed_time;
81 long microsec;
82 struct timeval tv;
83 bool parse_address = false; /* This flag scans for Address: but only after Name: */
84 output chld_out;
85 output chld_err;
86 bool is_nxdomain = false;
88 setlocale(LC_ALL, "");
89 bindtextdomain(PACKAGE, LOCALEDIR);
90 textdomain(PACKAGE);
92 /* Set signal handling and alarm */
93 if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
94 usage_va(_("Cannot catch SIGALRM"));
97 /* Parse extra opts if any */
98 argv = np_extra_opts(&argc, argv, progname);
100 if (process_arguments(argc, argv) == ERROR) {
101 usage_va(_("Could not parse arguments"));
104 /* get the command to run */
105 xasprintf(&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
107 alarm(timeout_interval);
108 gettimeofday(&tv, NULL);
110 if (verbose)
111 printf("%s\n", command_line);
113 /* run the command */
114 if ((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
115 msg = (char *)_("nslookup returned an error status");
116 result = STATE_WARNING;
119 /* scan stdout */
120 for (size_t i = 0; i < chld_out.lines; i++) {
121 if (addresses == NULL)
122 addresses = malloc(sizeof(*addresses) * 10);
123 else if (!(n_addresses % 10))
124 addresses = realloc(addresses, sizeof(*addresses) * (n_addresses + 10));
126 if (verbose)
127 puts(chld_out.line[i]);
129 if (strcasestr(chld_out.line[i], ".in-addr.arpa") || strcasestr(chld_out.line[i], ".ip6.arpa")) {
130 if ((temp_buffer = strstr(chld_out.line[i], "name = ")))
131 addresses[n_addresses++] = strdup(temp_buffer + 7);
132 else {
133 msg = (char *)_("Warning plugin error");
134 result = STATE_WARNING;
138 /* bug ID: 2946553 - Older versions of bind will use all available dns
139 servers, we have to match the one specified */
140 if (strstr(chld_out.line[i], "Server:") && strlen(dns_server) > 0) {
141 temp_buffer = strchr(chld_out.line[i], ':');
142 temp_buffer++;
144 /* Strip leading tabs */
145 for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++)
146 /* NOOP */;
148 strip(temp_buffer);
149 if (temp_buffer == NULL || strlen(temp_buffer) == 0) {
150 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty server string\n"), NSLOOKUP_COMMAND);
153 if (strcmp(temp_buffer, dns_server) != 0) {
154 die(STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server);
158 /* the server is responding, we just got the host name... */
159 if (strstr(chld_out.line[i], "Name:"))
160 parse_address = true;
161 else if (parse_address && (strstr(chld_out.line[i], "Address:") || strstr(chld_out.line[i], "Addresses:"))) {
162 temp_buffer = index(chld_out.line[i], ':');
163 temp_buffer++;
165 /* Strip leading spaces */
166 while (*temp_buffer == ' ')
167 temp_buffer++;
169 strip(temp_buffer);
170 if (temp_buffer == NULL || strlen(temp_buffer) == 0) {
171 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty host name string\n"), NSLOOKUP_COMMAND);
174 addresses[n_addresses++] = strdup(temp_buffer);
175 } else if (strstr(chld_out.line[i], _("Non-authoritative answer:"))) {
176 non_authoritative = true;
179 result = error_scan(chld_out.line[i], &is_nxdomain);
180 if (result != STATE_OK) {
181 msg = strchr(chld_out.line[i], ':');
182 if (msg)
183 msg++;
184 break;
188 /* scan stderr */
189 for (size_t i = 0; i < chld_err.lines; i++) {
190 if (verbose)
191 puts(chld_err.line[i]);
193 if (error_scan(chld_err.line[i], &is_nxdomain) != STATE_OK) {
194 result = max_state(result, error_scan(chld_err.line[i], &is_nxdomain));
195 msg = strchr(input_buffer, ':');
196 if (msg)
197 msg++;
198 else
199 msg = input_buffer;
203 if (is_nxdomain && !expect_nxdomain) {
204 die(STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address);
207 if (addresses) {
208 int i;
209 int slen;
210 char *adrp;
211 qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
212 for (i = 0, slen = 1; i < n_addresses; i++) {
213 slen += strlen(addresses[i]) + 1;
215 adrp = address = malloc(slen);
216 for (i = 0; i < n_addresses; i++) {
217 if (i)
218 *adrp++ = ',';
219 strcpy(adrp, addresses[i]);
220 adrp += strlen(addresses[i]);
222 *adrp = 0;
223 } else
224 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), NSLOOKUP_COMMAND);
226 /* compare to expected address */
227 if (result == STATE_OK && expected_address_cnt > 0) {
228 result = STATE_CRITICAL;
229 temp_buffer = "";
230 unsigned long expect_match = (1 << expected_address_cnt) - 1;
231 unsigned long addr_match = (1 << n_addresses) - 1;
233 for (int i = 0; i < expected_address_cnt; i++) {
234 int j;
235 /* check if we get a match on 'raw' ip or cidr */
236 for (j = 0; j < n_addresses; j++) {
237 if (strcmp(addresses[j], expected_address[i]) == 0 || ip_match_cidr(addresses[j], expected_address[i])) {
238 result = STATE_OK;
239 addr_match &= ~(1 << j);
240 expect_match &= ~(1 << i);
244 /* prepare an error string */
245 xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
247 /* check if expected_address must cover all in addresses and none may be missing */
248 if (all_match && (expect_match != 0 || addr_match != 0))
249 result = STATE_CRITICAL;
250 if (result == STATE_CRITICAL) {
251 /* Strip off last semicolon... */
252 temp_buffer[strlen(temp_buffer) - 2] = '\0';
253 xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
257 if (expect_nxdomain) {
258 if (!is_nxdomain) {
259 result = STATE_CRITICAL;
260 xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), query_address, address);
261 } else {
262 if (address != NULL)
263 free(address);
264 address = "NXDOMAIN";
268 /* check if authoritative */
269 if (result == STATE_OK && expect_authority && non_authoritative) {
270 result = STATE_CRITICAL;
271 xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
274 microsec = deltime(tv);
275 elapsed_time = (double)microsec / 1.0e6;
277 if (result == STATE_OK) {
278 result = get_status(elapsed_time, time_thresholds);
279 if (result == STATE_OK) {
280 printf("DNS %s: ", _("OK"));
281 } else if (result == STATE_WARNING) {
282 printf("DNS %s: ", _("WARNING"));
283 } else if (result == STATE_CRITICAL) {
284 printf("DNS %s: ", _("CRITICAL"));
286 printf(ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
287 printf(_(". %s returns %s"), query_address, address);
288 if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) {
289 printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, true, time_thresholds->critical->end,
290 true, 0, false, 0));
291 } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) {
292 printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, true, time_thresholds->critical->end, true, 0, false, 0));
293 } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) {
294 printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, false, 0, true, 0, false, 0));
295 } else
296 printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0));
297 } else if (result == STATE_WARNING)
298 printf(_("DNS WARNING - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
299 else if (result == STATE_CRITICAL)
300 printf(_("DNS CRITICAL - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
301 else
302 printf(_("DNS UNKNOWN - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
304 return result;
307 bool ip_match_cidr(const char *addr, const char *cidr_ro) {
308 char *subnet;
309 char *mask_c;
310 char *cidr = strdup(cidr_ro);
311 int mask;
312 subnet = strtok(cidr, "/");
313 mask_c = strtok(NULL, "\0");
314 if (!subnet || !mask_c) {
315 return false;
317 mask = atoi(mask_c);
319 /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */
320 return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask);
323 unsigned long ip2long(const char *src) {
324 unsigned long ip[4];
325 /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */
326 return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", &ip[0], &ip[1], &ip[2], &ip[3]) == 4 && ip[0] < 256 && ip[1] < 256 && ip[2] < 256 &&
327 ip[3] < 256)
328 ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
329 : 0;
332 int error_scan(char *input_buffer, bool *is_nxdomain) {
334 const int nxdomain = strstr(input_buffer, "Non-existent") || strstr(input_buffer, "** server can't find") ||
335 strstr(input_buffer, "** Can't find") || strstr(input_buffer, "NXDOMAIN");
336 if (nxdomain)
337 *is_nxdomain = true;
339 /* the DNS lookup timed out */
340 if (strstr(input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
341 strstr(input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) ||
342 strstr(input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
343 return STATE_OK;
345 /* DNS server is not running... */
346 else if (strstr(input_buffer, "No response from server"))
347 die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
348 else if (strstr(input_buffer, "no servers could be reached"))
349 die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
351 /* Host name is valid, but server doesn't have records... */
352 else if (strstr(input_buffer, "No records"))
353 die(STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
355 /* Connection was refused */
356 else if (strstr(input_buffer, "Connection refused") || strstr(input_buffer, "Couldn't find server") ||
357 strstr(input_buffer, "Refused") || (strstr(input_buffer, "** server can't find") && strstr(input_buffer, ": REFUSED")))
358 die(STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
360 /* Query refused (usually by an ACL in the namserver) */
361 else if (strstr(input_buffer, "Query refused"))
362 die(STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
364 /* No information (e.g. nameserver IP has two PTR records) */
365 else if (strstr(input_buffer, "No information"))
366 die(STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
368 /* Network is unreachable */
369 else if (strstr(input_buffer, "Network is unreachable"))
370 die(STATE_CRITICAL, _("Network is unreachable\n"));
372 /* Internal server failure */
373 else if (strstr(input_buffer, "Server failure"))
374 die(STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
376 /* Request error or the DNS lookup timed out */
377 else if (strstr(input_buffer, "Format error") || strstr(input_buffer, "Timed out"))
378 return STATE_WARNING;
380 return STATE_OK;
383 /* process command-line arguments */
384 int process_arguments(int argc, char **argv) {
385 int c;
386 char *warning = NULL;
387 char *critical = NULL;
389 int opt_index = 0;
390 static struct option long_opts[] = {{"help", no_argument, 0, 'h'},
391 {"version", no_argument, 0, 'V'},
392 {"verbose", no_argument, 0, 'v'},
393 {"timeout", required_argument, 0, 't'},
394 {"hostname", required_argument, 0, 'H'},
395 {"server", required_argument, 0, 's'},
396 {"reverse-server", required_argument, 0, 'r'},
397 {"expected-address", required_argument, 0, 'a'},
398 {"expect-nxdomain", no_argument, 0, 'n'},
399 {"expect-authority", no_argument, 0, 'A'},
400 {"all", no_argument, 0, 'L'},
401 {"warning", required_argument, 0, 'w'},
402 {"critical", required_argument, 0, 'c'},
403 {0, 0, 0, 0}};
405 if (argc < 2)
406 return ERROR;
408 for (c = 1; c < argc; c++)
409 if (strcmp("-to", argv[c]) == 0)
410 strcpy(argv[c], "-t");
412 while (1) {
413 c = getopt_long(argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index);
415 if (c == -1 || c == EOF)
416 break;
418 switch (c) {
419 case 'h': /* help */
420 print_help();
421 exit(STATE_UNKNOWN);
422 case 'V': /* version */
423 print_revision(progname, NP_VERSION);
424 exit(STATE_UNKNOWN);
425 case 'v': /* version */
426 verbose = true;
427 break;
428 case 't': /* timeout period */
429 timeout_interval = atoi(optarg);
430 break;
431 case 'H': /* hostname */
432 if (strlen(optarg) >= ADDRESS_LENGTH)
433 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
434 strcpy(query_address, optarg);
435 break;
436 case 's': /* server name */
437 /* TODO: this host_or_die check is probably unnecessary.
438 * Better to confirm nslookup response matches */
439 host_or_die(optarg);
440 if (strlen(optarg) >= ADDRESS_LENGTH)
441 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
442 strcpy(dns_server, optarg);
443 break;
444 case 'r': /* reverse server name */
445 /* TODO: Is this host_or_die necessary? */
446 host_or_die(optarg);
447 if (strlen(optarg) >= ADDRESS_LENGTH)
448 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
449 strcpy(ptr_server, optarg);
450 break;
451 case 'a': /* expected address */
452 if (strlen(optarg) >= ADDRESS_LENGTH)
453 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
454 if (strchr(optarg, ',') != NULL) {
455 char *comma = strchr(optarg, ',');
456 while (comma != NULL) {
457 expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **));
458 expected_address[expected_address_cnt] = strndup(optarg, comma - optarg);
459 expected_address_cnt++;
460 optarg = comma + 1;
461 comma = strchr(optarg, ',');
463 expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **));
464 expected_address[expected_address_cnt] = strdup(optarg);
465 expected_address_cnt++;
466 } else {
467 expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **));
468 expected_address[expected_address_cnt] = strdup(optarg);
469 expected_address_cnt++;
471 break;
472 case 'n': /* expect NXDOMAIN */
473 expect_nxdomain = true;
474 break;
475 case 'A': /* expect authority */
476 expect_authority = true;
477 break;
478 case 'L': /* all must match */
479 all_match = true;
480 break;
481 case 'w':
482 warning = optarg;
483 break;
484 case 'c':
485 critical = optarg;
486 break;
487 default: /* args not parsable */
488 usage5();
492 c = optind;
493 if (strlen(query_address) == 0 && c < argc) {
494 if (strlen(argv[c]) >= ADDRESS_LENGTH)
495 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
496 strcpy(query_address, argv[c++]);
499 if (strlen(dns_server) == 0 && c < argc) {
500 /* TODO: See -s option */
501 host_or_die(argv[c]);
502 if (strlen(argv[c]) >= ADDRESS_LENGTH)
503 die(STATE_UNKNOWN, _("Input buffer overflow\n"));
504 strcpy(dns_server, argv[c++]);
507 set_thresholds(&time_thresholds, warning, critical);
509 return validate_arguments();
512 int validate_arguments(void) {
513 if (query_address[0] == 0) {
514 printf("missing --host argument\n");
515 return ERROR;
518 if (expected_address_cnt > 0 && expect_nxdomain) {
519 printf("--expected-address and --expect-nxdomain cannot be combined\n");
520 return ERROR;
523 return OK;
526 void print_help(void) {
527 print_revision(progname, NP_VERSION);
529 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
530 printf(COPYRIGHT, copyright, email);
532 printf("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
533 printf("%s\n", _("An optional DNS server to use may be specified."));
534 printf("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
536 printf("\n\n");
538 print_usage();
540 printf(UT_HELP_VRSN);
541 printf(UT_EXTRA_OPTS);
543 printf(" -H, --hostname=HOST\n");
544 printf(" %s\n", _("The name or address you want to query"));
545 printf(" -s, --server=HOST\n");
546 printf(" %s\n", _("Optional DNS server you want to use for the lookup"));
547 printf(" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n");
548 printf(" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end"));
549 printf(" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any"));
550 printf(" %s\n", _("value matches)."));
551 printf(" -n, --expect-nxdomain\n");
552 printf(" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)"));
553 printf(" %s\n", _("Cannot be used together with -a"));
554 printf(" -A, --expect-authority\n");
555 printf(" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
556 printf(" -w, --warning=seconds\n");
557 printf(" %s\n", _("Return warning if elapsed time exceeds value. Default off"));
558 printf(" -c, --critical=seconds\n");
559 printf(" %s\n", _("Return critical if elapsed time exceeds value. Default off"));
560 printf(" -L, --all\n");
561 printf(" %s\n", _("Return critical if the list of expected addresses does not match all addresses"));
562 printf(" %s\n", _("returned. Default off"));
564 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
566 printf(UT_SUPPORT);
569 void print_usage(void) {
570 printf("%s\n", _("Usage:"));
571 printf("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname);