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