Ejemplo n.º 1
0
int
ssh_connect (char *haddr, int hport, char *remote_version)
{
	int sd;
	int result;
	char *output = NULL;
	char *buffer = NULL;
	char *ssh_proto = NULL;
	char *ssh_server = NULL;
	static char *rev_no = VERSION;
	struct timeval tv;
	double elapsed_time;

	gettimeofday(&tv, NULL);

	result = my_tcp_connect (haddr, hport, &sd);

	if (result != STATE_OK)
		return result;

	output = (char *) malloc (BUFF_SZ + 1);
	memset (output, 0, BUFF_SZ + 1);
	recv (sd, output, BUFF_SZ, 0);
	if (strncmp (output, "SSH", 3)) {
		printf (_("Server answer: %s"), output);
		close(sd);
		exit (STATE_CRITICAL);
	}
	else {
		strip (output);
		if (verbose)
			printf ("%s\n", output);
		ssh_proto = output + 4;
		ssh_server = ssh_proto + strspn (ssh_proto, "-0123456789. ");
		ssh_proto[strspn (ssh_proto, "0123456789. ")] = 0;

		xasprintf (&buffer, "SSH-%s-check_ssh_%s\r\n", ssh_proto, rev_no);
		send (sd, buffer, strlen (buffer), MSG_DONTWAIT);
		if (verbose)
			printf ("%s\n", buffer);

		if (remote_version && strcmp(remote_version, ssh_server)) {
			printf
				(_("SSH WARNING - %s (protocol %s) version mismatch, expected '%s'\n"),
				 ssh_server, ssh_proto, remote_version);
			close(sd);
			exit (STATE_WARNING);
		}

		elapsed_time = (double)deltime(tv) / 1.0e6;

		printf
			(_("SSH OK - %s (protocol %s) | %s\n"),
			 ssh_server, ssh_proto, fperfdata("time", elapsed_time, "s",
			 FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));
		close(sd);
		exit (STATE_OK);
	}
}
Ejemplo n.º 2
0
int
main (int argc, char **argv)
{
  char *command_line;
  output chld_out, chld_err;
  char *msg = NULL;
  size_t i;
  char *t;
  long microsec;
  double elapsed_time;
  int result = STATE_UNKNOWN;
  int timeout_interval_dig;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR)
    usage_va(_("Cannot catch SIGALRM"));

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR)
    usage_va(_("Could not parse arguments"));

  /* dig applies the timeout to each try, so we need to work around this */
  timeout_interval_dig = timeout_interval / number_tries + number_tries;

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +tries=%d +time=%d",
            PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose) {
    printf ("%s\n", command_line);
    if(expected_address != NULL) {
      printf (_("Looking for: '%s'\n"), expected_address);
    } else {
      printf (_("Looking for: '%s'\n"), query_address);
    }
  }

  /* run the command */
  if(np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) {
    result = STATE_WARNING;
    msg = (char *)_("dig returned an error status");
  }

  for(i = 0; i < chld_out.lines; i++) {
    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], ";; ANSWER SECTION:")) {

      /* loop through the whole 'ANSWER SECTION' */
      for(; i < chld_out.lines; i++) {
        /* get the host address */
        if (verbose)
          printf ("%s\n", chld_out.line[i]);

        if (strstr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) {
          msg = chld_out.line[i];
          result = STATE_OK;

          /* Translate output TAB -> SPACE */
          t = msg;
          while ((t = strchr(t, '\t')) != NULL) *t = ' ';
          break;
        }
      }

      if (result == STATE_UNKNOWN) {
        msg = (char *)_("Server not found in ANSWER SECTION");
        result = STATE_WARNING;
      }

      /* we found the answer section, so break out of the loop */
      break;
    }
  }

  if (result == STATE_UNKNOWN) {
    msg = (char *)_("No ANSWER SECTION found");
    result = STATE_CRITICAL;
  }

  /* If we get anything on STDERR, at least set warning */
  if(chld_err.buflen > 0) {
    result = max_state(result, STATE_WARNING);
    if(!msg) for(i = 0; i < chld_err.lines; i++) {
      msg = strchr(chld_err.line[0], ':');
      if(msg) {
        msg++;
        break;
      }
    }
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (critical_interval > UNDEFINED && elapsed_time > critical_interval)
    result = STATE_CRITICAL;

  else if (warning_interval > UNDEFINED && elapsed_time > warning_interval)
    result = STATE_WARNING;

  printf ("DNS %s - %.3f seconds response time (%s)|%s\n",
          state_text (result), elapsed_time,
          msg ? msg : _("Probably a non-existent host/domain"),
          fperfdata("time", elapsed_time, "s",
                    (warning_interval>UNDEFINED?TRUE:FALSE),
                    warning_interval,
                    (critical_interval>UNDEFINED?TRUE:FALSE),
            critical_interval,
            TRUE, 0, FALSE, 0));
  return result;
}
Ejemplo n.º 3
0
int
main (int argc, char **argv)
{
	short supports_tls=FALSE;
	int n = 0;
	double elapsed_time;
	long microsec;
	int result = STATE_UNKNOWN;
	char *cmd_str = NULL;
	char *helocmd = NULL;
	char *error_msg = "";
	struct timeval tv;

	/* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
	(void) signal (SIGPIPE, SIG_IGN);

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* If localhostname not set on command line, use gethostname to set */
	if(! localhostname){
		localhostname = malloc (HOST_MAX_BYTES);
		if(!localhostname){
			printf(_("malloc() failed!\n"));
			return STATE_CRITICAL;
		}
		if(gethostname(localhostname, HOST_MAX_BYTES)){
			printf(_("gethostname() failed!\n"));
			return STATE_CRITICAL;
		}
	}
	if(use_ehlo)
		xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
	else
		xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");

	if (verbose)
		printf("HELOCMD: %s", helocmd);

	/* initialize the MAIL command with optional FROM command  */
	xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n");

	if (verbose && send_mail_from)
		printf ("FROM CMD: %s", cmd_str);

	/* initialize alarm signal handling */
	(void) signal (SIGALRM, socket_timeout_alarm_handler);

	/* set socket timeout */
	(void) alarm (socket_timeout);

	/* start timer */
	gettimeofday (&tv, NULL);

	/* try to connect to the host at the given port number */
	result = my_tcp_connect (server_address, server_port, &sd);

	if (result == STATE_OK) { /* we connected */

		/* watch for the SMTP connection string and */
		/* return a WARNING status if we couldn't read any data */
		if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
			printf (_("recv() failed\n"));
			return STATE_WARNING;
		}
		else {
			if (verbose)
				printf ("%s", buffer);
			/* strip the buffer of carriage returns */
			strip (buffer);
			/* make sure we find the response we are looking for */
			if (!strstr (buffer, server_expect)) {
				if (server_port == SMTP_PORT)
					printf (_("Invalid SMTP response received from host: %s\n"), buffer);
				else
					printf (_("Invalid SMTP response received from host on port %d: %s\n"),
									server_port, buffer);
				return STATE_WARNING;
			}
		}

		/* send the HELO/EHLO command */
		send(sd, helocmd, strlen(helocmd), 0);

		/* allow for response to helo command to reach us */
		if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
			printf (_("recv() failed\n"));
			return STATE_WARNING;
		} else if(use_ehlo){
			if(strstr(buffer, "250 STARTTLS") != NULL ||
			   strstr(buffer, "250-STARTTLS") != NULL){
				supports_tls=TRUE;
			}
		}

		if(use_ssl && ! supports_tls){
			printf(_("WARNING - TLS not supported by server\n"));
			smtp_quit();
			return STATE_WARNING;
		}

