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 }
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 errcode = regcomp (&preg, responses[n], cflags);
258 if (errcode != 0) {
259 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
260 printf (_("Could Not Compile Regular Expression"));
261 return ERROR;
262 }
263 excode = regexec (&preg, buffer, 10, pmatch, eflags);
264 if (excode == 0) {
265 result = STATE_OK;
266 }
267 else if (excode == REG_NOMATCH) {
268 result = STATE_WARNING;
269 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
270 }
271 else {
272 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
273 printf (_("Execute Error: %s\n"), errbuf);
274 result = STATE_UNKNOWN;
275 }
276 #else
277 if (strstr(buffer, responses[n])!=buffer) {
278 result = STATE_WARNING;
279 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
280 }
281 #endif
282 }
283 n++;
284 }
286 /* tell the server we're done */
287 #ifdef HAVE_SSL
288 if (use_ssl)
289 SSL_write(ssl,SMTP_QUIT, strlen (SMTP_QUIT));
290 else
291 #endif
292 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
294 /* finally close the connection */
295 close (sd);
296 }
298 /* reset the alarm */
299 alarm (0);
301 microsec = deltime (tv);
302 elapsed_time = (double)microsec / 1.0e6;
304 if (result == STATE_OK) {
305 if (check_critical_time && elapsed_time > (double) critical_time)
306 result = STATE_CRITICAL;
307 else if (check_warning_time && elapsed_time > (double) warning_time)
308 result = STATE_WARNING;
309 }
311 printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
312 state_text (result), elapsed_time,
313 verbose?", ":"", verbose?buffer:"",
314 fperfdata ("time", elapsed_time, "s",
315 (int)check_warning_time, warning_time,
316 (int)check_critical_time, critical_time,
317 TRUE, 0, FALSE, 0));
319 return result;
320 }
324 /* process command-line arguments */
325 int
326 process_arguments (int argc, char **argv)
327 {
328 int c;
330 int option = 0;
331 static struct option longopts[] = {
332 {"hostname", required_argument, 0, 'H'},
333 {"expect", required_argument, 0, 'e'},
334 {"critical", required_argument, 0, 'c'},
335 {"warning", required_argument, 0, 'w'},
336 {"timeout", required_argument, 0, 't'},
337 {"port", required_argument, 0, 'p'},
338 {"from", required_argument, 0, 'f'},
339 {"command", required_argument, 0, 'C'},
340 {"response", required_argument, 0, 'R'},
341 {"nocommand", required_argument, 0, 'n'},
342 {"verbose", no_argument, 0, 'v'},
343 {"version", no_argument, 0, 'V'},
344 {"use-ipv4", no_argument, 0, '4'},
345 {"use-ipv6", no_argument, 0, '6'},
346 {"help", no_argument, 0, 'h'},
347 {"starttls",no_argument,0,'S'},
348 {"certificate",required_argument,0,'D'},
349 {0, 0, 0, 0}
350 };
352 if (argc < 2)
353 return ERROR;
355 for (c = 1; c < argc; c++) {
356 if (strcmp ("-to", argv[c]) == 0)
357 strcpy (argv[c], "-t");
358 else if (strcmp ("-wt", argv[c]) == 0)
359 strcpy (argv[c], "-w");
360 else if (strcmp ("-ct", argv[c]) == 0)
361 strcpy (argv[c], "-c");
362 }
364 while (1) {
365 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:",
366 longopts, &option);
368 if (c == -1 || c == EOF)
369 break;
371 switch (c) {
372 case 'H': /* hostname */
373 if (is_host (optarg)) {
374 server_address = optarg;
375 }
376 else {
377 usage2 (_("Invalid hostname/address"), optarg);
378 }
379 break;
380 case 'p': /* port */
381 if (is_intpos (optarg))
382 server_port = atoi (optarg);
383 else
384 usage4 (_("Port must be a positive integer"));
385 break;
386 case 'f': /* from argument */
387 from_arg = optarg;
388 smtp_use_dummycmd = 1;
389 break;
390 case 'e': /* server expect string on 220 */
391 server_expect = optarg;
392 break;
393 case 'C': /* commands */
394 if (ncommands >= command_size) {
395 commands = realloc (commands, command_size+8);
396 if (commands == NULL)
397 die (STATE_UNKNOWN,
398 _("Could not realloc() units [%d]\n"), ncommands);
399 }
400 commands[ncommands] = optarg;
401 ncommands++;
402 break;
403 case 'R': /* server responses */
404 if (nresponses >= response_size) {
405 responses = realloc (responses, response_size+8);
406 if (responses == NULL)
407 die (STATE_UNKNOWN,
408 _("Could not realloc() units [%d]\n"), nresponses);
409 }
410 responses[nresponses] = optarg;
411 nresponses++;
412 break;
413 case 'c': /* critical time threshold */
414 if (is_intnonneg (optarg)) {
415 critical_time = atoi (optarg);
416 check_critical_time = TRUE;
417 }
418 else {
419 usage4 (_("Critical time must be a positive integer"));
420 }
421 break;
422 case 'w': /* warning time threshold */
423 if (is_intnonneg (optarg)) {
424 warning_time = atoi (optarg);
425 check_warning_time = TRUE;
426 }
427 else {
428 usage4 (_("Warning time must be a positive integer"));
429 }
430 break;
431 case 'v': /* verbose */
432 verbose++;
433 break;
434 case 't': /* timeout */
435 if (is_intnonneg (optarg)) {
436 socket_timeout = atoi (optarg);
437 }
438 else {
439 usage4 (_("Timeout interval must be a positive integer"));
440 }
441 break;
442 case 'S':
443 /* starttls */
444 use_ssl = TRUE;
445 break;
446 case 'D':
447 /* Check SSL cert validity */
448 #ifdef HAVE_SSL
449 if (!is_intnonneg (optarg))
450 usage2 ("Invalid certificate expiration period",optarg);
451 days_till_exp = atoi (optarg);
452 check_cert = TRUE;
453 #else
454 usage (_("SSL support not available - install OpenSSL and recompile"));
455 #endif
456 break;
457 case '4':
458 address_family = AF_INET;
459 break;
460 case '6':
461 #ifdef USE_IPV6
462 address_family = AF_INET6;
463 #else
464 usage4 (_("IPv6 support not available"));
465 #endif
466 break;
467 case 'V': /* version */
468 print_revision (progname, revision);
469 exit (STATE_OK);
470 case 'h': /* help */
471 print_help ();
472 exit (STATE_OK);
473 case '?': /* help */
474 usage2 (_("Unknown argument"), optarg);
475 }
476 }
478 c = optind;
479 if (server_address == NULL) {
480 if (argv[c]) {
481 if (is_host (argv[c]))
482 server_address = argv[c];
483 else
484 usage2 (_("Invalid hostname/address"), argv[c]);
485 }
486 else {
487 asprintf (&server_address, "127.0.0.1");
488 }
489 }
491 if (server_expect == NULL)
492 server_expect = strdup (SMTP_EXPECT);
494 if (mail_command == NULL)
495 mail_command = strdup("MAIL ");
497 if (from_arg==NULL)
498 from_arg = strdup(" ");
500 return validate_arguments ();
501 }
505 int
506 validate_arguments (void)
507 {
508 return OK;
509 }
513 void
514 print_help (void)
515 {
516 char *myport;
517 asprintf (&myport, "%d", SMTP_PORT);
519 print_revision (progname, revision);
521 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
522 printf (COPYRIGHT, copyright, email);
524 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
526 print_usage ();
528 printf (_(UT_HELP_VRSN));
530 printf (_(UT_HOST_PORT), 'p', myport);
532 printf (_(UT_IPv46));
534 printf (_("\
535 -e, --expect=STRING\n\
536 String to expect in first line of server response (default: '%s')\n\
537 -n, nocommand\n\
538 Suppress SMTP command\n\
539 -C, --command=STRING\n\
540 SMTP command (may be used repeatedly)\n\
541 -R, --command=STRING\n\
542 Expected response to command (may be used repeatedly)\n\
543 -f, --from=STRING\n\
544 FROM-address to include in MAIL command, required by Exchange 2000\n"),
545 SMTP_EXPECT);
546 #ifdef HAVE_SSL
547 printf (_("\
548 -D, --certificate=INTEGER\n\
549 Minimum number of days a certificate has to be valid.\n\
550 -S, --starttls\n\
551 Use STARTTLS for the connection.\n"));
552 #endif
554 printf (_(UT_WARN_CRIT));
556 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
558 printf (_(UT_VERBOSE));
560 printf(_("\n\
561 Successul connects return STATE_OK, refusals and timeouts return\n\
562 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
563 connects, but incorrect reponse messages from the host result in\n\
564 STATE_WARNING return values.\n"));
566 printf (_(UT_SUPPORT));
567 }
571 void
572 print_usage (void)
573 {
574 printf ("\
575 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
576 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
577 }
579 #ifdef HAVE_SSL
580 int
581 connect_STARTTLS (void)
582 {
583 SSL_METHOD *meth;
585 /* Initialize SSL context */
586 SSLeay_add_ssl_algorithms ();
587 meth = SSLv2_client_method ();
588 SSL_load_error_strings ();
589 if ((ctx = SSL_CTX_new (meth)) == NULL)
590 {
591 printf(_("CRITICAL - Cannot create SSL context.\n"));
592 return STATE_CRITICAL;
593 }
594 /* do the SSL handshake */
595 if ((ssl = SSL_new (ctx)) != NULL)
596 {
597 SSL_set_fd (ssl, sd);
598 /* original version checked for -1
599 I look for success instead (1) */
600 if (SSL_connect (ssl) == 1)
601 return OK;
602 ERR_print_errors_fp (stderr);
603 }
604 else
605 {
606 printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
607 }
608 /* this causes a seg faul
609 not sure why, being sloppy
610 and commenting it out */
611 /* SSL_free (ssl); */
612 SSL_CTX_free(ctx);
613 my_close();
615 return STATE_CRITICAL;
616 }
618 int
619 check_certificate (X509 ** certificate)
620 {
621 ASN1_STRING *tm;
622 int offset;
623 struct tm stamp;
624 int days_left;
626 /* Retrieve timestamp of certificate */
627 tm = X509_get_notAfter (*certificate);
629 /* Generate tm structure to process timestamp */
630 if (tm->type == V_ASN1_UTCTIME) {
631 if (tm->length < 10) {
632 printf (_("CRITICAL - Wrong time format in certificate.\n"));
633 return STATE_CRITICAL;
634 }
635 else {
636 stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
637 if (stamp.tm_year < 50)
638 stamp.tm_year += 100;
639 offset = 0;
640 }
641 }
642 else {
643 if (tm->length < 12) {
644 printf (_("CRITICAL - Wrong time format in certificate.\n"));
645 return STATE_CRITICAL;
646 }
647 else {
648 stamp.tm_year =
649 (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
650 (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
651 stamp.tm_year -= 1900;
652 offset = 2;
653 }
654 }
655 stamp.tm_mon =
656 (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
657 stamp.tm_mday =
658 (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
659 stamp.tm_hour =
660 (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
661 stamp.tm_min =
662 (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
663 stamp.tm_sec = 0;
664 stamp.tm_isdst = -1;
666 days_left = (mktime (&stamp) - time (NULL)) / 86400;
667 snprintf
668 (timestamp, sizeof(timestamp), "%02d/%02d/%04d %02d:%02d",
669 stamp.tm_mon + 1,
670 stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
672 if (days_left > 0 && days_left <= days_till_exp) {
673 printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
674 return STATE_WARNING;
675 }
676 if (days_left < 0) {
677 printf ("Certificate expired on %s.\n", timestamp);
678 return STATE_CRITICAL;
679 }
681 if (days_left == 0) {
682 printf ("Certificate expires today (%s).\n", timestamp);
683 return STATE_WARNING;
684 }
686 printf ("Certificate will expire on %s.\n", timestamp);
688 return STATE_OK;
689 }
690 #endif
692 int
693 myrecv (void)
694 {
695 int i;
697 #ifdef HAVE_SSL
698 if (use_ssl) {
699 i = SSL_read (ssl, buffer, MAXBUF - 1);
700 }
701 else {
702 #endif
703 i = read (sd, buffer, MAXBUF - 1);
704 #ifdef HAVE_SSL
705 }
706 #endif
707 return i;
708 }
710 int
711 my_close (void)
712 {
713 #ifdef HAVE_SSL
714 if (use_ssl == TRUE) {
715 SSL_shutdown (ssl);
716 SSL_free (ssl);
717 SSL_CTX_free (ctx);
718 return 0;
719 }
720 else {
721 #endif
722 return close(sd);
723 #ifdef HAVE_SSL
724 }
725 #endif
726 }