1 /*****************************************************************************
3 * Nagios check_smtp plugin
6 * Copyright (c) 2000-2007 Nagios Plugins Development Team
10 * This file contains the check_smtp plugin
12 * This plugin will attempt to open an SMTP connection with the host.
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 *****************************************************************************/
31 const char *progname
= "check_smtp";
32 const char *copyright
= "2000-2007";
33 const char *email
= "nagiosplug-devel@lists.sourceforge.net";
43 int check_cert
= FALSE
;
45 # define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
46 # define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
47 #else /* ifndef HAVE_SSL */
48 # define my_recv(buf, len) read(sd, buf, len)
49 # define my_send(buf, len) send(sd, buf, len, 0)
55 #define SMTP_EXPECT "220"
56 #define SMTP_HELO "HELO "
57 #define SMTP_EHLO "EHLO "
58 #define SMTP_QUIT "QUIT\r\n"
59 #define SMTP_STARTTLS "STARTTLS\r\n"
60 #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
62 #ifndef HOST_MAX_BYTES
63 #define HOST_MAX_BYTES 255
66 #define EHLO_SUPPORTS_STARTTLS 1
68 int process_arguments (int, char **);
69 int validate_arguments (void);
70 void print_help (void);
71 void print_usage (void);
73 int recvline(char *, size_t);
74 int recvlines(char *, size_t);
78 char regex_expect
[MAX_INPUT_BUFFER
] = "";
80 regmatch_t pmatch
[10];
81 char timestamp
[20] = "";
82 char errbuf
[MAX_INPUT_BUFFER
];
83 int cflags
= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
87 int server_port
= SMTP_PORT
;
88 char *server_address
= NULL
;
89 char *server_expect
= NULL
;
90 int smtp_use_dummycmd
= 0;
91 char *mail_command
= NULL
;
92 char *from_arg
= NULL
;
97 char **commands
= NULL
;
98 char **responses
= NULL
;
99 char *authtype
= NULL
;
100 char *authuser
= NULL
;
101 char *authpass
= NULL
;
102 int warning_time
= 0;
103 int check_warning_time
= FALSE
;
104 int critical_time
= 0;
105 int check_critical_time
= FALSE
;
108 short use_ehlo
= FALSE
;
109 short ssl_established
= 0;
110 char *localhostname
= NULL
;
112 char buffer
[MAX_INPUT_BUFFER
];
120 main (int argc
, char **argv
)
122 short supports_tls
=FALSE
;
126 int result
= STATE_UNKNOWN
;
127 char *cmd_str
= NULL
;
128 char *helocmd
= NULL
;
129 char *error_msg
= "";
132 setlocale (LC_ALL
, "");
133 bindtextdomain (PACKAGE
, LOCALEDIR
);
134 textdomain (PACKAGE
);
136 /* Parse extra opts if any */
137 argv
=np_extra_opts (&argc
, argv
, progname
);
139 if (process_arguments (argc
, argv
) == ERROR
)
140 usage4 (_("Could not parse arguments"));
142 /* If localhostname not set on command line, use gethostname to set */
144 localhostname
= malloc (HOST_MAX_BYTES
);
146 printf(_("malloc() failed!\n"));
147 return STATE_CRITICAL
;
149 if(gethostname(localhostname
, HOST_MAX_BYTES
)){
150 printf(_("gethostname() failed!\n"));
151 return STATE_CRITICAL
;
155 asprintf (&helocmd
, "%s%s%s", SMTP_EHLO
, localhostname
, "\r\n");
157 asprintf (&helocmd
, "%s%s%s", SMTP_HELO
, localhostname
, "\r\n");
160 printf("HELOCMD: %s", helocmd
);
162 /* initialize the MAIL command with optional FROM command */
163 asprintf (&cmd_str
, "%sFROM: %s%s", mail_command
, from_arg
, "\r\n");
165 if (verbose
&& smtp_use_dummycmd
)
166 printf ("FROM CMD: %s", cmd_str
);
168 /* initialize alarm signal handling */
169 (void) signal (SIGALRM
, socket_timeout_alarm_handler
);
171 /* set socket timeout */
172 (void) alarm (socket_timeout
);
175 gettimeofday (&tv
, NULL
);
177 /* try to connect to the host at the given port number */
178 result
= my_tcp_connect (server_address
, server_port
, &sd
);
180 if (result
== STATE_OK
) { /* we connected */
182 /* watch for the SMTP connection string and */
183 /* return a WARNING status if we couldn't read any data */
184 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
185 printf (_("recv() failed\n"));
186 result
= STATE_WARNING
;
190 printf ("%s", buffer
);
191 /* strip the buffer of carriage returns */
193 /* make sure we find the response we are looking for */
194 if (!strstr (buffer
, server_expect
)) {
195 if (server_port
== SMTP_PORT
)
196 printf (_("Invalid SMTP response received from host: %s\n"), buffer
);
198 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
199 server_port
, buffer
);
200 result
= STATE_WARNING
;
204 /* send the HELO/EHLO command */
205 send(sd
, helocmd
, strlen(helocmd
), 0);
207 /* allow for response to helo command to reach us */
208 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
209 printf (_("recv() failed\n"));
210 return STATE_WARNING
;
212 if(strstr(buffer
, "250 STARTTLS") != NULL
||
213 strstr(buffer
, "250-STARTTLS") != NULL
){
218 if(use_ssl
&& ! supports_tls
){
219 printf(_("WARNING - TLS not supported by server\n"));
221 return STATE_WARNING
;
226 /* send the STARTTLS command */
227 send(sd
, SMTP_STARTTLS
, strlen(SMTP_STARTTLS
), 0);
229 recvlines(buffer
, MAX_INPUT_BUFFER
); /* wait for it */
230 if (!strstr (buffer
, server_expect
)) {
231 printf (_("Server does not support STARTTLS\n"));
233 return STATE_UNKNOWN
;
235 result
= np_net_ssl_init(sd
);
236 if(result
!= STATE_OK
) {
237 printf (_("CRITICAL - Cannot create SSL context.\n"));
238 np_net_ssl_cleanup();
240 return STATE_CRITICAL
;
246 * Resend the EHLO command.
248 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
249 * obtained from the server, such as the list of SMTP service
250 * extensions, which was not obtained from the TLS negotiation
251 * itself. The client SHOULD send an EHLO command as the first
252 * command after a successful TLS negotiation.'' For this
253 * reason, some MTAs will not allow an AUTH LOGIN command before
254 * we resent EHLO via TLS.
256 if (my_send(helocmd
, strlen(helocmd
)) <= 0) {
257 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
259 return STATE_UNKNOWN
;
262 printf(_("sent %s"), helocmd
);
263 if ((n
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
264 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
266 return STATE_UNKNOWN
;
269 printf("%s", buffer
);
274 result
= np_net_ssl_check_cert(days_till_exp
);
275 if(result
!= STATE_OK
){
276 printf ("%s\n", _("CRITICAL - Cannot retrieve server certificate."));
281 # endif /* USE_OPENSSL */
285 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
286 * to do something useful. This can be prevented by giving a command
287 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
289 * According to rfc821 you can include a null reversepath in the from command
290 * - but a log message is generated on the smtp server.
292 * You can disable sending mail_command with '--nocommand'
293 * Use the -f option to provide a FROM address
295 if (smtp_use_dummycmd
) {
296 my_send(cmd_str
, strlen(cmd_str
));
297 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
298 printf("%s", buffer
);
301 while (n
< ncommands
) {
302 asprintf (&cmd_str
, "%s%s", commands
[n
], "\r\n");
303 my_send(cmd_str
, strlen(cmd_str
));
304 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
305 printf("%s", buffer
);
307 if (n
< nresponses
) {
308 cflags
|= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
309 errcode
= regcomp (&preg
, responses
[n
], cflags
);
311 regerror (errcode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
312 printf (_("Could Not Compile Regular Expression"));
315 excode
= regexec (&preg
, buffer
, 10, pmatch
, eflags
);
319 else if (excode
== REG_NOMATCH
) {
320 result
= STATE_WARNING
;
321 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result
), buffer
, commands
[n
]);
324 regerror (excode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
325 printf (_("Execute Error: %s\n"), errbuf
);
326 result
= STATE_UNKNOWN
;
332 if (authtype
!= NULL
) {
333 if (strcmp (authtype
, "LOGIN") == 0) {
337 if (authuser
== NULL
) {
338 result
= STATE_CRITICAL
;
339 asprintf(&error_msg
, _("no authuser specified, "));
342 if (authpass
== NULL
) {
343 result
= STATE_CRITICAL
;
344 asprintf(&error_msg
, _("no authpass specified, "));
348 /* send AUTH LOGIN */
349 my_send(SMTP_AUTH_LOGIN
, strlen(SMTP_AUTH_LOGIN
));
351 printf (_("sent %s\n"), "AUTH LOGIN");
353 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
354 asprintf(&error_msg
, _("recv() failed after AUTH LOGIN, "));
355 result
= STATE_WARNING
;
359 printf (_("received %s\n"), buffer
);
361 if (strncmp (buffer
, "334", 3) != 0) {
362 result
= STATE_CRITICAL
;
363 asprintf(&error_msg
, _("invalid response received after AUTH LOGIN, "));
367 /* encode authuser with base64 */
368 base64_encode_alloc (authuser
, strlen(authuser
), &abuf
);
369 /* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
370 strcat (abuf
, "\r\n");
371 my_send(abuf
, strlen(abuf
));
373 printf (_("sent %s\n"), abuf
);
375 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
376 result
= STATE_CRITICAL
;
377 asprintf(&error_msg
, _("recv() failed after sending authuser, "));
381 printf (_("received %s\n"), buffer
);
383 if (strncmp (buffer
, "334", 3) != 0) {
384 result
= STATE_CRITICAL
;
385 asprintf(&error_msg
, _("invalid response received after authuser, "));
388 /* encode authpass with base64 */
389 base64_encode_alloc (authpass
, strlen(authpass
), &abuf
);
390 /* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
391 strcat (abuf
, "\r\n");
392 my_send(abuf
, strlen(abuf
));
394 printf (_("sent %s\n"), abuf
);
396 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
397 result
= STATE_CRITICAL
;
398 asprintf(&error_msg
, _("recv() failed after sending authpass, "));
402 printf (_("received %s\n"), buffer
);
404 if (strncmp (buffer
, "235", 3) != 0) {
405 result
= STATE_CRITICAL
;
406 asprintf(&error_msg
, _("invalid response received after authpass, "));
412 result
= STATE_CRITICAL
;
413 asprintf(&error_msg
, _("only authtype LOGIN is supported, "));
417 /* tell the server we're done */
420 /* finally close the connection */
424 /* reset the alarm */
427 microsec
= deltime (tv
);
428 elapsed_time
= (double)microsec
/ 1.0e6
;
430 if (result
== STATE_OK
) {
431 if (check_critical_time
&& elapsed_time
> (double) critical_time
)
432 result
= STATE_CRITICAL
;
433 else if (check_warning_time
&& elapsed_time
> (double) warning_time
)
434 result
= STATE_WARNING
;
437 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
441 verbose
?", ":"", verbose
?buffer
:"",
442 fperfdata ("time", elapsed_time
, "s",
443 (int)check_warning_time
, warning_time
,
444 (int)check_critical_time
, critical_time
,
452 /* process command-line arguments */
454 process_arguments (int argc
, char **argv
)
459 static struct option longopts
[] = {
460 {"hostname", required_argument
, 0, 'H'},
461 {"expect", required_argument
, 0, 'e'},
462 {"critical", required_argument
, 0, 'c'},
463 {"warning", required_argument
, 0, 'w'},
464 {"timeout", required_argument
, 0, 't'},
465 {"port", required_argument
, 0, 'p'},
466 {"from", required_argument
, 0, 'f'},
467 {"fqdn", required_argument
, 0, 'F'},
468 {"authtype", required_argument
, 0, 'A'},
469 {"authuser", required_argument
, 0, 'U'},
470 {"authpass", required_argument
, 0, 'P'},
471 {"command", required_argument
, 0, 'C'},
472 {"response", required_argument
, 0, 'R'},
473 {"nocommand", required_argument
, 0, 'n'},
474 {"verbose", no_argument
, 0, 'v'},
475 {"version", no_argument
, 0, 'V'},
476 {"use-ipv4", no_argument
, 0, '4'},
477 {"use-ipv6", no_argument
, 0, '6'},
478 {"help", no_argument
, 0, 'h'},
479 {"starttls",no_argument
,0,'S'},
480 {"certificate",required_argument
,0,'D'},
487 for (c
= 1; c
< argc
; c
++) {
488 if (strcmp ("-to", argv
[c
]) == 0)
489 strcpy (argv
[c
], "-t");
490 else if (strcmp ("-wt", argv
[c
]) == 0)
491 strcpy (argv
[c
], "-w");
492 else if (strcmp ("-ct", argv
[c
]) == 0)
493 strcpy (argv
[c
], "-c");
497 c
= getopt_long (argc
, argv
, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:",
500 if (c
== -1 || c
== EOF
)
504 case 'H': /* hostname */
505 if (is_host (optarg
)) {
506 server_address
= optarg
;
509 usage2 (_("Invalid hostname/address"), optarg
);
513 if (is_intpos (optarg
))
514 server_port
= atoi (optarg
);
516 usage4 (_("Port must be a positive integer"));
520 localhostname
= strdup(optarg
);
522 case 'f': /* from argument */
524 smtp_use_dummycmd
= 1;
536 case 'e': /* server expect string on 220 */
537 server_expect
= optarg
;
539 case 'C': /* commands */
540 if (ncommands
>= command_size
) {
542 commands
= realloc (commands
, sizeof(char *) * command_size
);
543 if (commands
== NULL
)
545 _("Could not realloc() units [%d]\n"), ncommands
);
547 commands
[ncommands
] = (char *) malloc (sizeof(char) * 255);
548 strncpy (commands
[ncommands
], optarg
, 255);
551 case 'R': /* server responses */
552 if (nresponses
>= response_size
) {
554 responses
= realloc (responses
, sizeof(char *) * response_size
);
555 if (responses
== NULL
)
557 _("Could not realloc() units [%d]\n"), nresponses
);
559 responses
[nresponses
] = (char *) malloc (sizeof(char) * 255);
560 strncpy (responses
[nresponses
], optarg
, 255);
563 case 'c': /* critical time threshold */
564 if (is_intnonneg (optarg
)) {
565 critical_time
= atoi (optarg
);
566 check_critical_time
= TRUE
;
569 usage4 (_("Critical time must be a positive integer"));
572 case 'w': /* warning time threshold */
573 if (is_intnonneg (optarg
)) {
574 warning_time
= atoi (optarg
);
575 check_warning_time
= TRUE
;
578 usage4 (_("Warning time must be a positive integer"));
581 case 'v': /* verbose */
584 case 't': /* timeout */
585 if (is_intnonneg (optarg
)) {
586 socket_timeout
= atoi (optarg
);
589 usage4 (_("Timeout interval must be a positive integer"));
598 /* Check SSL cert validity */
600 if (!is_intnonneg (optarg
))
601 usage2 ("Invalid certificate expiration period",optarg
);
602 days_till_exp
= atoi (optarg
);
605 usage (_("SSL support not available - install OpenSSL and recompile"));
609 address_family
= AF_INET
;
613 address_family
= AF_INET6
;
615 usage4 (_("IPv6 support not available"));
618 case 'V': /* version */
619 print_revision (progname
, NP_VERSION
);
630 if (server_address
== NULL
) {
632 if (is_host (argv
[c
]))
633 server_address
= argv
[c
];
635 usage2 (_("Invalid hostname/address"), argv
[c
]);
638 asprintf (&server_address
, "127.0.0.1");
642 if (server_expect
== NULL
)
643 server_expect
= strdup (SMTP_EXPECT
);
645 if (mail_command
== NULL
)
646 mail_command
= strdup("MAIL ");
649 from_arg
= strdup(" ");
651 return validate_arguments ();
657 validate_arguments (void)
668 my_send(SMTP_QUIT
, strlen(SMTP_QUIT
));
670 printf(_("sent %s\n"), "QUIT");
672 /* read the response but don't care about problems */
673 bytes
= recvlines(buffer
, MAX_INPUT_BUFFER
);
676 printf(_("recv() failed after QUIT."));
678 printf(_("Connection reset by peer."));
680 buffer
[bytes
] = '\0';
681 printf(_("received %s\n"), buffer
);
688 * Receive one line, copy it into buf and nul-terminate it. Returns the
689 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
692 * TODO: Reading one byte at a time is very inefficient. Replace this by a
693 * function which buffers the data, move that to netutils.c and change
694 * check_smtp and other plugins to use that. Also, remove (\r)\n.
697 recvline(char *buf
, size_t bufsize
)
702 for (i
= result
= 0; i
< bufsize
- 1; i
++) {
703 if ((result
= my_recv(&buf
[i
], 1)) != 1)
705 if (buf
[i
] == '\n') {
710 return (result
== 1 || i
== 0) ? -2 : result
; /* -2 if out of space */
715 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
716 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
717 * error. Works for all protocols which format multiline replies as follows:
719 * ``The format for multiline replies requires that every line, except the last,
720 * begin with the reply code, followed immediately by a hyphen, `-' (also known
721 * as minus), followed by text. The last line will begin with the reply code,
722 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
723 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
724 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
726 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
729 recvlines(char *buf
, size_t bufsize
)
733 for (i
= 0; /* forever */; i
+= result
)
734 if (!((result
= recvline(buf
+ i
, bufsize
- i
)) > 3 &&
735 isdigit((int)buf
[i
]) &&
736 isdigit((int)buf
[i
+ 1]) &&
737 isdigit((int)buf
[i
+ 2]) &&
741 return (result
<= 0) ? result
: result
+ i
;
749 np_net_ssl_cleanup();
759 asprintf (&myport
, "%d", SMTP_PORT
);
761 print_revision (progname
, NP_VERSION
);
763 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
764 printf (COPYRIGHT
, copyright
, email
);
766 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
772 printf (_(UT_HELP_VRSN
));
773 printf (_(UT_EXTRA_OPTS
));
775 printf (_(UT_HOST_PORT
), 'p', myport
);
777 printf (_(UT_IPv46
));
779 printf (" %s\n", "-e, --expect=STRING");
780 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT
);
781 printf (" %s\n", "-n, nocommand");
782 printf (" %s\n", _("Suppress SMTP command"));
783 printf (" %s\n", "-C, --command=STRING");
784 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
785 printf (" %s\n", "-R, --command=STRING");
786 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
787 printf (" %s\n", "-f, --from=STRING");
788 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
790 printf (" %s\n", "-D, --certificate=INTEGER");
791 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
792 printf (" %s\n", "-S, --starttls");
793 printf (" %s\n", _("Use STARTTLS for the connection."));
796 printf (" %s\n", "-A, --authtype=STRING");
797 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
798 printf (" %s\n", "-U, --authuser=STRING");
799 printf (" %s\n", _("SMTP AUTH username"));
800 printf (" %s\n", "-P, --authpass=STRING");
801 printf (" %s\n", _("SMTP AUTH password"));
803 printf (_(UT_WARN_CRIT
));
805 printf (_(UT_TIMEOUT
), DEFAULT_SOCKET_TIMEOUT
);
807 printf (_(UT_VERBOSE
));
810 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
811 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
812 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
813 printf ("%s\n", _("STATE_WARNING return values."));
817 printf ("%s\n", _("Notes:"));
818 printf (_(UT_EXTRA_OPTS_NOTES
));
821 printf (_(UT_SUPPORT
));
829 printf (_("Usage:"));
830 printf ("%s -H host [-p port] [-e expect] [-C command] [-f from addr]", progname
);
831 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout]\n");
832 printf ("[-S] [-D days] [-n] [-v] [-4|-6]\n");