#ifdef HAVE_SSL
		if(use_ssl) {
		  /* send the STARTTLS command */
		  send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);

		  recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
		  if (!strstr (buffer, server_expect)) {
		    printf (_("Server does not support STARTTLS\n"));
		    smtp_quit();
		    return STATE_UNKNOWN;
		  }
		  result = np_net_ssl_init(sd);
		  if(result != STATE_OK) {
		    printf (_("CRITICAL - Cannot create SSL context.\n"));
		    np_net_ssl_cleanup();
		    close(sd);
		    return STATE_CRITICAL;
		  } else {
			ssl_established = 1;
		  }

		/*
		 * Resend the EHLO command.
		 *
		 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
		 * obtained from the server, such as the list of SMTP service
		 * extensions, which was not obtained from the TLS negotiation
		 * itself.  The client SHOULD send an EHLO command as the first
		 * command after a successful TLS negotiation.''  For this
		 * reason, some MTAs will not allow an AUTH LOGIN command before
		 * we resent EHLO via TLS.
		 */
		if (my_send(helocmd, strlen(helocmd)) <= 0) {
			printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
			my_close();
			return STATE_UNKNOWN;
		}
		if (verbose)
			printf(_("sent %s"), helocmd);
		if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
			printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
			my_close();
			return STATE_UNKNOWN;
		}
		if (verbose) {
			printf("%s", buffer);
		}

#  ifdef USE_OPENSSL
		  if ( check_cert ) {
                    result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
		    my_close();
		    return result;
		  }
#  endif /* USE_OPENSSL */
		}
