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
31 int check_cert = FALSE;
32 int days_till_exp;
33 # define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
34 # define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
35 #else /* ifndef HAVE_SSL */
36 # define my_recv(buf, len) read(sd, buf, len)
37 # define my_send(buf, len) send(sd, buf, len, 0)
38 #endif
40 enum {
41 SMTP_PORT = 25
42 };
43 #define SMTP_EXPECT "220"
44 #define SMTP_HELO "HELO "
45 #define SMTP_EHLO "EHLO "
46 #define SMTP_QUIT "QUIT\r\n"
47 #define SMTP_STARTTLS "STARTTLS\r\n"
48 #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
50 #ifndef HOST_MAX_BYTES
51 #define HOST_MAX_BYTES 255
52 #endif
54 #define EHLO_SUPPORTS_STARTTLS 1
56 int process_arguments (int, char **);
57 int validate_arguments (void);
58 void print_help (void);
59 void print_usage (void);
60 int my_close(void);
62 #include "regex.h"
63 char regex_expect[MAX_INPUT_BUFFER] = "";
64 regex_t preg;
65 regmatch_t pmatch[10];
66 char timestamp[20] = "";
67 char errbuf[MAX_INPUT_BUFFER];
68 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
69 int eflags = 0;
70 int errcode, excode;
72 int server_port = SMTP_PORT;
73 char *server_address = NULL;
74 char *server_expect = NULL;
75 int smtp_use_dummycmd = 0;
76 char *mail_command = NULL;
77 char *from_arg = NULL;
78 int ncommands=0;
79 int command_size=0;
80 int nresponses=0;
81 int response_size=0;
82 char **commands = NULL;
83 char **responses = NULL;
84 char *authtype = NULL;
85 char *authuser = NULL;
86 char *authpass = NULL;
87 int warning_time = 0;
88 int check_warning_time = FALSE;
89 int critical_time = 0;
90 int check_critical_time = FALSE;
91 int verbose = 0;
92 int use_ssl = FALSE;
93 short use_ehlo = FALSE;
94 short ssl_established = 0;
95 char *localhostname = NULL;
96 int sd;
97 char buffer[MAX_INPUT_BUFFER];
98 enum {
99 TCP_PROTOCOL = 1,
100 UDP_PROTOCOL = 2,
101 MAXBUF = 1024
102 };
104 /* written by lauri alanko */
105 static char *
106 base64 (const char *bin, size_t len)
107 {
109 char *buf = (char *) malloc ((len + 2) / 3 * 4 + 1);
110 size_t i = 0, j = 0;
112 char BASE64_END = '=';
113 char base64_table[64];
114 strncpy (base64_table, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 64);
116 while (j < len - 2) {
117 buf[i++] = base64_table[bin[j] >> 2];
118 buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
119 buf[i++] = base64_table[((bin[j + 1] & 15) << 2) | (bin[j + 2] >> 6)];
120 buf[i++] = base64_table[bin[j + 2] & 63];
121 j += 3;
122 }
124 switch (len - j) {
125 case 1:
126 buf[i++] = base64_table[bin[j] >> 2];
127 buf[i++] = base64_table[(bin[j] & 3) << 4];
128 buf[i++] = BASE64_END;
129 buf[i++] = BASE64_END;
130 break;
131 case 2:
132 buf[i++] = base64_table[bin[j] >> 2];
133 buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
134 buf[i++] = base64_table[(bin[j + 1] & 15) << 2];
135 buf[i++] = BASE64_END;
136 break;
137 case 0:
138 break;
139 }
141 buf[i] = '\0';
142 return buf;
143 }
145 int
146 main (int argc, char **argv)
147 {
148 short supports_tls=FALSE;
149 int n = 0;
150 double elapsed_time;
151 long microsec;
152 int result = STATE_UNKNOWN;
153 char *cmd_str = NULL;
154 char *helocmd = NULL;
155 char *error_msg = NULL;
156 struct timeval tv;
157 struct hostent *hp;
159 setlocale (LC_ALL, "");
160 bindtextdomain (PACKAGE, LOCALEDIR);
161 textdomain (PACKAGE);
163 if (process_arguments (argc, argv) == ERROR)
164 usage4 (_("Could not parse arguments"));
166 /* initialize the HELO command with the localhostname */
167 if(! localhostname){
168 localhostname = malloc (HOST_MAX_BYTES);
169 if(!localhostname){
170 printf(_("malloc() failed!\n"));
171 return STATE_CRITICAL;
172 }
173 if(gethostname(localhostname, HOST_MAX_BYTES)){
174 printf(_("gethostname() failed!\n"));
175 return STATE_CRITICAL;
176 }
177 hp = gethostbyname(localhostname);
178 if(!hp) helocmd = localhostname;
179 else helocmd = hp->h_name;
180 } else {
181 helocmd = localhostname;
182 }
183 if(use_ehlo)
184 asprintf (&helocmd, "%s%s%s", SMTP_EHLO, helocmd, "\r\n");
185 else
186 asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
188 /* initialize the MAIL command with optional FROM command */
189 asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
191 if (verbose && smtp_use_dummycmd)
192 printf ("FROM CMD: %s", cmd_str);
194 /* initialize alarm signal handling */
195 (void) signal (SIGALRM, socket_timeout_alarm_handler);
197 /* set socket timeout */
198 (void) alarm (socket_timeout);
200 /* start timer */
201 gettimeofday (&tv, NULL);
203 /* try to connect to the host at the given port number */
204 result = my_tcp_connect (server_address, server_port, &sd);
206 if (result == STATE_OK) { /* we connected */
208 /* watch for the SMTP connection string and */
209 /* return a WARNING status if we couldn't read any data */
210 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
211 printf (_("recv() failed\n"));
212 result = STATE_WARNING;
213 }
214 else {
215 if (verbose)
216 printf ("%s", buffer);
217 /* strip the buffer of carriage returns */
218 strip (buffer);
219 /* make sure we find the response we are looking for */
220 if (!strstr (buffer, server_expect)) {
221 if (server_port == SMTP_PORT)
222 printf (_("Invalid SMTP response received from host\n"));
223 else
224 printf (_("Invalid SMTP response received from host on port %d\n"),
225 server_port);
226 result = STATE_WARNING;
227 }
228 }
230 /* send the HELO/EHLO command */
231 send(sd, helocmd, strlen(helocmd), 0);
233 /* allow for response to helo command to reach us */
234 if(read (sd, buffer, MAXBUF - 1) < 0){
235 printf (_("recv() failed\n"));
236 return STATE_WARNING;
237 } else if(use_ehlo){
238 buffer[MAXBUF-1]='\0';
239 if(strstr(buffer, "250 STARTTLS") != NULL ||
240 strstr(buffer, "250-STARTTLS") != NULL){
241 supports_tls=TRUE;
242 }
243 }
245 if(use_ssl && ! supports_tls){
246 printf(_("WARNING - TLS not supported by server\n"));
247 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
248 return STATE_WARNING;
249 }
251 #ifdef HAVE_SSL
252 if(use_ssl) {
253 /* send the STARTTLS command */
254 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
256 recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); /* wait for it */
257 if (!strstr (buffer, server_expect)) {
258 printf (_("Server does not support STARTTLS\n"));
259 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
260 return STATE_UNKNOWN;
261 }
262 result = np_net_ssl_init(sd);
263 if(result != STATE_OK) {
264 printf (_("CRITICAL - Cannot create SSL context.\n"));
265 np_net_ssl_cleanup();
266 close(sd);
267 return STATE_CRITICAL;
268 } else {
269 ssl_established = 1;
270 }
271 # ifdef USE_OPENSSL
272 if ( check_cert ) {
273 result = np_net_ssl_check_cert(days_till_exp);
274 if(result != STATE_OK){
275 printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
276 }
277 my_close();
278 return result;
279 }
280 # endif /* USE_OPENSSL */
281 }
282 #endif
284 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
285 * to do something useful. This can be prevented by giving a command
286 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
287 *
288 * According to rfc821 you can include a null reversepath in the from command
289 * - but a log message is generated on the smtp server.
290 *
291 * You can disable sending mail_command with '--nocommand'
292 * Use the -f option to provide a FROM address
293 */
294 if (smtp_use_dummycmd) {
295 my_send(cmd_str, strlen(cmd_str));
296 my_recv(buffer, MAX_INPUT_BUFFER-1);
297 if (verbose)
298 printf("%s", buffer);
299 }
301 while (n < ncommands) {
302 asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
303 my_send(cmd_str, strlen(cmd_str));
304 my_recv(buffer, MAX_INPUT_BUFFER-1);
305 if (verbose)
306 printf("%s", buffer);
307 strip (buffer);
308 if (n < nresponses) {
309 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
310 errcode = regcomp (&preg, responses[n], cflags);
311 if (errcode != 0) {
312 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
313 printf (_("Could Not Compile Regular Expression"));
314 return ERROR;
315 }
316 excode = regexec (&preg, buffer, 10, pmatch, eflags);
317 if (excode == 0) {
318 result = STATE_OK;
319 }
320 else if (excode == REG_NOMATCH) {
321 result = STATE_WARNING;
322 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
323 }
324 else {
325 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
326 printf (_("Execute Error: %s\n"), errbuf);
327 result = STATE_UNKNOWN;
328 }
329 }
330 n++;
331 }
333 if (authtype != NULL) {
334 if (strcmp (authtype, "LOGIN") == 0) {
335 char *abuf;
336 int ret;
337 do {
338 if (authuser == NULL) {
339 result = STATE_CRITICAL;
340 error_msg = _("no authuser specified, ");
341 break;
342 }
343 if (authpass == NULL) {
344 result = STATE_CRITICAL;
345 error_msg = _("no authpass specified, ");
346 break;
347 }
349 /* send AUTH LOGIN */
350 my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
351 if (verbose)
352 printf (_("sent %s\n"), "AUTH LOGIN");
354 if((ret = my_recv(buffer, MAXBUF - 1)) < 0){
355 error_msg = _("recv() failed after AUTH LOGIN, \n");
356 result = STATE_WARNING;
357 break;
358 }
359 buffer[ret] = 0;
360 if (verbose)
361 printf (_("received %s\n"), buffer);
363 if (strncmp (buffer, "334", 3) != 0) {
364 result = STATE_CRITICAL;
365 error_msg = _("invalid response received after AUTH LOGIN, ");
366 break;
367 }
369 /* encode authuser with base64 */
370 abuf = base64 (authuser, strlen(authuser));
371 strcat (abuf, "\r\n");
372 my_send(abuf, strlen(abuf));
373 if (verbose)
374 printf (_("sent %s\n"), abuf);
376 if ((ret = my_recv(buffer, MAX_INPUT_BUFFER-1)) == -1) {
377 result = STATE_CRITICAL;
378 error_msg = _("recv() failed after sending authuser, ");
379 break;
380 }
381 buffer[ret] = 0;
382 if (verbose) {
383 printf (_("received %s\n"), buffer);
384 }
385 if (strncmp (buffer, "334", 3) != 0) {
386 result = STATE_CRITICAL;
387 error_msg = _("invalid response received after authuser, ");
388 break;
389 }
390 /* encode authpass with base64 */
391 abuf = base64 (authpass, strlen(authpass));
392 strcat (abuf, "\r\n");
393 my_send(abuf, strlen(abuf));
394 if (verbose) {
395 printf (_("sent %s\n"), abuf);
396 }
397 if ((ret = my_recv(buffer, MAX_INPUT_BUFFER-1)) == -1) {
398 result = STATE_CRITICAL;
399 error_msg = _("recv() failed after sending authpass, ");
400 break;
401 }
402 buffer[ret] = 0;
403 if (verbose) {
404 printf (_("received %s\n"), buffer);
405 }
406 if (strncmp (buffer, "235", 3) != 0) {
407 result = STATE_CRITICAL;
408 error_msg = _("invalid response received after authpass, ");
409 break;
410 }
411 break;
412 } while (0);
413 } else {
414 result = STATE_CRITICAL;
415 error_msg = _("only authtype LOGIN is supported, ");
416 }
417 }
419 /* tell the server we're done */
420 my_send (SMTP_QUIT, strlen (SMTP_QUIT));
422 /* finally close the connection */
423 close (sd);
424 }
426 /* reset the alarm */
427 alarm (0);
429 microsec = deltime (tv);
430 elapsed_time = (double)microsec / 1.0e6;
432 if (result == STATE_OK) {
433 if (check_critical_time && elapsed_time > (double) critical_time)
434 result = STATE_CRITICAL;
435 else if (check_warning_time && elapsed_time > (double) warning_time)
436 result = STATE_WARNING;
437 }
439 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
440 state_text (result),
441 (error_msg == NULL ? "" : error_msg),
442 elapsed_time,
443 verbose?", ":"", verbose?buffer:"",
444 fperfdata ("time", elapsed_time, "s",
445 (int)check_warning_time, warning_time,
446 (int)check_critical_time, critical_time,
447 TRUE, 0, FALSE, 0));
449 return result;
450 }
454 /* process command-line arguments */
455 int
456 process_arguments (int argc, char **argv)
457 {
458 int c;
460 int option = 0;
461 static struct option longopts[] = {
462 {"hostname", required_argument, 0, 'H'},
463 {"expect", required_argument, 0, 'e'},
464 {"critical", required_argument, 0, 'c'},
465 {"warning", required_argument, 0, 'w'},
466 {"timeout", required_argument, 0, 't'},
467 {"port", required_argument, 0, 'p'},
468 {"from", required_argument, 0, 'f'},
469 {"fqdn", required_argument, 0, 'F'},
470 {"authtype", required_argument, 0, 'A'},
471 {"authuser", required_argument, 0, 'U'},
472 {"authpass", required_argument, 0, 'P'},
473 {"command", required_argument, 0, 'C'},
474 {"response", required_argument, 0, 'R'},
475 {"nocommand", required_argument, 0, 'n'},
476 {"verbose", no_argument, 0, 'v'},
477 {"version", no_argument, 0, 'V'},
478 {"use-ipv4", no_argument, 0, '4'},
479 {"use-ipv6", no_argument, 0, '6'},
480 {"help", no_argument, 0, 'h'},
481 {"starttls",no_argument,0,'S'},
482 {"certificate",required_argument,0,'D'},
483 {0, 0, 0, 0}
484 };
486 if (argc < 2)
487 return ERROR;
489 for (c = 1; c < argc; c++) {
490 if (strcmp ("-to", argv[c]) == 0)
491 strcpy (argv[c], "-t");
492 else if (strcmp ("-wt", argv[c]) == 0)
493 strcpy (argv[c], "-w");
494 else if (strcmp ("-ct", argv[c]) == 0)
495 strcpy (argv[c], "-c");
496 }
498 while (1) {
499 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:",
500 longopts, &option);
502 if (c == -1 || c == EOF)
503 break;
505 switch (c) {
506 case 'H': /* hostname */
507 if (is_host (optarg)) {
508 server_address = optarg;
509 }
510 else {
511 usage2 (_("Invalid hostname/address"), optarg);
512 }
513 break;
514 case 'p': /* port */
515 if (is_intpos (optarg))
516 server_port = atoi (optarg);
517 else
518 usage4 (_("Port must be a positive integer"));
519 break;
520 case 'F':
521 /* localhostname */
522 localhostname = strdup(optarg);
523 break;
524 case 'f': /* from argument */
525 from_arg = optarg;
526 smtp_use_dummycmd = 1;
527 break;
528 case 'A':
529 authtype = optarg;
530 break;
531 case 'U':
532 authuser = optarg;
533 break;
534 case 'P':
535 authpass = optarg;
536 break;
537 case 'e': /* server expect string on 220 */
538 server_expect = optarg;
539 break;
540 case 'C': /* commands */
541 if (ncommands >= command_size) {
542 commands = realloc (commands, command_size+8);
543 if (commands == NULL)
544 die (STATE_UNKNOWN,
545 _("Could not realloc() units [%d]\n"), ncommands);
546 }
547 commands[ncommands] = optarg;
548 ncommands++;
549 break;
550 case 'R': /* server responses */
551 if (nresponses >= response_size) {
552 responses = realloc (responses, response_size+8);
553 if (responses == NULL)
554 die (STATE_UNKNOWN,
555 _("Could not realloc() units [%d]\n"), nresponses);
556 }
557 responses[nresponses] = optarg;
558 nresponses++;
559 break;
560 case 'c': /* critical time threshold */
561 if (is_intnonneg (optarg)) {
562 critical_time = atoi (optarg);
563 check_critical_time = TRUE;
564 }
565 else {
566 usage4 (_("Critical time must be a positive integer"));
567 }
568 break;
569 case 'w': /* warning time threshold */
570 if (is_intnonneg (optarg)) {
571 warning_time = atoi (optarg);
572 check_warning_time = TRUE;
573 }
574 else {
575 usage4 (_("Warning time must be a positive integer"));
576 }
577 break;
578 case 'v': /* verbose */
579 verbose++;
580 break;
581 case 't': /* timeout */
582 if (is_intnonneg (optarg)) {
583 socket_timeout = atoi (optarg);
584 }
585 else {
586 usage4 (_("Timeout interval must be a positive integer"));
587 }
588 break;
589 case 'S':
590 /* starttls */
591 use_ssl = TRUE;
592 use_ehlo = TRUE;
593 break;
594 case 'D':
595 /* Check SSL cert validity */
596 #ifdef USE_OPENSSL
597 if (!is_intnonneg (optarg))
598 usage2 ("Invalid certificate expiration period",optarg);
599 days_till_exp = atoi (optarg);
600 check_cert = TRUE;
601 #else
602 usage (_("SSL support not available - install OpenSSL and recompile"));
603 #endif
604 break;
605 case '4':
606 address_family = AF_INET;
607 break;
608 case '6':
609 #ifdef USE_IPV6
610 address_family = AF_INET6;
611 #else
612 usage4 (_("IPv6 support not available"));
613 #endif
614 break;
615 case 'V': /* version */
616 print_revision (progname, revision);
617 exit (STATE_OK);
618 case 'h': /* help */
619 print_help ();
620 exit (STATE_OK);
621 case '?': /* help */
622 usage2 (_("Unknown argument"), optarg);
623 }
624 }
626 c = optind;
627 if (server_address == NULL) {
628 if (argv[c]) {
629 if (is_host (argv[c]))
630 server_address = argv[c];
631 else
632 usage2 (_("Invalid hostname/address"), argv[c]);
633 }
634 else {
635 asprintf (&server_address, "127.0.0.1");
636 }
637 }
639 if (server_expect == NULL)
640 server_expect = strdup (SMTP_EXPECT);
642 if (mail_command == NULL)
643 mail_command = strdup("MAIL ");
645 if (from_arg==NULL)
646 from_arg = strdup(" ");
648 return validate_arguments ();
649 }
653 int
654 validate_arguments (void)
655 {
656 return OK;
657 }
661 void
662 print_help (void)
663 {
664 char *myport;
665 asprintf (&myport, "%d", SMTP_PORT);
667 print_revision (progname, revision);
669 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
670 printf (COPYRIGHT, copyright, email);
672 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
674 print_usage ();
676 printf (_(UT_HELP_VRSN));
678 printf (_(UT_HOST_PORT), 'p', myport);
680 printf (_(UT_IPv46));
682 printf (_("\
683 -e, --expect=STRING\n\
684 String to expect in first line of server response (default: '%s')\n\
685 -n, nocommand\n\
686 Suppress SMTP command\n\
687 -C, --command=STRING\n\
688 SMTP command (may be used repeatedly)\n\
689 -R, --command=STRING\n\
690 Expected response to command (may be used repeatedly)\n\
691 -f, --from=STRING\n\
692 FROM-address to include in MAIL command, required by Exchange 2000\n"),
693 SMTP_EXPECT);
694 #ifdef HAVE_SSL
695 printf (_("\
696 -D, --certificate=INTEGER\n\
697 Minimum number of days a certificate has to be valid.\n\
698 -S, --starttls\n\
699 Use STARTTLS for the connection.\n"));
700 #endif
702 printf("\
703 -A, --authtype=STRING\n\
704 SMTP AUTH type to check (default none, only LOGIN supported)\n\
705 -U, --authuser=STRING\n\
706 SMTP AUTH username\n\
707 -P, --authpass=STRING\n\
708 SMTP AUTH password\n\
709 ");
711 printf (_(UT_WARN_CRIT));
713 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
715 printf (_(UT_VERBOSE));
717 printf(_("\n\
718 Successul connects return STATE_OK, refusals and timeouts return\n\
719 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
720 connects, but incorrect reponse messages from the host result in\n\
721 STATE_WARNING return values.\n"));
723 printf (_(UT_SUPPORT));
724 }
728 void
729 print_usage (void)
730 {
731 printf ("\
732 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
733 [-A authtype -U authuser -P authpass]\n\
734 [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
735 }
737 int
738 my_close (void)
739 {
740 #ifdef HAVE_SSL
741 np_net_ssl_cleanup();
742 #endif
743 return close(sd);
744 }