1 /******************************************************************************
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2 of the License, or
6 (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 $Id$
19 ******************************************************************************/
21 const char *progname = "check_smtp";
22 const char *revision = "$Revision$";
23 const char *copyright = "2000-2004";
24 const char *email = "nagiosplug-devel@lists.sourceforge.net";
26 #include "common.h"
27 #include "netutils.h"
28 #include "utils.h"
30 #ifdef HAVE_SSL_H
31 # include <rsa.h>
32 # include <crypto.h>
33 # include <x509.h>
34 # include <pem.h>
35 # include <ssl.h>
36 # include <err.h>
37 #else
38 # ifdef HAVE_OPENSSL_SSL_H
39 # include <openssl/rsa.h>
40 # include <openssl/crypto.h>
41 # include <openssl/x509.h>
42 # include <openssl/pem.h>
43 # include <openssl/ssl.h>
44 # include <openssl/err.h>
45 # endif
46 #endif
48 #ifdef HAVE_SSL
50 int check_cert = FALSE;
51 int days_till_exp;
52 SSL_CTX *ctx;
53 SSL *ssl;
54 X509 *server_cert;
55 int connect_STARTTLS (void);
56 int check_certificate (X509 **);
57 #endif
59 enum {
60 SMTP_PORT = 25
61 };
62 const char *SMTP_EXPECT = "220";
63 const char *SMTP_HELO = "HELO ";
64 const char *SMTP_QUIT = "QUIT\r\n";
65 const char *SMTP_STARTTLS = "STARTTLS\r\n";
67 int process_arguments (int, char **);
68 int validate_arguments (void);
69 void print_help (void);
70 void print_usage (void);
71 int myrecv(void);
72 int my_close(void);
74 #ifdef HAVE_REGEX_H
75 #include <regex.h>
76 char regex_expect[MAX_INPUT_BUFFER] = "";
77 regex_t preg;
78 regmatch_t pmatch[10];
79 char timestamp[20] = "";
80 char errbuf[MAX_INPUT_BUFFER];
81 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
82 int eflags = 0;
83 int errcode, excode;
84 #endif
86 int server_port = SMTP_PORT;
87 char *server_address = NULL;
88 char *server_expect = NULL;
89 int smtp_use_dummycmd = 0;
90 char *mail_command = NULL;
91 char *from_arg = NULL;
92 int ncommands=0;
93 int command_size=0;
94 int nresponses=0;
95 int response_size=0;
96 char **commands = NULL;
97 char **responses = NULL;
98 int warning_time = 0;
99 int check_warning_time = FALSE;
100 int critical_time = 0;
101 int check_critical_time = FALSE;
102 int verbose = 0;
103 int use_ssl = FALSE;
104 int sd;
105 char buffer[MAX_INPUT_BUFFER];
106 enum {
107 TCP_PROTOCOL = 1,
108 UDP_PROTOCOL = 2,
109 MAXBUF = 1024
110 };
112 int
113 main (int argc, char **argv)
114 {
116 int n = 0;
117 double elapsed_time;
118 long microsec;
119 int result = STATE_UNKNOWN;
120 char *cmd_str = NULL;
121 char *helocmd = NULL;
122 struct timeval tv;
124 setlocale (LC_ALL, "");
125 bindtextdomain (PACKAGE, LOCALEDIR);
126 textdomain (PACKAGE);
128 if (process_arguments (argc, argv) == ERROR)
129 usage4 (_("Could not parse arguments"));
131 /* initialize the HELO command with the localhostname */
132 #ifndef HOST_MAX_BYTES
133 #define HOST_MAX_BYTES 255
134 #endif
135 helocmd = malloc (HOST_MAX_BYTES);
136 gethostname(helocmd, HOST_MAX_BYTES);
137 asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
139 /* initialize the MAIL command with optional FROM command */
140 asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
142 if (verbose && smtp_use_dummycmd)
143 printf ("FROM CMD: %s", cmd_str);
145 /* initialize alarm signal handling */
146 (void) signal (SIGALRM, socket_timeout_alarm_handler);
148 /* set socket timeout */
149 (void) alarm (socket_timeout);
151 /* start timer */
152 gettimeofday (&tv, NULL);
154 /* try to connect to the host at the given port number */
155 result = my_tcp_connect (server_address, server_port, &sd);
157 if (result == STATE_OK) { /* we connected */
159 /* watch for the SMTP connection string and */
160 /* return a WARNING status if we couldn't read any data */
161 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
162 printf (_("recv() failed\n"));
163 result = STATE_WARNING;
164 }
165 else {
166 if (verbose)
167 printf ("%s", buffer);
168 /* strip the buffer of carriage returns */
169 strip (buffer);
170 /* make sure we find the response we are looking for */
171 if (!strstr (buffer, server_expect)) {
172 if (server_port == SMTP_PORT)
173 printf (_("Invalid SMTP response received from host\n"));
174 else
175 printf (_("Invalid SMTP response received from host on port %d\n"),
176 server_port);
177 result = STATE_WARNING;
178 }
179 }
181 /* send the HELO command */
182 send(sd, helocmd, strlen(helocmd), 0);
184 /* allow for response to helo command to reach us */
185 read (sd, buffer, MAXBUF - 1);
187 #ifdef HAVE_SSL
188 if(use_ssl) {
189 /* send the STARTTLS command */
190 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
192 recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); /* wait for it */
193 if (!strstr (buffer, server_expect)) {
194 printf (_("Server does not support STARTTLS\n"));
195 return STATE_UNKNOWN;
196 }
197 if(connect_STARTTLS() != OK) {
198 printf (_("CRITICAL - Cannot create SSL context.\n"));
199 return STATE_CRITICAL;
200 }
201 if ( check_cert ) {
202 if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
203 result = check_certificate (&server_cert);
204 X509_free(server_cert);
205 }
206 else {
207 printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
208 result = STATE_CRITICAL;
210 }
211 my_close();
212 return result;
213 }
214 }
215 #endif
217 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
218 * to do something useful. This can be prevented by giving a command
219 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
220 *
221 * According to rfc821 you can include a null reversepath in the from command
222 * - but a log message is generated on the smtp server.
223 *
224 * You can disable sending mail_command with '--nocommand'
225 * Use the -f option to provide a FROM address
226 */
227 if (smtp_use_dummycmd) {
228 #ifdef HAVE_SSL
229 if (use_ssl)
230 SSL_write(ssl, cmd_str, strlen(cmd_str));
231 else
232 #endif
233 send(sd, cmd_str, strlen(cmd_str), 0);
234 myrecv();
235 if (verbose)
236 printf("%s", buffer);
237 }
239 while (n < ncommands) {
240 asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
241 #ifdef HAVE_SSL
242 if (use_ssl)
243 SSL_write(ssl,cmd_str, strlen(cmd_str));
244 else
245 #endif
246 send(sd, cmd_str, strlen(cmd_str), 0);
247 myrecv();
248 if (verbose)
249 printf("%s", buffer);
250 strip (buffer);
251 if (n < nresponses) {
252 #ifdef HAVE_REGEX_H
253 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
254 errcode = regcomp (&preg, responses[n], cflags);
255 if (errcode != 0) {
256 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
257 printf (_("Could Not Compile Regular Expression"));
258 return ERROR;
259 }
260 excode = regexec (&preg, buffer, 10, pmatch, eflags);
261 if (excode == 0) {
262 result = STATE_OK;
263 }
264 else if (excode == REG_NOMATCH) {
265 result = STATE_WARNING;
266 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
267 }
268 else {
269 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
270 printf (_("Execute Error: %s\n"), errbuf);
271 result = STATE_UNKNOWN;
272 }
273 #else
274 if (strstr(buffer, responses[n])!=buffer) {
275 result = STATE_WARNING;
276 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
277 }
278 #endif
279 }
280 n++;
281 }
283 /* tell the server we're done */
284 #ifdef HAVE_SSL
285 if (use_ssl)
286 SSL_write(ssl,SMTP_QUIT, strlen (SMTP_QUIT));
287 else
288 #endif
289 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
291 /* finally close the connection */
292 close (sd);
293 }
295 /* reset the alarm */
296 alarm (0);
298 microsec = deltime (tv);
299 elapsed_time = (double)microsec / 1.0e6;
301 if (result == STATE_OK) {
302 if (check_critical_time && elapsed_time > (double) critical_time)
303 result = STATE_CRITICAL;
304 else if (check_warning_time && elapsed_time > (double) warning_time)
305 result = STATE_WARNING;
306 }
308 printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
309 state_text (result), elapsed_time,
310 verbose?", ":"", verbose?buffer:"",
311 fperfdata ("time", elapsed_time, "s",
312 (int)check_warning_time, warning_time,
313 (int)check_critical_time, critical_time,
314 TRUE, 0, FALSE, 0));
316 return result;
317 }
321 /* process command-line arguments */
322 int
323 process_arguments (int argc, char **argv)
324 {
325 int c;
327 int option = 0;
328 static struct option longopts[] = {
329 {"hostname", required_argument, 0, 'H'},
330 {"expect", required_argument, 0, 'e'},
331 {"critical", required_argument, 0, 'c'},
332 {"warning", required_argument, 0, 'w'},
333 {"timeout", required_argument, 0, 't'},
334 {"port", required_argument, 0, 'p'},
335 {"from", required_argument, 0, 'f'},
336 {"command", required_argument, 0, 'C'},
337 {"response", required_argument, 0, 'R'},
338 {"nocommand", required_argument, 0, 'n'},
339 {"verbose", no_argument, 0, 'v'},
340 {"version", no_argument, 0, 'V'},
341 {"use-ipv4", no_argument, 0, '4'},
342 {"use-ipv6", no_argument, 0, '6'},
343 {"help", no_argument, 0, 'h'},
344 {"starttls",no_argument,0,'S'},
345 {"certificate",required_argument,0,'D'},
346 {0, 0, 0, 0}
347 };
349 if (argc < 2)
350 return ERROR;
352 for (c = 1; c < argc; c++) {
353 if (strcmp ("-to", argv[c]) == 0)
354 strcpy (argv[c], "-t");
355 else if (strcmp ("-wt", argv[c]) == 0)
356 strcpy (argv[c], "-w");
357 else if (strcmp ("-ct", argv[c]) == 0)
358 strcpy (argv[c], "-c");
359 }
361 while (1) {
362 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:",
363 longopts, &option);
365 if (c == -1 || c == EOF)
366 break;
368 switch (c) {
369 case 'H': /* hostname */
370 if (is_host (optarg)) {
371 server_address = optarg;
372 }
373 else {
374 usage2 (_("Invalid hostname/address"), optarg);
375 }
376 break;
377 case 'p': /* port */
378 if (is_intpos (optarg))
379 server_port = atoi (optarg);
380 else
381 usage4 (_("Port must be a positive integer"));
382 break;
383 case 'f': /* from argument */
384 from_arg = optarg;
385 smtp_use_dummycmd = 1;
386 break;
387 case 'e': /* server expect string on 220 */
388 server_expect = optarg;
389 break;
390 case 'C': /* commands */
391 if (ncommands >= command_size) {
392 commands = realloc (commands, command_size+8);
393 if (commands == NULL)
394 die (STATE_UNKNOWN,
395 _("Could not realloc() units [%d]\n"), ncommands);
396 }
397 commands[ncommands] = optarg;
398 ncommands++;
399 break;
400 case 'R': /* server responses */
401 if (nresponses >= response_size) {
402 responses = realloc (responses, response_size+8);
403 if (responses == NULL)
404 die (STATE_UNKNOWN,
405 _("Could not realloc() units [%d]\n"), nresponses);
406 }
407 responses[nresponses] = optarg;
408 nresponses++;
409 break;
410 case 'c': /* critical time threshold */
411 if (is_intnonneg (optarg)) {
412 critical_time = atoi (optarg);
413 check_critical_time = TRUE;
414 }
415 else {
416 usage4 (_("Critical time must be a positive integer"));
417 }
418 break;
419 case 'w': /* warning time threshold */
420 if (is_intnonneg (optarg)) {
421 warning_time = atoi (optarg);
422 check_warning_time = TRUE;
423 }
424 else {
425 usage4 (_("Warning time must be a positive integer"));
426 }
427 break;
428 case 'v': /* verbose */
429 verbose++;
430 break;
431 case 't': /* timeout */
432 if (is_intnonneg (optarg)) {
433 socket_timeout = atoi (optarg);
434 }
435 else {
436 usage4 (_("Timeout interval must be a positive integer"));
437 }
438 break;
439 case 'S':
440 /* starttls */
441 use_ssl = TRUE;
442 break;
443 case 'D':
444 /* Check SSL cert validity */
445 #ifdef HAVE_SSL
446 if (!is_intnonneg (optarg))
447 usage2 ("Invalid certificate expiration period",optarg);
448 days_till_exp = atoi (optarg);
449 check_cert = TRUE;
450 #else
451 usage (_("SSL support not available - install OpenSSL and recompile"));
452 #endif
453 break;
454 case '4':
455 address_family = AF_INET;
456 break;
457 case '6':
458 #ifdef USE_IPV6
459 address_family = AF_INET6;
460 #else
461 usage4 (_("IPv6 support not available"));
462 #endif
463 break;
464 case 'V': /* version */
465 print_revision (progname, revision);
466 exit (STATE_OK);
467 case 'h': /* help */
468 print_help ();
469 exit (STATE_OK);
470 case '?': /* help */
471 usage2 (_("Unknown argument"), optarg);
472 }
473 }
475 c = optind;
476 if (server_address == NULL) {
477 if (argv[c]) {
478 if (is_host (argv[c]))
479 server_address = argv[c];
480 else
481 usage2 (_("Invalid hostname/address"), argv[c]);
482 }
483 else {
484 asprintf (&server_address, "127.0.0.1");
485 }
486 }
488 if (server_expect == NULL)
489 server_expect = strdup (SMTP_EXPECT);
491 if (mail_command == NULL)
492 mail_command = strdup("MAIL ");
494 if (from_arg==NULL)
495 from_arg = strdup(" ");
497 return validate_arguments ();
498 }
502 int
503 validate_arguments (void)
504 {
505 return OK;
506 }
510 void
511 print_help (void)
512 {
513 char *myport;
514 asprintf (&myport, "%d", SMTP_PORT);
516 print_revision (progname, revision);
518 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
519 printf (COPYRIGHT, copyright, email);
521 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
523 print_usage ();
525 printf (_(UT_HELP_VRSN));
527 printf (_(UT_HOST_PORT), 'p', myport);
529 printf (_(UT_IPv46));
531 printf (_("\
532 -e, --expect=STRING\n\
533 String to expect in first line of server response (default: '%s')\n\
534 -n, nocommand\n\
535 Suppress SMTP command\n\
536 -C, --command=STRING\n\
537 SMTP command (may be used repeatedly)\n\
538 -R, --command=STRING\n\
539 Expected response to command (may be used repeatedly)\n\
540 -f, --from=STRING\n\
541 FROM-address to include in MAIL command, required by Exchange 2000\n"),
542 SMTP_EXPECT);
543 #ifdef HAVE_SSL
544 printf (_("\
545 -D, --certificate=INTEGER\n\
546 Minimum number of days a certificate has to be valid.\n\
547 -S, --starttls\n\
548 Use STARTTLS for the connection.\n"));
549 #endif
551 printf (_(UT_WARN_CRIT));
553 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
555 printf (_(UT_VERBOSE));
557 printf(_("\n\
558 Successul connects return STATE_OK, refusals and timeouts return\n\
559 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
560 connects, but incorrect reponse messages from the host result in\n\
561 STATE_WARNING return values.\n"));
563 printf (_(UT_SUPPORT));
564 }
568 void
569 print_usage (void)
570 {
571 printf ("\
572 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
573 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
574 }
576 #ifdef HAVE_SSL
577 int
578 connect_STARTTLS (void)
579 {
580 SSL_METHOD *meth;
582 /* Initialize SSL context */
583 SSLeay_add_ssl_algorithms ();
584 meth = SSLv2_client_method ();
585 SSL_load_error_strings ();
586 if ((ctx = SSL_CTX_new (meth)) == NULL)
587 {
588 printf(_("CRITICAL - Cannot create SSL context.\n"));
589 return STATE_CRITICAL;
590 }
591 /* do the SSL handshake */
592 if ((ssl = SSL_new (ctx)) != NULL)
593 {
594 SSL_set_fd (ssl, sd);
595 /* original version checked for -1
596 I look for success instead (1) */
597 if (SSL_connect (ssl) == 1)
598 return OK;
599 ERR_print_errors_fp (stderr);
600 }
601 else
602 {
603 printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
604 }
605 /* this causes a seg faul
606 not sure why, being sloppy
607 and commenting it out */
608 /* SSL_free (ssl); */
609 SSL_CTX_free(ctx);
610 my_close();
612 return STATE_CRITICAL;
613 }
615 int
616 check_certificate (X509 ** certificate)
617 {
618 ASN1_STRING *tm;
619 int offset;
620 struct tm stamp;
621 int days_left;
623 /* Retrieve timestamp of certificate */
624 tm = X509_get_notAfter (*certificate);
626 /* Generate tm structure to process timestamp */
627 if (tm->type == V_ASN1_UTCTIME) {
628 if (tm->length < 10) {
629 printf (_("CRITICAL - Wrong time format in certificate.\n"));
630 return STATE_CRITICAL;
631 }
632 else {
633 stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
634 if (stamp.tm_year < 50)
635 stamp.tm_year += 100;
636 offset = 0;
637 }
638 }
639 else {
640 if (tm->length < 12) {
641 printf (_("CRITICAL - Wrong time format in certificate.\n"));
642 return STATE_CRITICAL;
643 }
644 else {
645 stamp.tm_year =
646 (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
647 (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
648 stamp.tm_year -= 1900;
649 offset = 2;
650 }
651 }
652 stamp.tm_mon =
653 (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
654 stamp.tm_mday =
655 (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
656 stamp.tm_hour =
657 (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
658 stamp.tm_min =
659 (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
660 stamp.tm_sec = 0;
661 stamp.tm_isdst = -1;
663 days_left = (mktime (&stamp) - time (NULL)) / 86400;
664 snprintf
665 (timestamp, sizeof(timestamp), "%02d/%02d/%04d %02d:%02d",
666 stamp.tm_mon + 1,
667 stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
669 if (days_left > 0 && days_left <= days_till_exp) {
670 printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
671 return STATE_WARNING;
672 }
673 if (days_left < 0) {
674 printf ("Certificate expired on %s.\n", timestamp);
675 return STATE_CRITICAL;
676 }
678 if (days_left == 0) {
679 printf ("Certificate expires today (%s).\n", timestamp);
680 return STATE_WARNING;
681 }
683 printf ("Certificate will expire on %s.\n", timestamp);
685 return STATE_OK;
686 }
687 #endif
689 int
690 myrecv (void)
691 {
692 int i;
694 #ifdef HAVE_SSL
695 if (use_ssl) {
696 i = SSL_read (ssl, buffer, MAXBUF - 1);
697 }
698 else {
699 #endif
700 i = read (sd, buffer, MAXBUF - 1);
701 #ifdef HAVE_SSL
702 }
703 #endif
704 return i;
705 }
707 int
708 my_close (void)
709 {
710 #ifdef HAVE_SSL
711 if (use_ssl == TRUE) {
712 SSL_shutdown (ssl);
713 SSL_free (ssl);
714 SSL_CTX_free (ctx);
715 return 0;
716 }
717 else {
718 #endif
719 return close(sd);
720 #ifdef HAVE_SSL
721 }
722 #endif
723 }