#endif

		if (send_mail_from) {
		  my_send(cmd_str, strlen(cmd_str));
		  if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
		    printf("%s", buffer);
		}

		while (n < ncommands) {
			xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
			my_send(cmd_str, strlen(cmd_str));
			if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
				printf("%s", buffer);
			strip (buffer);
			if (n < nresponses) {
				cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
				errcode = regcomp (&preg, responses[n], cflags);
				if (errcode != 0) {
					regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
					printf (_("Could Not Compile Regular Expression"));
					return ERROR;
				}
				excode = regexec (&preg, buffer, 10, pmatch, eflags);
				if (excode == 0) {
					result = STATE_OK;
				}
				else if (excode == REG_NOMATCH) {
					result = STATE_WARNING;
					printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
				}
				else {
					regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
					printf (_("Execute Error: %s\n"), errbuf);
					result = STATE_UNKNOWN;
				}
			}
			n++;
		}

		if (authtype != NULL) {
			if (strcmp (authtype, "LOGIN") == 0) {
				char *abuf;
				int ret;
				do {
					if (authuser == NULL) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("no authuser specified, "));
						break;
					}
					if (authpass == NULL) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("no authpass specified, "));
						break;
					}

					/* send AUTH LOGIN */
					my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
					if (verbose)
						printf (_("sent %s\n"), "AUTH LOGIN");

					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
						result = STATE_WARNING;
						break;
					}
					if (verbose)
						printf (_("received %s\n"), buffer);

					if (strncmp (buffer, "334", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
						break;
					}

					/* encode authuser with base64 */
					base64_encode_alloc (authuser, strlen(authuser), &abuf);
					xasprintf(&abuf, "%s\r\n", abuf);
					my_send(abuf, strlen(abuf));
					if (verbose)
						printf (_("sent %s\n"), abuf);

					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("recv() failed after sending authuser, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "334", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after authuser, "));
						break;
					}
					/* encode authpass with base64 */
					base64_encode_alloc (authpass, strlen(authpass), &abuf);
					xasprintf(&abuf, "%s\r\n", abuf);
					my_send(abuf, strlen(abuf));
					if (verbose) {
						printf (_("sent %s\n"), abuf);
					}
					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("recv() failed after sending authpass, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "235", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after authpass, "));
						break;
					}
					break;
				} while (0);
			} else {
				result = STATE_CRITICAL;
				xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
			}
		}

		/* tell the server we're done */
		smtp_quit();

		/* finally close the connection */
		close (sd);
	}

	/* reset the alarm */
	alarm (0);

	microsec = deltime (tv);
	elapsed_time = (double)microsec / 1.0e6;

	if (result == STATE_OK) {
		if (check_critical_time && elapsed_time > critical_time)
			result = STATE_CRITICAL;
		else if (check_warning_time && elapsed_time > warning_time)
			result = STATE_WARNING;
	}

	printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
			state_text (result),
			error_msg,
			elapsed_time,
			verbose?", ":"", verbose?buffer:"",
			fperfdata ("time", elapsed_time, "s",
				(int)check_warning_time, warning_time,
				(int)check_critical_time, critical_time,
				TRUE, 0, FALSE, 0));

	return result;
}
Ejemplo n.º 4
0
int
main (int argc, char *argv[])
{

	LDAP *ld;
	LDAPMessage *result;

	/* should be 	int result = STATE_UNKNOWN; */

	int status = STATE_UNKNOWN;
	long microsec;
	double elapsed_time;

	/* for ldap tls */

	int tls;
	int version=3;

	/* for entry counting */

	LDAPMessage *next_entry;
	int status_entries = STATE_OK;
	int num_entries = 0;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	if (strstr(argv[0],"check_ldaps")) {
		xasprintf (&progname, "check_ldaps");
 	}

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	if (strstr(argv[0],"check_ldaps") && ! starttls && ! ssl_on_connect)
		starttls = TRUE;

	/* initialize alarm signal handling */
	signal (SIGALRM, socket_timeout_alarm_handler);

	/* set socket timeout */
	alarm (timeout_interval);

	/* get the start time */
	gettimeofday (&tv, NULL);

	/* initialize ldap */
	if (ld_uri != NULL)
	{
#ifdef HAVE_LDAP_INITIALIZE
		int result = ldap_initialize(&ld, ld_uri);
		if (result != LDAP_SUCCESS)
		{
			printf ("Failed to connect to LDAP server at %s: %s\n",
				ld_uri, ldap_err2string(result));
			return STATE_CRITICAL;
		}
#else
		printf ("Sorry, this version of %s was compiled without URI support!\n",
			argv[0]);
		return STATE_CRITICAL;
#endif
	}
#ifdef HAVE_LDAP_INIT
	else if (!(ld = ldap_init (ld_host, ld_port))) {
		printf ("Could not connect to the server at port %i\n", ld_port);
		return STATE_CRITICAL;
	}
#else
	else if (!(ld = ldap_open (ld_host, ld_port))) {
		if (verbose)
			ldap_perror(ld, "ldap_open");
		printf (_("Could not connect to the server at port %i\n"), ld_port);
		return STATE_CRITICAL;
	}
#endif /* HAVE_LDAP_INIT */

#ifdef HAVE_LDAP_SET_OPTION
	/* set ldap options */
	if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) !=
			LDAP_OPT_SUCCESS ) {
		printf(_("Could not set protocol version %d\n"), ld_protocol);
		return STATE_CRITICAL;
	}
