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[10] = "";
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 }
180 #ifdef HAVE_SSL
181 if(use_ssl) {
182 /* send the STARTTLS command */
183 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
185 recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); // wait for it
186 if (!strstr (buffer, server_expect)) {
187 printf (_("Server does not support STARTTLS\n"));
188 return STATE_UNKNOWN;
189 }
190 if(connect_STARTTLS() != OK) {
191 printf (_("CRITICAL - Cannot create SSL context.\n"));
192 return STATE_CRITICAL;
193 }
194 if ( check_cert ) {
195 if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
196 result = check_certificate (&server_cert);
197 X509_free(server_cert);
198 }
199 else {
200 printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
201 result = STATE_CRITICAL;
203 }
204 my_close();
205 return result;
206 }
207 }
208 #endif
209 /* send the HELO command */
210 #ifdef HAVE_SSL
211 if (use_ssl)
212 SSL_write(ssl, helocmd, strlen(helocmd));
213 else
214 #endif
215 send(sd, helocmd, strlen(helocmd), 0);
217 /* allow for response to helo command to reach us */
218 myrecv();
220 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
221 * to do something useful. This can be prevented by giving a command
222 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
223 *
224 * According to rfc821 you can include a null reversepath in the from command
225 * - but a log message is generated on the smtp server.
226 *
227 * You can disable sending mail_command with '--nocommand'
228 * Use the -f option to provide a FROM address
229 */
230 if (smtp_use_dummycmd) {
231 #ifdef HAVE_SSL
232 if (use_ssl)
233 SSL_write(ssl, cmd_str, strlen(cmd_str));
234 else
235 #endif
236 send(sd, cmd_str, strlen(cmd_str), 0);
237 myrecv();
238 if (verbose)
239 printf("%s", buffer);
240 }
242 while (n < ncommands) {
243 asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
244 #ifdef HAVE_SSL
245 if (use_ssl)
246 SSL_write(ssl,cmd_str, strlen(cmd_str));
247 else
248 #endif
249 send(sd, cmd_str, strlen(cmd_str), 0);
250 myrecv();
251 if (verbose)
252 printf("%s", buffer);
253 strip (buffer);
254 if (n < nresponses) {
255 #ifdef HAVE_REGEX_H
256 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
257 //strncpy (regex_expect, responses[n], sizeof (regex_expect) - 1);
258 //regex_expect[sizeof (regex_expect) - 1] = '\0';
259 errcode = regcomp (&preg, responses[n], cflags);
260 if (errcode != 0) {
261 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
262 printf (_("Could Not Compile Regular Expression"));
263 return ERROR;
264 }
265 excode = regexec (&preg, buffer, 10, pmatch, eflags);
266 if (excode == 0) {
267 result = STATE_OK;
268 }
269 else if (excode == REG_NOMATCH) {
270 result = STATE_WARNING;
271 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
272 }
273 else {
274 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
275 printf (_("Execute Error: %s\n"), errbuf);
276 result = STATE_UNKNOWN;
277 }
278 #else
279 if (strstr(buffer, responses[n])!=buffer) {
280 result = STATE_WARNING;
281 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
282 }
283 #endif
284 }
285 n++;
286 }
288 /* tell the server we're done */
289 #ifdef HAVE_SSL
290 if (use_ssl)
291 SSL_write(ssl,SMTP_QUIT, strlen (SMTP_QUIT));
292 else
293 #endif
294 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
296 /* finally close the connection */
297 close (sd);
298 }
300 /* reset the alarm */
301 alarm (0);
303 microsec = deltime (tv);
304 elapsed_time = (double)microsec / 1.0e6;
306 if (result == STATE_OK) {
307 if (check_critical_time && elapsed_time > (double) critical_time)
308 result = STATE_CRITICAL;
309 else if (check_warning_time && elapsed_time > (double) warning_time)
310 result = STATE_WARNING;
311 }
313 printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
314 state_text (result), elapsed_time,
315 verbose?", ":"", verbose?buffer:"",
316 fperfdata ("time", elapsed_time, "s",
317 (int)check_warning_time, warning_time,
318 (int)check_critical_time, critical_time,
319 TRUE, 0, FALSE, 0));
321 return result;
322 }
326 /* process command-line arguments */
327 int
328 process_arguments (int argc, char **argv)
329 {
330 int c;
332 int option = 0;
333 static struct option longopts[] = {
334 {"hostname", required_argument, 0, 'H'},
335 {"expect", required_argument, 0, 'e'},
336 {"critical", required_argument, 0, 'c'},
337 {"warning", required_argument, 0, 'w'},
338 {"timeout", required_argument, 0, 't'},
339 {"port", required_argument, 0, 'p'},
340 {"from", required_argument, 0, 'f'},
341 {"command", required_argument, 0, 'C'},
342 {"response", required_argument, 0, 'R'},
343 {"nocommand", required_argument, 0, 'n'},
344 {"verbose", no_argument, 0, 'v'},
345 {"version", no_argument, 0, 'V'},
346 {"use-ipv4", no_argument, 0, '4'},
347 {"use-ipv6", no_argument, 0, '6'},
348 {"help", no_argument, 0, 'h'},
349 {"starttls",no_argument,0,'S'},
350 {"certificate",required_argument,0,'D'},
351 {0, 0, 0, 0}
352 };
354 if (argc < 2)
355 return ERROR;
357 for (c = 1; c < argc; c++) {
358 if (strcmp ("-to", argv[c]) == 0)
359 strcpy (argv[c], "-t");
360 else if (strcmp ("-wt", argv[c]) == 0)
361 strcpy (argv[c], "-w");
362 else if (strcmp ("-ct", argv[c]) == 0)
363 strcpy (argv[c], "-c");
364 }
366 while (1) {
367 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:",
368 longopts, &option);
370 if (c == -1 || c == EOF)
371 break;
373 switch (c) {
374 case 'H': /* hostname */
375 if (is_host (optarg)) {
376 server_address = optarg;
377 }
378 else {
379 usage2 (_("Invalid hostname/address"), optarg);
380 }
381 break;
382 case 'p': /* port */
383 if (is_intpos (optarg))
384 server_port = atoi (optarg);
385 else
386 usage4 (_("Port must be a positive integer"));
387 break;
388 case 'f': /* from argument */
389 from_arg = optarg;
390 smtp_use_dummycmd = 1;
391 break;
392 case 'e': /* server expect string on 220 */
393 server_expect = optarg;
394 break;
395 case 'C': /* commands */
396 if (ncommands >= command_size) {
397 commands = realloc (commands, command_size+8);
398 if (commands == NULL)
399 die (STATE_UNKNOWN,
400 _("Could not realloc() units [%d]\n"), ncommands);
401 }
402 commands[ncommands] = optarg;
403 ncommands++;
404 break;
405 case 'R': /* server responses */
406 if (nresponses >= response_size) {
407 responses = realloc (responses, response_size+8);
408 if (responses == NULL)
409 die (STATE_UNKNOWN,
410 _("Could not realloc() units [%d]\n"), nresponses);
411 }
412 responses[nresponses] = optarg;
413 nresponses++;
414 break;
415 case 'c': /* critical time threshold */
416 if (is_intnonneg (optarg)) {
417 critical_time = atoi (optarg);
418 check_critical_time = TRUE;
419 }
420 else {
421 usage4 (_("Critical time must be a positive integer"));
422 }
423 break;
424 case 'w': /* warning time threshold */
425 if (is_intnonneg (optarg)) {
426 warning_time = atoi (optarg);
427 check_warning_time = TRUE;
428 }
429 else {
430 usage4 (_("Warning time must be a positive integer"));
431 }
432 break;
433 case 'v': /* verbose */
434 verbose++;
435 break;
436 case 't': /* timeout */
437 if (is_intnonneg (optarg)) {
438 socket_timeout = atoi (optarg);
439 }
440 else {
441 usage4 (_("Timeout interval must be a positive integer"));
442 }
443 break;
444 case 'S':
445 /* starttls */
446 use_ssl = TRUE;
447 break;
448 case 'D':
449 /* Check SSL cert validity */
450 #ifdef HAVE_SSL
451 if (!is_intnonneg (optarg))
452 usage2 ("Invalid certificate expiration period",optarg);
453 days_till_exp = atoi (optarg);
454 check_cert = TRUE;
455 #else
456 usage (_("SSL support not available - install OpenSSL and recompile"));
457 #endif
458 break;
459 case '4':
460 address_family = AF_INET;
461 break;
462 case '6':
463 #ifdef USE_IPV6
464 address_family = AF_INET6;
465 #else
466 usage4 (_("IPv6 support not available"));
467 #endif
468 break;
469 case 'V': /* version */
470 print_revision (progname, revision);
471 exit (STATE_OK);
472 case 'h': /* help */
473 print_help ();
474 exit (STATE_OK);
475 case '?': /* help */
476 usage2 (_("Unknown argument"), optarg);
477 }
478 }
480 c = optind;
481 if (server_address == NULL) {
482 if (argv[c]) {
483 if (is_host (argv[c]))
484 server_address = argv[c];
485 else
486 usage2 (_("Invalid hostname/address"), argv[c]);
487 }
488 else {
489 asprintf (&server_address, "127.0.0.1");
490 }
491 }
493 if (server_expect == NULL)
494 server_expect = strdup (SMTP_EXPECT);
496 if (mail_command == NULL)
497 mail_command = strdup("MAIL ");
499 if (from_arg==NULL)
500 from_arg = strdup(" ");
502 return validate_arguments ();
503 }
507 int
508 validate_arguments (void)
509 {
510 return OK;
511 }
515 void
516 print_help (void)
517 {
518 char *myport;
519 asprintf (&myport, "%d", SMTP_PORT);
521 print_revision (progname, revision);
523 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
524 printf (COPYRIGHT, copyright, email);
526 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
528 print_usage ();
530 printf (_(UT_HELP_VRSN));
532 printf (_(UT_HOST_PORT), 'p', myport);
534 printf (_(UT_IPv46));
536 printf (_("\
537 -e, --expect=STRING\n\
538 String to expect in first line of server response (default: '%s')\n\
539 -n, nocommand\n\
540 Suppress SMTP command\n\
541 -C, --command=STRING\n\
542 SMTP command (may be used repeatedly)\n\
543 -R, --command=STRING\n\
544 Expected response to command (may be used repeatedly)\n\
545 -f, --from=STRING\n\
546 FROM-address to include in MAIL command, required by Exchange 2000\n"),
547 SMTP_EXPECT);
548 #ifdef HAVE_SSL
549 printf (_("\
550 -D, --certificate=INTEGER\n\
551 Minimum number of days a certificate has to be valid.\n\
552 -S, --starttls\n\
553 Use STARTTLS for the connection.\n"));
554 #endif
556 printf (_(UT_WARN_CRIT));
558 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
560 printf (_(UT_VERBOSE));
562 printf(_("\n\
563 Successul connects return STATE_OK, refusals and timeouts return\n\
564 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
565 connects, but incorrect reponse messages from the host result in\n\
566 STATE_WARNING return values.\n"));
568 printf (_(UT_SUPPORT));
569 }
573 void
574 print_usage (void)
575 {
576 printf ("\
577 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
578 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
579 }
581 #ifdef HAVE_SSL
582 int
583 connect_STARTTLS (void)
584 {
585 SSL_METHOD *meth;
587 /* Initialize SSL context */
588 SSLeay_add_ssl_algorithms ();
589 meth = SSLv2_client_method ();
590 SSL_load_error_strings ();
591 if ((ctx = SSL_CTX_new (meth)) == NULL)
592 {
593 printf(_("CRITICAL - Cannot create SSL context.\n"));
594 return STATE_CRITICAL;
595 }
596 /* do the SSL handshake */
597 if ((ssl = SSL_new (ctx)) != NULL)
598 {
599 SSL_set_fd (ssl, sd);
600 /* original version checked for -1
601 I look for success instead (1) */
602 if (SSL_connect (ssl) == 1)
603 return OK;
604 ERR_print_errors_fp (stderr);
605 }
606 else
607 {
608 printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
609 }
610 /* this causes a seg faul
611 not sure why, being sloppy
612 and commenting it out */
613 // SSL_free (ssl);
614 SSL_CTX_free(ctx);
615 my_close();
617 return STATE_CRITICAL;
618 }
620 int
621 check_certificate (X509 ** certificate)
622 {
623 ASN1_STRING *tm;
624 int offset;
625 struct tm stamp;
626 int days_left;
628 /* Retrieve timestamp of certificate */
629 tm = X509_get_notAfter (*certificate);
631 /* Generate tm structure to process timestamp */
632 if (tm->type == V_ASN1_UTCTIME) {
633 if (tm->length < 10) {
634 printf (_("CRITICAL - Wrong time format in certificate.\n"));
635 return STATE_CRITICAL;
636 }
637 else {
638 stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
639 if (stamp.tm_year < 50)
640 stamp.tm_year += 100;
641 offset = 0;
642 }
643 }
644 else {
645 if (tm->length < 12) {
646 printf (_("CRITICAL - Wrong time format in certificate.\n"));
647 return STATE_CRITICAL;
648 }
649 else {
650 stamp.tm_year =
651 (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
652 (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
653 stamp.tm_year -= 1900;
654 offset = 2;
655 }
656 }
657 stamp.tm_mon =
658 (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
659 stamp.tm_mday =
660 (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
661 stamp.tm_hour =
662 (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
663 stamp.tm_min =
664 (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
665 stamp.tm_sec = 0;
666 stamp.tm_isdst = -1;
668 days_left = (mktime (&stamp) - time (NULL)) / 86400;
669 snprintf
670 (timestamp, 16, "%02d/%02d/%04d %02d:%02d",
671 stamp.tm_mon + 1,
672 stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
674 if (days_left > 0 && days_left <= days_till_exp) {
675 printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
676 return STATE_WARNING;
677 }
678 if (days_left < 0) {
679 printf ("Certificate expired on %s.\n", timestamp);
680 return STATE_CRITICAL;
681 }
683 if (days_left == 0) {
684 printf ("Certificate expires today (%s).\n", timestamp);
685 return STATE_WARNING;
686 }
688 printf ("Certificate will expire on %s.\n", timestamp);
690 return STATE_OK;
691 }
692 #endif
694 int
695 myrecv (void)
696 {
697 int i;
699 #ifdef HAVE_SSL
700 if (use_ssl) {
701 i = SSL_read (ssl, buffer, MAXBUF - 1);
702 }
703 else {
704 #endif
705 i = read (sd, buffer, MAXBUF - 1);
706 #ifdef HAVE_SSL
707 }
708 #endif
709 return i;
710 }
712 int
713 my_close (void)
714 {
715 #ifdef HAVE_SSL
716 if (use_ssl == TRUE) {
717 SSL_shutdown (ssl);
718 SSL_free (ssl);
719 SSL_CTX_free (ctx);
720 return 0;
721 }
722 else {
723 #endif
724 return close(sd);
725 #ifdef HAVE_SSL
726 }
727 #endif
728 }