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
;
44 int days_till_exp_warn
, days_till_exp_crit
;
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
];
117 int ignore_send_quit_failure
= FALSE
;
121 main (int argc
, char **argv
)
123 short supports_tls
=FALSE
;
127 int result
= STATE_UNKNOWN
;
128 char *cmd_str
= NULL
;
129 char *helocmd
= NULL
;
130 char *error_msg
= "";
133 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
134 (void) signal (SIGPIPE
, SIG_IGN
);
136 setlocale (LC_ALL
, "");
137 bindtextdomain (PACKAGE
, LOCALEDIR
);
138 textdomain (PACKAGE
);
140 /* Parse extra opts if any */
141 argv
=np_extra_opts (&argc
, argv
, progname
);
143 if (process_arguments (argc
, argv
) == ERROR
)
144 usage4 (_("Could not parse arguments"));
146 /* If localhostname not set on command line, use gethostname to set */
148 localhostname
= malloc (HOST_MAX_BYTES
);
150 printf(_("malloc() failed!\n"));
151 return STATE_CRITICAL
;
153 if(gethostname(localhostname
, HOST_MAX_BYTES
)){
154 printf(_("gethostname() failed!\n"));
155 return STATE_CRITICAL
;
159 asprintf (&helocmd
, "%s%s%s", SMTP_EHLO
, localhostname
, "\r\n");
161 asprintf (&helocmd
, "%s%s%s", SMTP_HELO
, localhostname
, "\r\n");
164 printf("HELOCMD: %s", helocmd
);
166 /* initialize the MAIL command with optional FROM command */
167 asprintf (&cmd_str
, "%sFROM: %s%s", mail_command
, from_arg
, "\r\n");
169 if (verbose
&& smtp_use_dummycmd
)
170 printf ("FROM CMD: %s", cmd_str
);
172 /* initialize alarm signal handling */
173 (void) signal (SIGALRM
, socket_timeout_alarm_handler
);
175 /* set socket timeout */
176 (void) alarm (socket_timeout
);
179 gettimeofday (&tv
, NULL
);
181 /* try to connect to the host at the given port number */
182 result
= my_tcp_connect (server_address
, server_port
, &sd
);
184 if (result
== STATE_OK
) { /* we connected */
186 /* watch for the SMTP connection string and */
187 /* return a WARNING status if we couldn't read any data */
188 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
189 printf (_("recv() failed\n"));
190 return STATE_WARNING
;
194 printf ("%s", buffer
);
195 /* strip the buffer of carriage returns */
197 /* make sure we find the response we are looking for */
198 if (!strstr (buffer
, server_expect
)) {
199 if (server_port
== SMTP_PORT
)
200 printf (_("Invalid SMTP response received from host: %s\n"), buffer
);
202 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
203 server_port
, buffer
);
204 return STATE_WARNING
;
208 /* send the HELO/EHLO command */
209 send(sd
, helocmd
, strlen(helocmd
), 0);
211 /* allow for response to helo command to reach us */
212 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
213 printf (_("recv() failed\n"));
214 return STATE_WARNING
;
216 if(strstr(buffer
, "250 STARTTLS") != NULL
||
217 strstr(buffer
, "250-STARTTLS") != NULL
){
222 if(use_ssl
&& ! supports_tls
){
223 printf(_("WARNING - TLS not supported by server\n"));
225 return STATE_WARNING
;
230 /* send the STARTTLS command */
231 send(sd
, SMTP_STARTTLS
, strlen(SMTP_STARTTLS
), 0);
233 recvlines(buffer
, MAX_INPUT_BUFFER
); /* wait for it */
234 if (!strstr (buffer
, server_expect
)) {
235 printf (_("Server does not support STARTTLS\n"));
237 return STATE_UNKNOWN
;
239 result
= np_net_ssl_init(sd
);
240 if(result
!= STATE_OK
) {
241 printf (_("CRITICAL - Cannot create SSL context.\n"));
242 np_net_ssl_cleanup();
244 return STATE_CRITICAL
;
250 * Resend the EHLO command.
252 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
253 * obtained from the server, such as the list of SMTP service
254 * extensions, which was not obtained from the TLS negotiation
255 * itself. The client SHOULD send an EHLO command as the first
256 * command after a successful TLS negotiation.'' For this
257 * reason, some MTAs will not allow an AUTH LOGIN command before
258 * we resent EHLO via TLS.
260 if (my_send(helocmd
, strlen(helocmd
)) <= 0) {
261 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
263 return STATE_UNKNOWN
;
266 printf(_("sent %s"), helocmd
);
267 if ((n
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
268 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
270 return STATE_UNKNOWN
;
273 printf("%s", buffer
);
278 result
= np_net_ssl_check_cert(days_till_exp_warn
, days_till_exp_crit
);
282 # endif /* USE_OPENSSL */
286 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
287 * to do something useful. This can be prevented by giving a command
288 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
290 * According to rfc821 you can include a null reversepath in the from command
291 * - but a log message is generated on the smtp server.
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
)
460 static struct option longopts
[] = {
461 {"hostname", required_argument
, 0, 'H'},
462 {"expect", required_argument
, 0, 'e'},
463 {"critical", required_argument
, 0, 'c'},
464 {"warning", required_argument
, 0, 'w'},
465 {"timeout", required_argument
, 0, 't'},
466 {"port", required_argument
, 0, 'p'},
467 {"from", required_argument
, 0, 'f'},
468 {"fqdn", required_argument
, 0, 'F'},
469 {"authtype", required_argument
, 0, 'A'},
470 {"authuser", required_argument
, 0, 'U'},
471 {"authpass", required_argument
, 0, 'P'},
472 {"command", required_argument
, 0, 'C'},
473 {"response", required_argument
, 0, 'R'},
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'},
481 {"ignore-quit-failure",no_argument
,0,'q'},
488 for (c
= 1; c
< argc
; c
++) {
489 if (strcmp ("-to", argv
[c
]) == 0)
490 strcpy (argv
[c
], "-t");
491 else if (strcmp ("-wt", argv
[c
]) == 0)
492 strcpy (argv
[c
], "-w");
493 else if (strcmp ("-ct", argv
[c
]) == 0)
494 strcpy (argv
[c
], "-c");
498 c
= getopt_long (argc
, argv
, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:q",
501 if (c
== -1 || c
== EOF
)
505 case 'H': /* hostname */
506 if (is_host (optarg
)) {
507 server_address
= optarg
;
510 usage2 (_("Invalid hostname/address"), optarg
);
514 if (is_intpos (optarg
))
515 server_port
= atoi (optarg
);
517 usage4 (_("Port must be a positive integer"));
521 localhostname
= strdup(optarg
);
523 case 'f': /* from argument */
525 smtp_use_dummycmd
= 1;
537 case 'e': /* server expect string on 220 */
538 server_expect
= optarg
;
540 case 'C': /* commands */
541 if (ncommands
>= command_size
) {
543 commands
= realloc (commands
, sizeof(char *) * command_size
);
544 if (commands
== NULL
)
546 _("Could not realloc() units [%d]\n"), ncommands
);
548 commands
[ncommands
] = (char *) malloc (sizeof(char) * 255);
549 strncpy (commands
[ncommands
], optarg
, 255);
552 case 'R': /* server responses */
553 if (nresponses
>= response_size
) {
555 responses
= realloc (responses
, sizeof(char *) * response_size
);
556 if (responses
== NULL
)
558 _("Could not realloc() units [%d]\n"), nresponses
);
560 responses
[nresponses
] = (char *) malloc (sizeof(char) * 255);
561 strncpy (responses
[nresponses
], optarg
, 255);
564 case 'c': /* critical time threshold */
565 if (is_intnonneg (optarg
)) {
566 critical_time
= atoi (optarg
);
567 check_critical_time
= TRUE
;
570 usage4 (_("Critical time must be a positive integer"));
573 case 'w': /* warning time threshold */
574 if (is_intnonneg (optarg
)) {
575 warning_time
= atoi (optarg
);
576 check_warning_time
= TRUE
;
579 usage4 (_("Warning time must be a positive integer"));
582 case 'v': /* verbose */
586 ignore_send_quit_failure
++; /* ignore problem sending QUIT */
588 case 't': /* timeout */
589 if (is_intnonneg (optarg
)) {
590 socket_timeout
= atoi (optarg
);
593 usage4 (_("Timeout interval must be a positive integer"));
602 /* Check SSL cert validity */
604 if ((temp
=strchr(optarg
,','))!=NULL
) {
606 if (!is_intnonneg (temp
))
607 usage2 ("Invalid certificate expiration period", optarg
);
608 days_till_exp_warn
= atoi(optarg
);
611 if (!is_intnonneg (temp
))
612 usage2 (_("Invalid certificate expiration period"), temp
);
613 days_till_exp_crit
= atoi (temp
);
616 days_till_exp_crit
=0;
617 if (!is_intnonneg (optarg
))
618 usage2 ("Invalid certificate expiration period", optarg
);
619 days_till_exp_warn
= atoi (optarg
);
623 usage (_("SSL support not available - install OpenSSL and recompile"));
627 address_family
= AF_INET
;
631 address_family
= AF_INET6
;
633 usage4 (_("IPv6 support not available"));
636 case 'V': /* version */
637 print_revision (progname
, NP_VERSION
);
648 if (server_address
== NULL
) {
650 if (is_host (argv
[c
]))
651 server_address
= argv
[c
];
653 usage2 (_("Invalid hostname/address"), argv
[c
]);
656 asprintf (&server_address
, "127.0.0.1");
660 if (server_expect
== NULL
)
661 server_expect
= strdup (SMTP_EXPECT
);
663 if (mail_command
== NULL
)
664 mail_command
= strdup("MAIL ");
667 from_arg
= strdup(" ");
669 return validate_arguments ();
675 validate_arguments (void)
687 n
= my_send(SMTP_QUIT
, strlen(SMTP_QUIT
));
689 if(ignore_send_quit_failure
) {
691 printf(_("Connection closed by server before sending QUIT command\n"));
696 _("Connection closed by server before sending QUIT command\n"));
700 printf(_("sent %s\n"), "QUIT");
702 /* read the response but don't care about problems */
703 bytes
= recvlines(buffer
, MAX_INPUT_BUFFER
);
706 printf(_("recv() failed after QUIT."));
708 printf(_("Connection reset by peer."));
710 buffer
[bytes
] = '\0';
711 printf(_("received %s\n"), buffer
);
718 * Receive one line, copy it into buf and nul-terminate it. Returns the
719 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
722 * TODO: Reading one byte at a time is very inefficient. Replace this by a
723 * function which buffers the data, move that to netutils.c and change
724 * check_smtp and other plugins to use that. Also, remove (\r)\n.
727 recvline(char *buf
, size_t bufsize
)
732 for (i
= result
= 0; i
< bufsize
- 1; i
++) {
733 if ((result
= my_recv(&buf
[i
], 1)) != 1)
735 if (buf
[i
] == '\n') {
740 return (result
== 1 || i
== 0) ? -2 : result
; /* -2 if out of space */
745 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
746 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
747 * error. Works for all protocols which format multiline replies as follows:
749 * ``The format for multiline replies requires that every line, except the last,
750 * begin with the reply code, followed immediately by a hyphen, `-' (also known
751 * as minus), followed by text. The last line will begin with the reply code,
752 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
753 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
754 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
756 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
759 recvlines(char *buf
, size_t bufsize
)
763 for (i
= 0; /* forever */; i
+= result
)
764 if (!((result
= recvline(buf
+ i
, bufsize
- i
)) > 3 &&
765 isdigit((int)buf
[i
]) &&
766 isdigit((int)buf
[i
+ 1]) &&
767 isdigit((int)buf
[i
+ 2]) &&
771 return (result
<= 0) ? result
: result
+ i
;
779 np_net_ssl_cleanup();
789 asprintf (&myport
, "%d", SMTP_PORT
);
791 print_revision (progname
, NP_VERSION
);
793 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
794 printf (COPYRIGHT
, copyright
, email
);
796 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
802 printf (UT_HELP_VRSN
);
803 printf (UT_EXTRA_OPTS
);
805 printf (UT_HOST_PORT
, 'p', myport
);
809 printf (" %s\n", "-e, --expect=STRING");
810 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT
);
811 printf (" %s\n", "-C, --command=STRING");
812 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
813 printf (" %s\n", "-R, --command=STRING");
814 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
815 printf (" %s\n", "-f, --from=STRING");
816 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
817 printf (" %s\n", "-F, --fqdn=STRING");
818 printf (" %s\n", _("FQDN used for HELO"));
820 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
821 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
822 printf (" %s\n", "-S, --starttls");
823 printf (" %s\n", _("Use STARTTLS for the connection."));
826 printf (" %s\n", "-A, --authtype=STRING");
827 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
828 printf (" %s\n", "-U, --authuser=STRING");
829 printf (" %s\n", _("SMTP AUTH username"));
830 printf (" %s\n", "-P, --authpass=STRING");
831 printf (" %s\n", _("SMTP AUTH password"));
832 printf (" %s\n", "-q, --ignore-quit-failure");
833 printf (" %s\n", _("Ignore failure when sending QUIT command to server"));
835 printf (UT_WARN_CRIT
);
837 printf (UT_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
842 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
843 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
844 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
845 printf ("%s\n", _("STATE_WARNING return values."));
855 printf ("%s\n", _("Usage:"));
856 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-f from addr]", progname
);
857 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
858 printf ("[-F fqdn] [-S] [-D warn days cert expire[,crit days cert expire]] [-v] \n");