#endif

	if (ld_port == LDAPS_PORT || ssl_on_connect) {
		xasprintf (&SERVICE, "LDAPS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
		/* ldaps: set option tls */
		tls = LDAP_OPT_X_TLS_HARD;

		if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
		{
			if (verbose)
				ldap_perror(ld, "ldaps_option");
			printf (_("Could not init TLS at port %i!\n"), ld_port);
			return STATE_CRITICAL;
		}
#else
		printf (_("TLS not supported by the libraries!\n"));
		return STATE_CRITICAL;
#endif /* LDAP_OPT_X_TLS */
	} else if (starttls) {
		xasprintf (&SERVICE, "LDAP-TLS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S)
		/* ldap with startTLS: set option version */
		if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS )
		{
			if (version < LDAP_VERSION3)
			{
				version = LDAP_VERSION3;
				ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
			}
		}
		/* call start_tls */
		if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS)
		{
			if (verbose)
				ldap_perror(ld, "ldap_start_tls");
			printf (_("Could not init startTLS at port %i!\n"), ld_port);
			return STATE_CRITICAL;
		}
#else
		printf (_("startTLS not supported by the library, needs LDAPv3!\n"));
		return STATE_CRITICAL;
#endif /* HAVE_LDAP_START_TLS_S */
	}

	/* bind to the ldap server */
	if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) !=
			LDAP_SUCCESS) {
		if (verbose)
			ldap_perror(ld, "ldap_bind");
		printf (_("Could not bind to the LDAP server\n"));
		return STATE_CRITICAL;
	}

	/* do a search of all objectclasses in the base dn */
	if (ldap_search_s (ld, ld_base, (crit_entries!=NULL || warn_entries!=NULL) ? LDAP_SCOPE_SUBTREE : LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result)
			!= LDAP_SUCCESS) {
		if (verbose)
			ldap_perror(ld, "ldap_search");
		printf (_("Could not search/find objectclasses in %s\n"), ld_base);
		return STATE_CRITICAL;
	} else if (crit_entries!=NULL || warn_entries!=NULL) {
		num_entries = ldap_count_entries(ld, result);
	}

	/* unbind from the ldap server */
	ldap_unbind (ld);

	/* reset the alarm handler */
	alarm (0);

	/* calcutate the elapsed time and compare to thresholds */

	microsec = deltime (tv);
	elapsed_time = (double)microsec / 1.0e6;

	if (crit_time!=UNDEFINED && elapsed_time>crit_time)
		status = STATE_CRITICAL;
	else if (warn_time!=UNDEFINED && elapsed_time>warn_time)
		status = STATE_WARNING;
	else
		status = STATE_OK;

	if(entries_thresholds != NULL) {
		if (verbose) {
			printf ("entries found: %d\n", num_entries);
			print_thresholds("entry threasholds", entries_thresholds);
		}
		status_entries = get_status(num_entries, entries_thresholds);
		if (status_entries == STATE_CRITICAL) {
			status = STATE_CRITICAL;
		} else if (status != STATE_CRITICAL) {
			status = status_entries;
		}
	}

	/* print out the result */
	if (crit_entries!=NULL || warn_entries!=NULL) {
		printf (_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"),
			state_text (status),
			num_entries,
			elapsed_time,
			fperfdata ("time", elapsed_time, "s",
				(int)warn_time, warn_time,
				(int)crit_time, crit_time,
				TRUE, 0, FALSE, 0),
			sperfdata ("entries", (double)num_entries, "",
				warn_entries,
				crit_entries,
				TRUE, 0.0, FALSE, 0.0));
	} else {
		printf (_("LDAP %s - %.3f seconds response time|%s\n"),
			state_text (status),
			elapsed_time,
			fperfdata ("time", elapsed_time, "s",
				(int)warn_time, warn_time,
				(int)crit_time, crit_time,
				TRUE, 0, FALSE, 0));
	}

	return status;
}
Ejemplo n.º 5
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char *temp_buffer = NULL;
  int non_authoritative = FALSE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], ".in-addr.arpa")) {
      if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
        addresses[n_addresses++] = strdup (temp_buffer + 7);
      else {
        msg = (char *)_("Warning plugin error");
        result = STATE_WARNING;
      }
    }

    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
             strstr (chld_out.line[i], "Addresses:"))) {
      temp_buffer = index (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading spaces */
      for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty host name string\n"),
             NSLOOKUP_COMMAND);
      }

      addresses[n_addresses++] = strdup(temp_buffer);
    }
    else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }


    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) {
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Ejemplo n.º 6
0
int
main (int argc, char **argv)
{
	int result = STATE_UNKNOWN;
	int i;
	char *status = NULL;
	struct timeval tv;
	size_t len;
	int match = -1;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* determine program- and service-name quickly */
	progname = strrchr(argv[0], '/');
	if(progname != NULL) progname++;
	else progname = argv[0];

	len = strlen(progname);
	if(len > 6 && !memcmp(progname, "check_", 6)) {
		SERVICE = strdup(progname + 6);
		for(i = 0; i < len - 6; i++)
			SERVICE[i] = toupper(SERVICE[i]);
	}

	/* set up a resonable buffer at first (will be realloc()'ed if
	 * user specifies other options) */
	server_expect = calloc(sizeof(char *), 2);

	/* determine defaults for this service's protocol */
	if (!strncmp(SERVICE, "UDP", 3)) {
		PROTOCOL = IPPROTO_UDP;
	}
	else if (!strncmp(SERVICE, "FTP", 3)) {
		EXPECT = "220";
		QUIT = "QUIT\r\n";
		PORT = 21;
	}
	else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
		EXPECT = "+OK";
		QUIT = "QUIT\r\n";
		PORT = 110;
	}
	else if (!strncmp(SERVICE, "SMTP", 4)) {
		EXPECT = "220";
		QUIT = "QUIT\r\n";
		PORT = 25;
	}
	else if (!strncmp(SERVICE, "IMAP", 4)) {
		EXPECT = "* OK";
		QUIT = "a1 LOGOUT\r\n";
		PORT = 143;
	}
#ifdef HAVE_SSL
	else if (!strncmp(SERVICE, "SIMAP", 5)) {
		EXPECT = "* OK";
		QUIT = "a1 LOGOUT\r\n";
		flags |= FLAG_SSL;
		PORT = 993;
	}
	else if (!strncmp(SERVICE, "SPOP", 4)) {
		EXPECT = "+OK";
		QUIT = "QUIT\r\n";
		flags |= FLAG_SSL;
		PORT = 995;
	}
	else if (!strncmp(SERVICE, "SSMTP", 5)) {
		EXPECT = "220";
		QUIT = "QUIT\r\n";
		flags |= FLAG_SSL;
		PORT = 465;
	}
	else if (!strncmp(SERVICE, "JABBER", 6)) {
		SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
		EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
		QUIT = "</stream:stream>\n";
		flags |= FLAG_HIDE_OUTPUT;
		PORT = 5222;
	}
	else if (!strncmp (SERVICE, "NNTPS", 5)) {
		server_expect_count = 2;
		server_expect[0] = "200";
		server_expect[1] = "201";
		QUIT = "QUIT\r\n";
		flags |= FLAG_SSL;
		PORT = 563;
	}
#endif
	else if (!strncmp (SERVICE, "NNTP", 4)) {
		server_expect_count = 2;
		server_expect = malloc(sizeof(char *) * server_expect_count);
		server_expect[0] = strdup("200");
		server_expect[1] = strdup("201");
		QUIT = "QUIT\r\n";
		PORT = 119;
	}
	else if (!strncmp(SERVICE, "CLAMD", 5)) {
		SEND = "PING";
		EXPECT = "PONG";
		QUIT = NULL;
		PORT = 3310;
	}
	/* fallthrough check, so it's supposed to use reverse matching */
	else if (strcmp (SERVICE, "TCP"))
		usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));

	server_address = "127.0.0.1";
	server_port = PORT;
	server_send = SEND;
	server_quit = QUIT;
	status = NULL;

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	if(flags & FLAG_VERBOSE) {
		printf("Using service %s\n", SERVICE);
		printf("Port: %d\n", server_port);
		printf("flags: 0x%x\n", (int)flags);
	}

	if(EXPECT && !server_expect_count)
		server_expect_count++;

	if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
		usage(_("With UDP checks, a send/expect string must be specified."));
	}

	/* set up the timer */
	signal (SIGALRM, socket_timeout_alarm_handler);
	alarm (socket_timeout);

	/* try to connect to the host at the given port number */
	gettimeofday (&tv, NULL);

	result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
	if (result == STATE_CRITICAL) return STATE_CRITICAL;

