19e9aea881467733e55726a650baa7afae49b9b4
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 # ifdef USE_OPENSSL
57 int check_certificate (X509 **);
58 # endif
59 #endif
61 enum {
62 SMTP_PORT = 25
63 };
64 #define SMTP_EXPECT "220"
65 #define SMTP_HELO "HELO "
66 #define SMTP_EHLO "EHLO "
67 #define SMTP_QUIT "QUIT\r\n"
68 #define SMTP_STARTTLS "STARTTLS\r\n"
70 #ifndef HOST_MAX_BYTES
71 #define HOST_MAX_BYTES 255
72 #endif
74 #define EHLO_SUPPORTS_STARTTLS 1
76 int process_arguments (int, char **);
77 int validate_arguments (void);
78 void print_help (void);
79 void print_usage (void);
80 int myrecv(void);
81 int my_close(void);
83 #ifdef HAVE_REGEX_H
84 #include <regex.h>
85 char regex_expect[MAX_INPUT_BUFFER] = "";
86 regex_t preg;
87 regmatch_t pmatch[10];
88 char timestamp[20] = "";
89 char errbuf[MAX_INPUT_BUFFER];
90 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
91 int eflags = 0;
92 int errcode, excode;
93 #endif
95 int server_port = SMTP_PORT;
96 char *server_address = NULL;
97 char *server_expect = NULL;
98 int smtp_use_dummycmd = 0;
99 char *mail_command = NULL;
100 char *from_arg = NULL;
101 int ncommands=0;
102 int command_size=0;
103 int nresponses=0;
104 int response_size=0;
105 char **commands = NULL;
106 char **responses = NULL;
107 int warning_time = 0;
108 int check_warning_time = FALSE;
109 int critical_time = 0;
110 int check_critical_time = FALSE;
111 int verbose = 0;
112 int use_ssl = FALSE;
113 short use_ehlo = FALSE;
114 short ssl_established = TRUE;
115 char *localhostname = NULL;
116 int sd;
117 char buffer[MAX_INPUT_BUFFER];
118 enum {
119 TCP_PROTOCOL = 1,
120 UDP_PROTOCOL = 2,
121 MAXBUF = 1024
122 };
124 int
125 main (int argc, char **argv)
126 {
127 short supports_tls=FALSE;
128 int n = 0;
129 double elapsed_time;
130 long microsec;
131 int result = STATE_UNKNOWN;
132 char *cmd_str = NULL;
133 char *helocmd = NULL;
134 struct timeval tv;
135 struct hostent *hp;
137 setlocale (LC_ALL, "");
138 bindtextdomain (PACKAGE, LOCALEDIR);
139 textdomain (PACKAGE);
141 if (process_arguments (argc, argv) == ERROR)
142 usage4 (_("Could not parse arguments"));
144 /* initialize the HELO command with the localhostname */
145 if(! localhostname){
146 localhostname = malloc (HOST_MAX_BYTES);
147 if(!localhostname){
148 printf(_("malloc() failed!\n"));
149 return STATE_CRITICAL;
150 }
151 if(gethostname(localhostname, HOST_MAX_BYTES)){
152 printf(_("gethostname() failed!\n"));
153 return STATE_CRITICAL;
154 }
155 hp = gethostbyname(localhostname);
156 if(!hp) helocmd = localhostname;
157 else helocmd = hp->h_name;
158 } else {
159 helocmd = localhostname;
160 }
161 if(use_ehlo)
162 asprintf (&helocmd, "%s%s%s", SMTP_EHLO, helocmd, "\r\n");
163 else
164 asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
166 /* initialize the MAIL command with optional FROM command */
167 asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
169 if (verbose && smtp_use_dummycmd)
170 printf ("FROM CMD: %s", cmd_str);
172 /* initialize alarm signal handling */
173 (void) signal (SIGALRM, socket_timeout_alarm_handler);
175 /* set socket timeout */
176 (void) alarm (socket_timeout);
178 /* start timer */
179 gettimeofday (&tv, NULL);
181 /* try to connect to the host at the given port number */
182 result = my_tcp_connect (server_address, server_port, &sd);
184 if (result == STATE_OK) { /* we connected */
186 /* watch for the SMTP connection string and */
187 /* return a WARNING status if we couldn't read any data */
188 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
189 printf (_("recv() failed\n"));
190 result = STATE_WARNING;
191 }
192 else {
193 if (verbose)
194 printf ("%s", buffer);
195 /* strip the buffer of carriage returns */
196 strip (buffer);
197 /* make sure we find the response we are looking for */
198 if (!strstr (buffer, server_expect)) {
199 if (server_port == SMTP_PORT)
200 printf (_("Invalid SMTP response received from host\n"));
201 else
202 printf (_("Invalid SMTP response received from host on port %d\n"),
203 server_port);
204 result = STATE_WARNING;
205 }
206 }
208 /* send the HELO/EHLO command */
209 send(sd, helocmd, strlen(helocmd), 0);
211 /* allow for response to helo command to reach us */
212 if(read (sd, buffer, MAXBUF - 1) < 0){
213 printf (_("recv() failed\n"));
214 return STATE_WARNING;
215 } else if(use_ehlo){
216 buffer[MAXBUF-1]='\0';
217 if(strstr(buffer, "250 STARTTLS") != NULL ||
218 strstr(buffer, "250-STARTTLS") != NULL){
219 supports_tls=TRUE;
220 }
221 }
223 if(use_ssl && ! supports_tls){
224 printf(_("WARNING - TLS not supported by server\n"));
225 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
226 return STATE_WARNING;
227 }
229 #ifdef HAVE_SSL
230 if(use_ssl) {
231 /* send the STARTTLS command */
232 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
234 recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); /* wait for it */
235 if (!strstr (buffer, server_expect)) {
236 printf (_("Server does not support STARTTLS\n"));
237 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
238 return STATE_UNKNOWN;
239 }
240 if(connect_STARTTLS() != OK) {
241 printf (_("CRITICAL - Cannot create SSL context.\n"));
242 return STATE_CRITICAL;
243 } else {
244 ssl_established = TRUE;
245 }
246 # ifdef USE_OPENSSL
247 if ( check_cert ) {
248 if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
249 result = check_certificate (&server_cert);
250 X509_free(server_cert);
251 }
252 else {
253 printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
254 result = STATE_CRITICAL;
256 }
257 my_close();
258 return result;
259 }
260 # endif /* USE_OPENSSL */
261 }
262 #endif
264 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
265 * to do something useful. This can be prevented by giving a command
266 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
267 *
268 * According to rfc821 you can include a null reversepath in the from command
269 * - but a log message is generated on the smtp server.
270 *
271 * You can disable sending mail_command with '--nocommand'
272 * Use the -f option to provide a FROM address
273 */
274 if (smtp_use_dummycmd) {
275 #ifdef HAVE_SSL
276 if (use_ssl)
277 SSL_write(ssl, cmd_str, strlen(cmd_str));
278 else
279 #endif
280 send(sd, cmd_str, strlen(cmd_str), 0);
281 myrecv();
282 if (verbose)
283 printf("%s", buffer);
284 }
286 while (n < ncommands) {
287 asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
288 #ifdef HAVE_SSL
289 if (use_ssl)
290 SSL_write(ssl,cmd_str, strlen(cmd_str));
291 else
292 #endif
293 send(sd, cmd_str, strlen(cmd_str), 0);
294 myrecv();
295 if (verbose)
296 printf("%s", buffer);
297 strip (buffer);
298 if (n < nresponses) {
299 #ifdef HAVE_REGEX_H
300 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
301 errcode = regcomp (&preg, responses[n], cflags);
302 if (errcode != 0) {
303 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
304 printf (_("Could Not Compile Regular Expression"));
305 return ERROR;
306 }
307 excode = regexec (&preg, buffer, 10, pmatch, eflags);
308 if (excode == 0) {
309 result = STATE_OK;
310 }
311 else if (excode == REG_NOMATCH) {
312 result = STATE_WARNING;
313 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
314 }
315 else {
316 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
317 printf (_("Execute Error: %s\n"), errbuf);
318 result = STATE_UNKNOWN;
319 }
320 #else
321 if (strstr(buffer, responses[n])!=buffer) {
322 result = STATE_WARNING;
323 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
324 }
325 #endif
326 }
327 n++;
328 }
330 /* tell the server we're done */
331 #ifdef HAVE_SSL
332 if (use_ssl)
333 SSL_write(ssl,SMTP_QUIT, strlen (SMTP_QUIT));
334 else
335 #endif
336 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
338 /* finally close the connection */
339 close (sd);
340 }
342 /* reset the alarm */
343 alarm (0);
345 microsec = deltime (tv);
346 elapsed_time = (double)microsec / 1.0e6;
348 if (result == STATE_OK) {
349 if (check_critical_time && elapsed_time > (double) critical_time)
350 result = STATE_CRITICAL;
351 else if (check_warning_time && elapsed_time > (double) warning_time)
352 result = STATE_WARNING;
353 }
355 printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
356 state_text (result), elapsed_time,
357 verbose?", ":"", verbose?buffer:"",
358 fperfdata ("time", elapsed_time, "s",
359 (int)check_warning_time, warning_time,
360 (int)check_critical_time, critical_time,
361 TRUE, 0, FALSE, 0));
363 return result;
364 }
368 /* process command-line arguments */
369 int
370 process_arguments (int argc, char **argv)
371 {
372 int c;
374 int option = 0;
375 static struct option longopts[] = {
376 {"hostname", required_argument, 0, 'H'},
377 {"expect", required_argument, 0, 'e'},
378 {"critical", required_argument, 0, 'c'},
379 {"warning", required_argument, 0, 'w'},
380 {"timeout", required_argument, 0, 't'},
381 {"port", required_argument, 0, 'p'},
382 {"from", required_argument, 0, 'f'},
383 {"fqdn", required_argument, 0, 'F'},
384 {"command", required_argument, 0, 'C'},
385 {"response", required_argument, 0, 'R'},
386 {"nocommand", required_argument, 0, 'n'},
387 {"verbose", no_argument, 0, 'v'},
388 {"version", no_argument, 0, 'V'},
389 {"use-ipv4", no_argument, 0, '4'},
390 {"use-ipv6", no_argument, 0, '6'},
391 {"help", no_argument, 0, 'h'},
392 {"starttls",no_argument,0,'S'},
393 {"certificate",required_argument,0,'D'},
394 {0, 0, 0, 0}
395 };
397 if (argc < 2)
398 return ERROR;
400 for (c = 1; c < argc; c++) {
401 if (strcmp ("-to", argv[c]) == 0)
402 strcpy (argv[c], "-t");
403 else if (strcmp ("-wt", argv[c]) == 0)
404 strcpy (argv[c], "-w");
405 else if (strcmp ("-ct", argv[c]) == 0)
406 strcpy (argv[c], "-c");
407 }
409 while (1) {
410 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:",
411 longopts, &option);
413 if (c == -1 || c == EOF)
414 break;
416 switch (c) {
417 case 'H': /* hostname */
418 if (is_host (optarg)) {
419 server_address = optarg;
420 }
421 else {
422 usage2 (_("Invalid hostname/address"), optarg);
423 }
424 break;
425 case 'p': /* port */
426 if (is_intpos (optarg))
427 server_port = atoi (optarg);
428 else
429 usage4 (_("Port must be a positive integer"));
430 break;
431 case 'F':
432 /* localhostname */
433 localhostname = strdup(optarg);
434 break;
435 case 'f': /* from argument */
436 from_arg = optarg;
437 smtp_use_dummycmd = 1;
438 break;
439 case 'e': /* server expect string on 220 */
440 server_expect = optarg;
441 break;
442 case 'C': /* commands */
443 if (ncommands >= command_size) {
444 commands = realloc (commands, command_size+8);
445 if (commands == NULL)
446 die (STATE_UNKNOWN,
447 _("Could not realloc() units [%d]\n"), ncommands);
448 }
449 commands[ncommands] = optarg;
450 ncommands++;
451 break;
452 case 'R': /* server responses */
453 if (nresponses >= response_size) {
454 responses = realloc (responses, response_size+8);
455 if (responses == NULL)
456 die (STATE_UNKNOWN,
457 _("Could not realloc() units [%d]\n"), nresponses);
458 }
459 responses[nresponses] = optarg;
460 nresponses++;
461 break;
462 case 'c': /* critical time threshold */
463 if (is_intnonneg (optarg)) {
464 critical_time = atoi (optarg);
465 check_critical_time = TRUE;
466 }
467 else {
468 usage4 (_("Critical time must be a positive integer"));
469 }
470 break;
471 case 'w': /* warning time threshold */
472 if (is_intnonneg (optarg)) {
473 warning_time = atoi (optarg);
474 check_warning_time = TRUE;
475 }
476 else {
477 usage4 (_("Warning time must be a positive integer"));
478 }
479 break;
480 case 'v': /* verbose */
481 verbose++;
482 break;
483 case 't': /* timeout */
484 if (is_intnonneg (optarg)) {
485 socket_timeout = atoi (optarg);
486 }
487 else {
488 usage4 (_("Timeout interval must be a positive integer"));
489 }
490 break;
491 case 'S':
492 /* starttls */
493 use_ssl = TRUE;
494 use_ehlo = TRUE;
495 break;
496 case 'D':
497 /* Check SSL cert validity */
498 #ifdef USE_OPENSSL
499 if (!is_intnonneg (optarg))
500 usage2 ("Invalid certificate expiration period",optarg);
501 days_till_exp = atoi (optarg);
502 check_cert = TRUE;
503 #else
504 usage (_("SSL support not available - install OpenSSL and recompile"));
505 #endif
506 break;
507 case '4':
508 address_family = AF_INET;
509 break;
510 case '6':
511 #ifdef USE_IPV6
512 address_family = AF_INET6;
513 #else
514 usage4 (_("IPv6 support not available"));
515 #endif
516 break;
517 case 'V': /* version */
518 print_revision (progname, revision);
519 exit (STATE_OK);
520 case 'h': /* help */
521 print_help ();
522 exit (STATE_OK);
523 case '?': /* help */
524 usage2 (_("Unknown argument"), optarg);
525 }
526 }
528 c = optind;
529 if (server_address == NULL) {
530 if (argv[c]) {
531 if (is_host (argv[c]))
532 server_address = argv[c];
533 else
534 usage2 (_("Invalid hostname/address"), argv[c]);
535 }
536 else {
537 asprintf (&server_address, "127.0.0.1");
538 }
539 }
541 if (server_expect == NULL)
542 server_expect = strdup (SMTP_EXPECT);
544 if (mail_command == NULL)
545 mail_command = strdup("MAIL ");
547 if (from_arg==NULL)
548 from_arg = strdup(" ");
550 return validate_arguments ();
551 }
555 int
556 validate_arguments (void)
557 {
558 return OK;
559 }
563 void
564 print_help (void)
565 {
566 char *myport;
567 asprintf (&myport, "%d", SMTP_PORT);
569 print_revision (progname, revision);
571 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
572 printf (COPYRIGHT, copyright, email);
574 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
576 print_usage ();
578 printf (_(UT_HELP_VRSN));
580 printf (_(UT_HOST_PORT), 'p', myport);
582 printf (_(UT_IPv46));
584 printf (_("\
585 -e, --expect=STRING\n\
586 String to expect in first line of server response (default: '%s')\n\
587 -n, nocommand\n\
588 Suppress SMTP command\n\
589 -C, --command=STRING\n\
590 SMTP command (may be used repeatedly)\n\
591 -R, --command=STRING\n\
592 Expected response to command (may be used repeatedly)\n\
593 -f, --from=STRING\n\
594 FROM-address to include in MAIL command, required by Exchange 2000\n"),
595 SMTP_EXPECT);
596 #ifdef HAVE_SSL
597 printf (_("\
598 -D, --certificate=INTEGER\n\
599 Minimum number of days a certificate has to be valid.\n\
600 -S, --starttls\n\
601 Use STARTTLS for the connection.\n"));
602 #endif
604 printf (_(UT_WARN_CRIT));
606 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
608 printf (_(UT_VERBOSE));
610 printf(_("\n\
611 Successul connects return STATE_OK, refusals and timeouts return\n\
612 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
613 connects, but incorrect reponse messages from the host result in\n\
614 STATE_WARNING return values.\n"));
616 printf (_(UT_SUPPORT));
617 }
621 void
622 print_usage (void)
623 {
624 printf ("\
625 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
626 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
627 }
629 #ifdef HAVE_SSL
630 int
631 connect_STARTTLS (void)
632 {
633 SSL_METHOD *meth;
635 /* Initialize SSL context */
636 SSLeay_add_ssl_algorithms ();
637 meth = SSLv23_client_method ();
638 SSL_load_error_strings ();
639 if ((ctx = SSL_CTX_new (meth)) == NULL)
640 {
641 printf(_("CRITICAL - Cannot create SSL context.\n"));
642 return STATE_CRITICAL;
643 }
644 /* do the SSL handshake */
645 if ((ssl = SSL_new (ctx)) != NULL)
646 {
647 SSL_set_fd (ssl, sd);
648 /* original version checked for -1
649 I look for success instead (1) */
650 if (SSL_connect (ssl) == 1)
651 return OK;
652 # ifdef USE_OPENSSL
653 ERR_print_errors_fp (stderr);
654 # endif
655 }
656 else
657 {
658 printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
659 }
660 my_close();
662 return STATE_CRITICAL;
663 }
665 # ifdef USE_OPENSSL
666 int
667 check_certificate (X509 ** certificate)
668 {
669 ASN1_STRING *tm;
670 int offset;
671 struct tm stamp;
672 int days_left;
674 /* Retrieve timestamp of certificate */
675 tm = X509_get_notAfter (*certificate);
677 /* Generate tm structure to process timestamp */
678 if (tm->type == V_ASN1_UTCTIME) {
679 if (tm->length < 10) {
680 printf (_("CRITICAL - Wrong time format in certificate.\n"));
681 return STATE_CRITICAL;
682 }
683 else {
684 stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
685 if (stamp.tm_year < 50)
686 stamp.tm_year += 100;
687 offset = 0;
688 }
689 }
690 else {
691 if (tm->length < 12) {
692 printf (_("CRITICAL - Wrong time format in certificate.\n"));
693 return STATE_CRITICAL;
694 }
695 else {
696 stamp.tm_year =
697 (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
698 (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
699 stamp.tm_year -= 1900;
700 offset = 2;
701 }
702 }
703 stamp.tm_mon =
704 (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
705 stamp.tm_mday =
706 (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
707 stamp.tm_hour =
708 (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
709 stamp.tm_min =
710 (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
711 stamp.tm_sec = 0;
712 stamp.tm_isdst = -1;
714 days_left = (mktime (&stamp) - time (NULL)) / 86400;
715 snprintf
716 (timestamp, sizeof(timestamp), "%02d/%02d/%04d %02d:%02d",
717 stamp.tm_mon + 1,
718 stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
720 if (days_left > 0 && days_left <= days_till_exp) {
721 printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
722 return STATE_WARNING;
723 }
724 if (days_left < 0) {
725 printf ("Certificate expired on %s.\n", timestamp);
726 return STATE_CRITICAL;
727 }
729 if (days_left == 0) {
730 printf ("Certificate expires today (%s).\n", timestamp);
731 return STATE_WARNING;
732 }
734 printf ("Certificate will expire on %s.\n", timestamp);
736 return STATE_OK;
737 }
738 # endif /* USE_OPENSSL */
739 #endif
741 int
742 myrecv (void)
743 {
744 int i;
746 #ifdef HAVE_SSL
747 if (use_ssl) {
748 i = SSL_read (ssl, buffer, MAXBUF - 1);
749 }
750 else {
751 #endif
752 i = read (sd, buffer, MAXBUF - 1);
753 #ifdef HAVE_SSL
754 }
755 #endif
756 return i;
757 }
759 int
760 my_close (void)
761 {
762 #ifdef HAVE_SSL
763 if (use_ssl == TRUE && ssl_established == TRUE) {
764 SSL_shutdown (ssl);
765 SSL_free (ssl);
766 SSL_CTX_free (ctx);
767 return 0;
768 }
769 else {
770 #endif
771 return close(sd);
772 #ifdef HAVE_SSL
773 }
774 #endif
775 }