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 terminate (STATE_UNKNOWN,
457 "SSL support not available. Install OpenSSL and recompile.");
458 #endif
459 break;
460 case '4':
461 address_family = AF_INET;
462 break;
463 case '6':
464 #ifdef USE_IPV6
465 address_family = AF_INET6;
466 #else
467 usage4 (_("IPv6 support not available"));
468 #endif
469 break;
470 case 'V': /* version */
471 print_revision (progname, revision);
472 exit (STATE_OK);
473 case 'h': /* help */
474 print_help ();
475 exit (STATE_OK);
476 case '?': /* help */
477 usage2 (_("Unknown argument"), optarg);
478 }
479 }
481 c = optind;
482 if (server_address == NULL) {
483 if (argv[c]) {
484 if (is_host (argv[c]))
485 server_address = argv[c];
486 else
487 usage2 (_("Invalid hostname/address"), argv[c]);
488 }
489 else {
490 asprintf (&server_address, "127.0.0.1");
491 }
492 }
494 if (server_expect == NULL)
495 server_expect = strdup (SMTP_EXPECT);
497 if (mail_command == NULL)
498 mail_command = strdup("MAIL ");
500 if (from_arg==NULL)
501 from_arg = strdup(" ");
503 return validate_arguments ();
504 }
508 int
509 validate_arguments (void)
510 {
511 return OK;
512 }
516 void
517 print_help (void)
518 {
519 char *myport;
520 asprintf (&myport, "%d", SMTP_PORT);
522 print_revision (progname, revision);
524 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
525 printf (COPYRIGHT, copyright, email);
527 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
529 print_usage ();
531 printf (_(UT_HELP_VRSN));
533 printf (_(UT_HOST_PORT), 'p', myport);
535 printf (_(UT_IPv46));
537 printf (_("\
538 -e, --expect=STRING\n\
539 String to expect in first line of server response (default: '%s')\n\
540 -n, nocommand\n\
541 Suppress SMTP command\n\
542 -C, --command=STRING\n\
543 SMTP command (may be used repeatedly)\n\
544 -R, --command=STRING\n\
545 Expected response to command (may be used repeatedly)\n\
546 -f, --from=STRING\n\
547 FROM-address to include in MAIL command, required by Exchange 2000\n"),
548 SMTP_EXPECT);
549 #ifdef HAVE_SSL
550 printf (_("\
551 -D, --certificate=INTEGER\n\
552 Minimum number of days a certificate has to be valid.\n\
553 -S, --starttls\n\
554 Use STARTTLS for the connection.\n"));
555 #endif
557 printf (_(UT_WARN_CRIT));
559 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
561 printf (_(UT_VERBOSE));
563 printf(_("\n\
564 Successul connects return STATE_OK, refusals and timeouts return\n\
565 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
566 connects, but incorrect reponse messages from the host result in\n\
567 STATE_WARNING return values.\n"));
569 printf (_(UT_SUPPORT));
570 }
574 void
575 print_usage (void)
576 {
577 printf ("\
578 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
579 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
580 }
582 #ifdef HAVE_SSL
583 int
584 connect_STARTTLS (void)
585 {
586 SSL_METHOD *meth;
588 /* Initialize SSL context */
589 SSLeay_add_ssl_algorithms ();
590 meth = SSLv2_client_method ();
591 SSL_load_error_strings ();
592 if ((ctx = SSL_CTX_new (meth)) == NULL)
593 {
594 printf(_("CRITICAL - Cannot create SSL context.\n"));
595 return STATE_CRITICAL;
596 }
597 /* do the SSL handshake */
598 if ((ssl = SSL_new (ctx)) != NULL)
599 {
600 SSL_set_fd (ssl, sd);
601 /* original version checked for -1
602 I look for success instead (1) */
603 if (SSL_connect (ssl) == 1)
604 return OK;
605 ERR_print_errors_fp (stderr);
606 }
607 else
608 {
609 printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
610 }
611 /* this causes a seg faul
612 not sure why, being sloppy
613 and commenting it out */
614 // SSL_free (ssl);
615 SSL_CTX_free(ctx);
616 my_close();
618 return STATE_CRITICAL;
619 }
621 int
622 check_certificate (X509 ** certificate)
623 {
624 ASN1_STRING *tm;
625 int offset;
626 struct tm stamp;
627 int days_left;
629 /* Retrieve timestamp of certificate */
630 tm = X509_get_notAfter (*certificate);
632 /* Generate tm structure to process timestamp */
633 if (tm->type == V_ASN1_UTCTIME) {
634 if (tm->length < 10) {
635 printf (_("CRITICAL - Wrong time format in certificate.\n"));
636 return STATE_CRITICAL;
637 }
638 else {
639 stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
640 if (stamp.tm_year < 50)
641 stamp.tm_year += 100;
642 offset = 0;
643 }
644 }
645 else {
646 if (tm->length < 12) {
647 printf (_("CRITICAL - Wrong time format in certificate.\n"));
648 return STATE_CRITICAL;
649 }
650 else {
651 stamp.tm_year =
652 (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
653 (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
654 stamp.tm_year -= 1900;
655 offset = 2;
656 }
657 }
658 stamp.tm_mon =
659 (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
660 stamp.tm_mday =
661 (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
662 stamp.tm_hour =
663 (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
664 stamp.tm_min =
665 (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
666 stamp.tm_sec = 0;
667 stamp.tm_isdst = -1;
669 days_left = (mktime (&stamp) - time (NULL)) / 86400;
670 snprintf
671 (timestamp, 16, "%02d/%02d/%04d %02d:%02d",
672 stamp.tm_mon + 1,
673 stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
675 if (days_left > 0 && days_left <= days_till_exp) {
676 printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
677 return STATE_WARNING;
678 }
679 if (days_left < 0) {
680 printf ("Certificate expired on %s.\n", timestamp);
681 return STATE_CRITICAL;
682 }
684 if (days_left == 0) {
685 printf ("Certificate expires today (%s).\n", timestamp);
686 return STATE_WARNING;
687 }
689 printf ("Certificate will expire on %s.\n", timestamp);
691 return STATE_OK;
692 }
693 #endif
695 int
696 myrecv (void)
697 {
698 int i;
700 #ifdef HAVE_SSL
701 if (use_ssl) {
702 i = SSL_read (ssl, buffer, MAXBUF - 1);
703 }
704 else {
705 #endif
706 i = read (sd, buffer, MAXBUF - 1);
707 #ifdef HAVE_SSL
708 }
709 #endif
710 return i;
711 }
713 int
714 my_close (void)
715 {
716 #ifdef HAVE_SSL
717 if (use_ssl == TRUE) {
718 SSL_shutdown (ssl);
719 SSL_free (ssl);
720 SSL_CTX_free (ctx);
721 return 0;
722 }
723 else {
724 #endif
725 return close(sd);
726 #ifdef HAVE_SSL
727 }
728 #endif
729 }