#ifdef HAVE_SSL
	if (flags & FLAG_SSL){
		result = np_net_ssl_init(sd);
		if (result == STATE_OK && check_cert == TRUE) {
			result = np_net_ssl_check_cert(days_till_exp);
		}
	}
	if(result != STATE_OK || check_cert == TRUE){
		np_net_ssl_cleanup();
		if(sd) close(sd);
		return result;
	}
#endif /* HAVE_SSL */

	if (server_send != NULL) {		/* Something to send? */
		my_send(server_send, strlen(server_send));
	}

	if (delay > 0) {
		tv.tv_sec += delay;
		sleep (delay);
	}

	if(flags & FLAG_VERBOSE) {
		if (server_send) {
			printf("Send string: %s\n", server_send);
		}
		if (server_quit) {
			printf("Quit string: %s\n", server_quit);
		}
		printf("server_expect_count: %d\n", (int)server_expect_count);
		for(i = 0; i < server_expect_count; i++)
			printf("\t%d: %s\n", i, server_expect[i]);
	}

	/* if(len) later on, we know we have a non-NULL response */
	len = 0;
	if (server_expect_count) {

		/* watch for the expect string */
		while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
			status = realloc(status, len + i + 1);
			memcpy(&status[len], buffer, i);
			len += i;

			/* stop reading if user-forced or data-starved */
			if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
				break;

			if (maxbytes && len >= maxbytes)
				break;
		}

		/* no data when expected, so return critical */
		if (len == 0)
			die (STATE_CRITICAL, _("No data received from host\n"));

		/* force null-termination and strip whitespace from end of output */
		status[len--] = '\0';
		/* print raw output if we're debugging */
		if(flags & FLAG_VERBOSE)
			printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
			       (int)len + 1, status);
		while(isspace(status[len])) status[len--] = '\0';

		match = np_expect_match(status,
                                server_expect,
                                server_expect_count,
                                (flags & FLAG_MATCH_ALL ? TRUE : FALSE),
                                (flags & FLAG_EXACT_MATCH ? TRUE : FALSE),
                                (flags & FLAG_VERBOSE ? TRUE : FALSE));
	}

	if (server_quit != NULL) {
		my_send(server_quit, strlen(server_quit));
	}
