1 /******************************************************************************
3 * Nagios check_smtp plugin
6 * Copyright (c) 1999-2006 nagios-plugins team
8 * Last Modified: $Date$
12 * This file contains the check_smtp plugin
14 * This plugin will attempt to open an SMTP connection with the host.
17 * License Information:
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36 ******************************************************************************/
38 const char *progname
= "check_smtp";
39 const char *revision
= "$Revision$";
40 const char *copyright
= "2000-2006";
41 const char *email
= "nagiosplug-devel@lists.sourceforge.net";
51 int check_cert
= FALSE
;
53 # define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
54 # define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
55 #else /* ifndef HAVE_SSL */
56 # define my_recv(buf, len) read(sd, buf, len)
57 # define my_send(buf, len) send(sd, buf, len, 0)
63 #define SMTP_EXPECT "220"
64 #define SMTP_HELO "HELO "
65 #define SMTP_EHLO "EHLO "
66 #define SMTP_QUIT "QUIT\r\n"
67 #define SMTP_STARTTLS "STARTTLS\r\n"
68 #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
70 #ifndef HOST_MAX_BYTES
71 #define HOST_MAX_BYTES 255
74 #define EHLO_SUPPORTS_STARTTLS 1
76 int process_arguments (int, char **);
77 int validate_arguments (void);
78 void print_help (void);
79 void print_usage (void);
81 int recvline(char *, size_t);
82 int recvlines(char *, size_t);
86 char regex_expect
[MAX_INPUT_BUFFER
] = "";
88 regmatch_t pmatch
[10];
89 char timestamp
[20] = "";
90 char errbuf
[MAX_INPUT_BUFFER
];
91 int cflags
= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
95 int server_port
= SMTP_PORT
;
96 char *server_address
= NULL
;
97 char *server_expect
= NULL
;
98 int smtp_use_dummycmd
= 0;
99 char *mail_command
= NULL
;
100 char *from_arg
= NULL
;
105 char **commands
= NULL
;
106 char **responses
= NULL
;
107 char *authtype
= NULL
;
108 char *authuser
= NULL
;
109 char *authpass
= NULL
;
110 int warning_time
= 0;
111 int check_warning_time
= FALSE
;
112 int critical_time
= 0;
113 int check_critical_time
= FALSE
;
116 short use_ehlo
= FALSE
;
117 short ssl_established
= 0;
118 char *localhostname
= NULL
;
120 char buffer
[MAX_INPUT_BUFFER
];
128 main (int argc
, char **argv
)
130 short supports_tls
=FALSE
;
134 int result
= STATE_UNKNOWN
;
135 char *cmd_str
= NULL
;
136 char *helocmd
= NULL
;
137 char *error_msg
= "";
140 setlocale (LC_ALL
, "");
141 bindtextdomain (PACKAGE
, LOCALEDIR
);
142 textdomain (PACKAGE
);
144 if (process_arguments (argc
, argv
) == ERROR
)
145 usage4 (_("Could not parse arguments"));
147 /* If localhostname not set on command line, use gethostname to set */
149 localhostname
= malloc (HOST_MAX_BYTES
);
151 printf(_("malloc() failed!\n"));
152 return STATE_CRITICAL
;
154 if(gethostname(localhostname
, HOST_MAX_BYTES
)){
155 printf(_("gethostname() failed!\n"));
156 return STATE_CRITICAL
;
160 asprintf (&helocmd
, "%s%s%s", SMTP_EHLO
, localhostname
, "\r\n");
162 asprintf (&helocmd
, "%s%s%s", SMTP_HELO
, localhostname
, "\r\n");
165 printf("HELOCMD: %s", helocmd
);
167 /* initialize the MAIL command with optional FROM command */
168 asprintf (&cmd_str
, "%sFROM: %s%s", mail_command
, from_arg
, "\r\n");
170 if (verbose
&& smtp_use_dummycmd
)
171 printf ("FROM CMD: %s", cmd_str
);
173 /* initialize alarm signal handling */
174 (void) signal (SIGALRM
, socket_timeout_alarm_handler
);
176 /* set socket timeout */
177 (void) alarm (socket_timeout
);
180 gettimeofday (&tv
, NULL
);
182 /* try to connect to the host at the given port number */
183 result
= my_tcp_connect (server_address
, server_port
, &sd
);
185 if (result
== STATE_OK
) { /* we connected */
187 /* watch for the SMTP connection string and */
188 /* return a WARNING status if we couldn't read any data */
189 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
190 printf (_("recv() failed\n"));
191 result
= STATE_WARNING
;
195 printf ("%s", buffer
);
196 /* strip the buffer of carriage returns */
198 /* make sure we find the response we are looking for */
199 if (!strstr (buffer
, server_expect
)) {
200 if (server_port
== SMTP_PORT
)
201 printf (_("Invalid SMTP response received from host\n"));
203 printf (_("Invalid SMTP response received from host on port %d\n"),
205 result
= STATE_WARNING
;
209 /* send the HELO/EHLO command */
210 send(sd
, helocmd
, strlen(helocmd
), 0);
212 /* allow for response to helo command to reach us */
213 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
214 printf (_("recv() failed\n"));
215 return STATE_WARNING
;
217 if(strstr(buffer
, "250 STARTTLS") != NULL
||
218 strstr(buffer
, "250-STARTTLS") != NULL
){
223 if(use_ssl
&& ! supports_tls
){
224 printf(_("WARNING - TLS not supported by server\n"));
226 return STATE_WARNING
;
231 /* send the STARTTLS command */
232 send(sd
, SMTP_STARTTLS
, strlen(SMTP_STARTTLS
), 0);
234 recvlines(buffer
, MAX_INPUT_BUFFER
); /* wait for it */
235 if (!strstr (buffer
, server_expect
)) {
236 printf (_("Server does not support STARTTLS\n"));
238 return STATE_UNKNOWN
;
240 result
= np_net_ssl_init(sd
);
241 if(result
!= STATE_OK
) {
242 printf (_("CRITICAL - Cannot create SSL context.\n"));
243 np_net_ssl_cleanup();
245 return STATE_CRITICAL
;
251 * Resend the EHLO command.
253 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
254 * obtained from the server, such as the list of SMTP service
255 * extensions, which was not obtained from the TLS negotiation
256 * itself. The client SHOULD send an EHLO command as the first
257 * command after a successful TLS negotiation.'' For this
258 * reason, some MTAs will not allow an AUTH LOGIN command before
259 * we resent EHLO via TLS.
261 if (my_send(helocmd
, strlen(helocmd
)) <= 0) {
262 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
264 return STATE_UNKNOWN
;
267 printf(_("sent %s"), helocmd
);
268 if ((n
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
269 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
271 return STATE_UNKNOWN
;
274 printf("%s", buffer
);
279 result
= np_net_ssl_check_cert(days_till_exp
);
280 if(result
!= STATE_OK
){
281 printf ("%s\n", _("CRITICAL - Cannot retrieve server certificate."));
286 # endif /* USE_OPENSSL */
290 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
291 * to do something useful. This can be prevented by giving a command
292 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
294 * According to rfc821 you can include a null reversepath in the from command
295 * - but a log message is generated on the smtp server.
297 * You can disable sending mail_command with '--nocommand'
298 * Use the -f option to provide a FROM address
300 if (smtp_use_dummycmd
) {
301 my_send(cmd_str
, strlen(cmd_str
));
302 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
303 printf("%s", buffer
);
306 while (n
< ncommands
) {
307 asprintf (&cmd_str
, "%s%s", commands
[n
], "\r\n");
308 my_send(cmd_str
, strlen(cmd_str
));
309 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
310 printf("%s", buffer
);
312 if (n
< nresponses
) {
313 cflags
|= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
314 errcode
= regcomp (&preg
, responses
[n
], cflags
);
316 regerror (errcode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
317 printf (_("Could Not Compile Regular Expression"));
320 excode
= regexec (&preg
, buffer
, 10, pmatch
, eflags
);
324 else if (excode
== REG_NOMATCH
) {
325 result
= STATE_WARNING
;
326 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result
), buffer
, commands
[n
]);
329 regerror (excode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
330 printf (_("Execute Error: %s\n"), errbuf
);
331 result
= STATE_UNKNOWN
;
337 if (authtype
!= NULL
) {
338 if (strcmp (authtype
, "LOGIN") == 0) {
342 if (authuser
== NULL
) {
343 result
= STATE_CRITICAL
;
344 asprintf(&error_msg
, _("no authuser specified, "));
347 if (authpass
== NULL
) {
348 result
= STATE_CRITICAL
;
349 asprintf(&error_msg
, _("no authpass specified, "));
353 /* send AUTH LOGIN */
354 my_send(SMTP_AUTH_LOGIN
, strlen(SMTP_AUTH_LOGIN
));
356 printf (_("sent %s\n"), "AUTH LOGIN");
358 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
359 asprintf(&error_msg
, _("recv() failed after AUTH LOGIN, "));
360 result
= STATE_WARNING
;
364 printf (_("received %s\n"), buffer
);
366 if (strncmp (buffer
, "334", 3) != 0) {
367 result
= STATE_CRITICAL
;
368 asprintf(&error_msg
, _("invalid response received after AUTH LOGIN, "));
372 /* encode authuser with base64 */
373 abuf
= base64 (authuser
, strlen(authuser
));
374 strcat (abuf
, "\r\n");
375 my_send(abuf
, strlen(abuf
));
377 printf (_("sent %s\n"), abuf
);
379 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
380 result
= STATE_CRITICAL
;
381 asprintf(&error_msg
, _("recv() failed after sending authuser, "));
385 printf (_("received %s\n"), buffer
);
387 if (strncmp (buffer
, "334", 3) != 0) {
388 result
= STATE_CRITICAL
;
389 asprintf(&error_msg
, _("invalid response received after authuser, "));
392 /* encode authpass with base64 */
393 abuf
= base64 (authpass
, strlen(authpass
));
394 strcat (abuf
, "\r\n");
395 my_send(abuf
, strlen(abuf
));
397 printf (_("sent %s\n"), abuf
);
399 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
400 result
= STATE_CRITICAL
;
401 asprintf(&error_msg
, _("recv() failed after sending authpass, "));
405 printf (_("received %s\n"), buffer
);
407 if (strncmp (buffer
, "235", 3) != 0) {
408 result
= STATE_CRITICAL
;
409 asprintf(&error_msg
, _("invalid response received after authpass, "));
415 result
= STATE_CRITICAL
;
416 asprintf(&error_msg
, _("only authtype LOGIN is supported, "));
420 /* tell the server we're done */
423 /* finally close the connection */
427 /* reset the alarm */
430 microsec
= deltime (tv
);
431 elapsed_time
= (double)microsec
/ 1.0e6
;
433 if (result
== STATE_OK
) {
434 if (check_critical_time
&& elapsed_time
> (double) critical_time
)
435 result
= STATE_CRITICAL
;
436 else if (check_warning_time
&& elapsed_time
> (double) warning_time
)
437 result
= STATE_WARNING
;
440 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
444 verbose
?", ":"", verbose
?buffer
:"",
445 fperfdata ("time", elapsed_time
, "s",
446 (int)check_warning_time
, warning_time
,
447 (int)check_critical_time
, critical_time
,
455 /* process command-line arguments */
457 process_arguments (int argc
, char **argv
)
462 static struct option longopts
[] = {
463 {"hostname", required_argument
, 0, 'H'},
464 {"expect", required_argument
, 0, 'e'},
465 {"critical", required_argument
, 0, 'c'},
466 {"warning", required_argument
, 0, 'w'},
467 {"timeout", required_argument
, 0, 't'},
468 {"port", required_argument
, 0, 'p'},
469 {"from", required_argument
, 0, 'f'},
470 {"fqdn", required_argument
, 0, 'F'},
471 {"authtype", required_argument
, 0, 'A'},
472 {"authuser", required_argument
, 0, 'U'},
473 {"authpass", required_argument
, 0, 'P'},
474 {"command", required_argument
, 0, 'C'},
475 {"response", required_argument
, 0, 'R'},
476 {"nocommand", required_argument
, 0, 'n'},
477 {"verbose", no_argument
, 0, 'v'},
478 {"version", no_argument
, 0, 'V'},
479 {"use-ipv4", no_argument
, 0, '4'},
480 {"use-ipv6", no_argument
, 0, '6'},
481 {"help", no_argument
, 0, 'h'},
482 {"starttls",no_argument
,0,'S'},
483 {"certificate",required_argument
,0,'D'},
490 for (c
= 1; c
< argc
; c
++) {
491 if (strcmp ("-to", argv
[c
]) == 0)
492 strcpy (argv
[c
], "-t");
493 else if (strcmp ("-wt", argv
[c
]) == 0)
494 strcpy (argv
[c
], "-w");
495 else if (strcmp ("-ct", argv
[c
]) == 0)
496 strcpy (argv
[c
], "-c");
500 c
= getopt_long (argc
, argv
, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:",
503 if (c
== -1 || c
== EOF
)
507 case 'H': /* hostname */
508 if (is_host (optarg
)) {
509 server_address
= optarg
;
512 usage2 (_("Invalid hostname/address"), optarg
);
516 if (is_intpos (optarg
))
517 server_port
= atoi (optarg
);
519 usage4 (_("Port must be a positive integer"));
523 localhostname
= strdup(optarg
);
525 case 'f': /* from argument */
527 smtp_use_dummycmd
= 1;
539 case 'e': /* server expect string on 220 */
540 server_expect
= optarg
;
542 case 'C': /* commands */
543 if (ncommands
>= command_size
) {
545 commands
= realloc (commands
, sizeof(char *) * command_size
);
546 if (commands
== NULL
)
548 _("Could not realloc() units [%d]\n"), ncommands
);
550 commands
[ncommands
] = (char *) malloc (sizeof(char) * 255);
551 strncpy (commands
[ncommands
], optarg
, 255);
554 case 'R': /* server responses */
555 if (nresponses
>= response_size
) {
557 responses
= realloc (responses
, sizeof(char *) * response_size
);
558 if (responses
== NULL
)
560 _("Could not realloc() units [%d]\n"), nresponses
);
562 responses
[nresponses
] = (char *) malloc (sizeof(char) * 255);
563 strncpy (responses
[nresponses
], optarg
, 255);
566 case 'c': /* critical time threshold */
567 if (is_intnonneg (optarg
)) {
568 critical_time
= atoi (optarg
);
569 check_critical_time
= TRUE
;
572 usage4 (_("Critical time must be a positive integer"));
575 case 'w': /* warning time threshold */
576 if (is_intnonneg (optarg
)) {
577 warning_time
= atoi (optarg
);
578 check_warning_time
= TRUE
;
581 usage4 (_("Warning time must be a positive integer"));
584 case 'v': /* verbose */
587 case 't': /* timeout */
588 if (is_intnonneg (optarg
)) {
589 socket_timeout
= atoi (optarg
);
592 usage4 (_("Timeout interval must be a positive integer"));
601 /* Check SSL cert validity */
603 if (!is_intnonneg (optarg
))
604 usage2 ("Invalid certificate expiration period",optarg
);
605 days_till_exp
= atoi (optarg
);
608 usage (_("SSL support not available - install OpenSSL and recompile"));
612 address_family
= AF_INET
;
616 address_family
= AF_INET6
;
618 usage4 (_("IPv6 support not available"));
621 case 'V': /* version */
622 print_revision (progname
, revision
);
633 if (server_address
== NULL
) {
635 if (is_host (argv
[c
]))
636 server_address
= argv
[c
];
638 usage2 (_("Invalid hostname/address"), argv
[c
]);
641 asprintf (&server_address
, "127.0.0.1");
645 if (server_expect
== NULL
)
646 server_expect
= strdup (SMTP_EXPECT
);
648 if (mail_command
== NULL
)
649 mail_command
= strdup("MAIL ");
652 from_arg
= strdup(" ");
654 return validate_arguments ();
660 validate_arguments (void)
671 my_send(SMTP_QUIT
, strlen(SMTP_QUIT
));
673 printf(_("sent %s\n"), "QUIT");
675 /* read the response but don't care about problems */
676 bytes
= recvlines(buffer
, MAX_INPUT_BUFFER
);
679 printf(_("recv() failed after QUIT."));
681 printf(_("Connection reset by peer."));
683 buffer
[bytes
] = '\0';
684 printf(_("received %s\n"), buffer
);
691 * Receive one line, copy it into buf and nul-terminate it. Returns the
692 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
695 * TODO: Reading one byte at a time is very inefficient. Replace this by a
696 * function which buffers the data, move that to netutils.c and change
697 * check_smtp and other plugins to use that. Also, remove (\r)\n.
700 recvline(char *buf
, size_t bufsize
)
705 for (i
= result
= 0; i
< bufsize
- 1; i
++) {
706 if ((result
= my_recv(&buf
[i
], 1)) != 1)
708 if (buf
[i
] == '\n') {
713 return (result
== 1 || i
== 0) ? -2 : result
; /* -2 if out of space */
718 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
719 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
720 * error. Works for all protocols which format multiline replies as follows:
722 * ``The format for multiline replies requires that every line, except the last,
723 * begin with the reply code, followed immediately by a hyphen, `-' (also known
724 * as minus), followed by text. The last line will begin with the reply code,
725 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
726 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
727 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
729 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
732 recvlines(char *buf
, size_t bufsize
)
736 for (i
= 0; /* forever */; i
+= result
)
737 if (!((result
= recvline(buf
+ i
, bufsize
- i
)) > 3 &&
738 isdigit((int)buf
[i
]) &&
739 isdigit((int)buf
[i
+ 1]) &&
740 isdigit((int)buf
[i
+ 2]) &&
744 return (result
<= 0) ? result
: result
+ i
;
752 np_net_ssl_cleanup();
762 asprintf (&myport
, "%d", SMTP_PORT
);
764 print_revision (progname
, revision
);
766 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
767 printf (COPYRIGHT
, copyright
, email
);
769 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
775 printf (_(UT_HELP_VRSN
));
777 printf (_(UT_HOST_PORT
), 'p', myport
);
779 printf (_(UT_IPv46
));
781 printf (" %s\n", "-e, --expect=STRING");
782 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT
);
783 printf (" %s\n", "-n, nocommand");
784 printf (" %s\n", _("Suppress SMTP command"));
785 printf (" %s\n", "-C, --command=STRING");
786 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
787 printf (" %s\n", "-R, --command=STRING");
788 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
789 printf (" %s\n", "-f, --from=STRING");
790 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
792 printf (" %s\n", "-D, --certificate=INTEGER");
793 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
794 printf (" %s\n", "-S, --starttls");
795 printf (" %s\n", _("Use STARTTLS for the connection."));
798 printf (" %s\n", "-A, --authtype=STRING");
799 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
800 printf (" %s\n", "-U, --authuser=STRING");
801 printf (" %s\n", _("SMTP AUTH username"));
802 printf (" %s\n", "-P, --authpass=STRING");
803 printf (" %s\n", _("SMTP AUTH password"));
805 printf (_(UT_WARN_CRIT
));
807 printf (_(UT_TIMEOUT
), DEFAULT_SOCKET_TIMEOUT
);
809 printf (_(UT_VERBOSE
));
812 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
813 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
814 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
815 printf ("%s\n", _("STATE_WARNING return values."));
817 printf (_(UT_SUPPORT
));
825 printf (_("Usage:"));
826 printf ("%s -H host [-p port] [-e expect] [-C command] [-f from addr]", progname
);
827 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout]\n");
828 printf ("[-S] [-D days] [-n] [-v] [-4|-6]\n");