#ifdef HAVE_SSL
	np_net_ssl_cleanup();
#endif
	if (sd) close (sd);

	microsec = deltime (tv);
	elapsed_time = (double)microsec / 1.0e6;

	if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
		result = STATE_CRITICAL;
	else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
		result = STATE_WARNING;

	/* did we get the response we hoped? */
	if(match == FALSE && result != STATE_CRITICAL)
		result = expect_mismatch_state;

	/* reset the alarm */
	alarm (0);

	/* this is a bit stupid, because we don't want to print the
	 * response time (which can look ok to the user) if we didn't get
	 * the response we were looking for. if-else */
	printf("%s %s - ", SERVICE, state_text(result));

	if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT))
		printf("Unexpected response from host/socket: %s", status);
	else {
		if(match == FALSE)
			printf("Unexpected response from host/socket on ");
		else
			printf("%.3f second response time on ", elapsed_time);
		if(server_address[0] != '/')
			printf("port %d", server_port);
		else
			printf("socket %s", server_address);
	}

	if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len)
		printf (" [%s]", status);

	/* perf-data doesn't apply when server doesn't talk properly,
	 * so print all zeroes on warn and crit. Use fperfdata since
	 * localisation settings can make different outputs */
	if(match == FALSE)
		printf ("|%s",
				fperfdata ("time", elapsed_time, "s",
				(flags & FLAG_TIME_WARN ? TRUE : FALSE), 0,
				(flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0,
				TRUE, 0,
				TRUE, socket_timeout)
			);
	else
		printf("|%s",
				fperfdata ("time", elapsed_time, "s",
				(flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time,
				(flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time,
				TRUE, 0,
				TRUE, socket_timeout)
			);

	putchar('\n');
	return result;
}
int main(int argc, char ** argv)
{
  struct memcached_st *mc;
  memcached_return_t  rc;
  char                key[32];
  u_int32_t           keylen;
  char               *val;
  size_t              value_len;
  uint32_t            flags;
  struct timeval      tv;
  long                microsec;
  double              elapsed_time;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Parse extra opts if any */
  argv = np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR)
    usage4 (_("Could not parse arguments"));

  TRACE("%s",">>main");

  // initialize
  gettimeofday(&tv, NULL);
  mc = memcached_create(NULL);
  if (mc == NULL) {
    printf("MEMCACHED %s: failed to memcached_create\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  TRACE("[server]%s:%d", mc_host, (int)mc_port);
  rc = memcached_server_add(mc, mc_host, (in_port_t)mc_port);
  TRACE("[mc_server_add rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to memcached_server_add (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  memcached_behavior_set(mc, MEMCACHED_BEHAVIOR_TCP_NODELAY, 1);

  srand(time(NULL) & getpid());
  sprintf(key, "%d_%s", rand(), mc_host);
  keylen = strlen(key);
  TRACE("[key]%s[keylen]%d", key, keylen);

  val = (char *)calloc(1, strlen(TEST_VAL)+1);
  sprintf(val, "%s", TEST_VAL);
  TRACE("[val]%s", val);

  // set
  TRACE("[expire]%d", mc_expire);
  rc = memcached_set(mc, key, keylen, val, strlen(val), mc_expire, 0);
  TRACE("[set rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to set (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }
  free(val);

  // get
  val = (char *)memcached_get(mc, key, keylen, &value_len, &flags, &rc);
  TRACE("[val]%s", val);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to get after set\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  free(val);

  // delete
  rc = memcached_delete(mc, key, keylen, 0);
  TRACE("[delete rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to delete (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  // get
  val = (char *)memcached_get(mc, key, keylen, &value_len, &flags, &rc);
  TRACE("[val]%s", val);
  if (rc != MEMCACHED_NOTFOUND) {
    printf("MEMCACHED %s: failed to get after delete\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  free(val);

  memcached_free(mc);

  microsec = deltime(tv);
  elapsed_time = (double)microsec / 1.0e6;
  printf("MEMCACHED %s: %.3f seconds\n", _("OK"), elapsed_time);

  return 0;
}
int main(int argc, char ** argv)
{
  struct memcached_st *mc;
  struct memcached_stat_st *stats;
  memcached_return_t rc;
  long             cur_conn = -1;
  int              status;
  char*            status_msg;
  struct timeval   tv;
  long             microsec;
  double           elapsed_time;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Parse extra opts if any */
  argv = np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR)
    usage4 (_("Could not parse arguments"));

  TRACE("%s",">>main");

  // initialize
  gettimeofday(&tv, NULL);
  mc = memcached_create(NULL);
  if (mc == NULL) {
    printf("MEMCACHED %s: failed to memcached_create\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  TRACE("[server]%s:%s", mc_host, mc_port);
  rc = memcached_server_add(mc, mc_host, (in_port_t)mc_port);
  TRACE("[mc_server_add rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to memcached_server_add (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  memcached_behavior_set(mc, MEMCACHED_BEHAVIOR_TCP_NODELAY, 1);

  stats = memcached_stat(mc, NULL, &rc);
  if (! stats) {
    printf("MEMCACHED %s: failed to memcached_stats\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }

  cur_conn = stats->curr_connections;

  memcached_stat_free(mc, stats);
  memcached_free(mc);

  status = get_status(cur_conn, my_thresholds);

  status_msg = _("CRITICAL");
  if (status == STATE_OK) {
      status_msg = _("OK");
  } else if (status == STATE_WARNING) {
      status_msg = _("WARNING");
  } else if (status == STATE_CRITICAL) {
      status_msg = _("CRITICAL");
  }

  microsec = deltime(tv);
  elapsed_time = (double)microsec / 1.0e6;
  printf("MEMCACHED %s: conn %ld, %.3f seconds\n", status_msg, cur_conn, elapsed_time);

  return status;
}
Ejemplo n.º 9
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char query_found[16] = "";
  char *temp_buffer = NULL;
  int non_authoritative = TRUE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s %s", NSLOOKUP_COMMAND, query_type, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], "Authoritative answers can be found from:")) {
      non_authoritative = FALSE;
      break;
    }
    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    /* begin handling types of records */
    if (strstr (chld_out.line[i], "AAAA address")) {
      if (verbose) printf("Found AAAA record\n");
      temp_buffer = rindex (chld_out.line[i], ' ');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=AAAA", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "exchanger =")) {
      if (verbose) printf("Found MX record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=MX", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "service =")) {
      if (verbose) printf("Found SRV record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SRV", sizeof(query_found));
    }
    else if (accept_cname && strstr (chld_out.line[i], "canonical name =")) {
      if (verbose) printf("Found CNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=CNAME", sizeof(query_found));
    }
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") || strstr (chld_out.line[i], "Addresses:"))) {
      if (verbose) printf("Found A record\n");
      temp_buffer = index (chld_out.line[i], ':');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=A", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "nameserver =")) {
      if (verbose) printf("Found NS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=NS", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "dname =")) {
      if (verbose) printf("Found DNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=DNAME", sizeof(query_found));
    }
    /* must be after other records with "name" as an identifier, as ptr does not spefify */
    else if (strstr (chld_out.line[i], "name =")) {
      if (verbose) printf("Found PTR record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=PTR", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "protocol =")) {
      if (verbose) printf("Found WKS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=WKS", sizeof(query_found));
    }
    /* TODO: needs to be changed to handle txt output and max size of txt recrods */
    else if (strstr (chld_out.line[i], "text =")) {
      if (verbose) printf("Found TXT record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=TXT", sizeof(query_found));
    }
    /* only matching for origin records, if requested other fields could be included at a later date */
    else if (strstr (chld_out.line[i], "origin =")) {
      if (verbose) printf("Found SOA record\n");
      temp_buffer = index(chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SOA", sizeof(query_found));
    }

    if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }

    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) { 
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && !non_authoritative) {
    result = STATE_CRITICAL;

    if (strncmp(dns_server, "", 1))
      xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
    else
      xasprintf(&msg, _("there is no authoritative server for %s"), query_address);
  }

  /* compare query type to query found, if query type is ANY we can skip as any record is accepted*/
  if (result == STATE_OK && strncmp(query_type, "", 1) && (strncmp(query_type, "-querytype=ANY", 15) != 0)) {
    if (strncmp(query_type, query_found, 16) != 0) {
      if (verbose)
        printf( "Failed query for %s only found %s, or nothing\n", query_type, query_found);
      result = STATE_CRITICAL;
      xasprintf(&msg, _("query type of %s was not found for %s"), query_type, query_address);
    }
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  FALSE, 0,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  FALSE, 0,
                                  TRUE, 0, FALSE, 0));
    } else
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Ejemplo n.º 10
0
int
ssh_connect_p (char *haddr, int hport, char *remote_version, char * remote_fingerprint)
{
	struct timeval tv;
	double elapsed_time;

	ssh_session my_ssh_session;
	int  version;
	int myversion;
	int hlen;
	int rc;
	int state;
	int i;
	unsigned char *hash = NULL;
	char *  fingerprint;
	int in_known_host;

	int sshv1,sshv2,sshv3;

	gettimeofday(&tv, NULL);

	my_ssh_session = ssh_new();

	if (my_ssh_session == NULL)
		return STATE_CRITICAL;

	ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, haddr);
	ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &hport);
	rc = ssh_connect(my_ssh_session);
	if (rc != SSH_OK) {
		printf ("Connect to Server failed\n");
		exit (STATE_CRITICAL);
	}
	in_known_host=-1;
	state = ssh_is_server_known(my_ssh_session);
	hlen = ssh_get_pubkey_hash(my_ssh_session, &hash);

	/* Get the finger print as a string */
	fingerprint = ssh_get_hexa(hash, hlen);
	if(remote_fingerprint && strcmp(remote_fingerprint, "known_host") == NULL) {
		if(state != SSH_SERVER_KNOWN_OK) {
			printf ("SSH CRITICAL - Fingerprint (%s) checked in known_hosts failed\n", remote_fingerprint,fingerprint);
			exit(STATE_CRITICAL);
		} else {
			in_known_host=1;
		}
	}

	/* FIXME: This alwats eval to false... */
	if(remote_fingerprint && strcmp(remote_fingerprint, "known_host") && strcmp(remote_fingerprint, fingerprint)) {
		printf ("SSH CRITICAL - Fingerprint (%s) mismatched %s\n", remote_fingerprint,fingerprint);
		free(fingerprint);
		exit(STATE_CRITICAL);
	}

	version = ssh_get_openssh_version(my_ssh_session);
	if(remote_version && sscanf(remote_version, "%d.%d.%d", &sshv1, &sshv2, &sshv3)) {
		myversion = SSH_VERSION_INT(sshv1, sshv2, sshv3);
		if(version < myversion) {
			printf ("SSH WARNING version on server is below %s\n", remote_version);
			exit(STATE_CRITICAL);
		}
	}

	elapsed_time = (double)deltime(tv) / 1.0e6;

	printf (_("SSH OK - fingerprint: %s (Version %d) known_host_check:%d | %s\n"),
	        fingerprint, version,in_known_host, fperfdata("time", elapsed_time, "s",
	        FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));
	free(fingerprint);
	ssh_disconnect(my_ssh_session);
	ssh_free(my_ssh_session);
	exit(STATE_OK);

}