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 char *mail_command
= NULL
;
91 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 double warning_time
= 0;
103 int check_warning_time
= FALSE
;
104 double 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 xasprintf (&helocmd
, "%s%s%s", SMTP_EHLO
, localhostname
, "\r\n");
161 xasprintf (&helocmd
, "%s%s%s", SMTP_HELO
, localhostname
, "\r\n");
164 printf("HELOCMD: %s", helocmd
);
166 /* initialize the MAIL command with optional FROM command */
167 xasprintf (&cmd_str
, "%sFROM:<%s>%s", mail_command
, from_arg
, "\r\n");
169 if (verbose
&& send_mail_from
)
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 if (send_mail_from
) {
287 my_send(cmd_str
, strlen(cmd_str
));
288 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
289 printf("%s", buffer
);
292 while (n
< ncommands
) {
293 xasprintf (&cmd_str
, "%s%s", commands
[n
], "\r\n");
294 my_send(cmd_str
, strlen(cmd_str
));
295 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
296 printf("%s", buffer
);
298 if (n
< nresponses
) {
299 cflags
|= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
300 errcode
= regcomp (&preg
, responses
[n
], cflags
);
302 regerror (errcode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
303 printf (_("Could Not Compile Regular Expression"));
306 excode
= regexec (&preg
, buffer
, 10, pmatch
, eflags
);
310 else if (excode
== REG_NOMATCH
) {
311 result
= STATE_WARNING
;
312 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result
), buffer
, commands
[n
]);
315 regerror (excode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
316 printf (_("Execute Error: %s\n"), errbuf
);
317 result
= STATE_UNKNOWN
;
323 if (authtype
!= NULL
) {
324 if (strcmp (authtype
, "LOGIN") == 0) {
328 if (authuser
== NULL
) {
329 result
= STATE_CRITICAL
;
330 xasprintf(&error_msg
, _("no authuser specified, "));
333 if (authpass
== NULL
) {
334 result
= STATE_CRITICAL
;
335 xasprintf(&error_msg
, _("no authpass specified, "));
339 /* send AUTH LOGIN */
340 my_send(SMTP_AUTH_LOGIN
, strlen(SMTP_AUTH_LOGIN
));
342 printf (_("sent %s\n"), "AUTH LOGIN");
344 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
345 xasprintf(&error_msg
, _("recv() failed after AUTH LOGIN, "));
346 result
= STATE_WARNING
;
350 printf (_("received %s\n"), buffer
);
352 if (strncmp (buffer
, "334", 3) != 0) {
353 result
= STATE_CRITICAL
;
354 xasprintf(&error_msg
, _("invalid response received after AUTH LOGIN, "));
358 /* encode authuser with base64 */
359 base64_encode_alloc (authuser
, strlen(authuser
), &abuf
);
360 xasprintf(&abuf
, "%s\r\n", abuf
);
361 my_send(abuf
, strlen(abuf
));
363 printf (_("sent %s\n"), abuf
);
365 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
366 result
= STATE_CRITICAL
;
367 xasprintf(&error_msg
, _("recv() failed after sending authuser, "));
371 printf (_("received %s\n"), buffer
);
373 if (strncmp (buffer
, "334", 3) != 0) {
374 result
= STATE_CRITICAL
;
375 xasprintf(&error_msg
, _("invalid response received after authuser, "));
378 /* encode authpass with base64 */
379 base64_encode_alloc (authpass
, strlen(authpass
), &abuf
);
380 xasprintf(&abuf
, "%s\r\n", abuf
);
381 my_send(abuf
, strlen(abuf
));
383 printf (_("sent %s\n"), abuf
);
385 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
386 result
= STATE_CRITICAL
;
387 xasprintf(&error_msg
, _("recv() failed after sending authpass, "));
391 printf (_("received %s\n"), buffer
);
393 if (strncmp (buffer
, "235", 3) != 0) {
394 result
= STATE_CRITICAL
;
395 xasprintf(&error_msg
, _("invalid response received after authpass, "));
401 result
= STATE_CRITICAL
;
402 xasprintf(&error_msg
, _("only authtype LOGIN is supported, "));
406 /* tell the server we're done */
409 /* finally close the connection */
413 /* reset the alarm */
416 microsec
= deltime (tv
);
417 elapsed_time
= (double)microsec
/ 1.0e6
;
419 if (result
== STATE_OK
) {
420 if (check_critical_time
&& elapsed_time
> critical_time
)
421 result
= STATE_CRITICAL
;
422 else if (check_warning_time
&& elapsed_time
> warning_time
)
423 result
= STATE_WARNING
;
426 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
430 verbose
?", ":"", verbose
?buffer
:"",
431 fperfdata ("time", elapsed_time
, "s",
432 (int)check_warning_time
, warning_time
,
433 (int)check_critical_time
, critical_time
,
441 /* process command-line arguments */
443 process_arguments (int argc
, char **argv
)
449 static struct option longopts
[] = {
450 {"hostname", required_argument
, 0, 'H'},
451 {"expect", required_argument
, 0, 'e'},
452 {"critical", required_argument
, 0, 'c'},
453 {"warning", required_argument
, 0, 'w'},
454 {"timeout", required_argument
, 0, 't'},
455 {"port", required_argument
, 0, 'p'},
456 {"from", required_argument
, 0, 'f'},
457 {"fqdn", required_argument
, 0, 'F'},
458 {"authtype", required_argument
, 0, 'A'},
459 {"authuser", required_argument
, 0, 'U'},
460 {"authpass", required_argument
, 0, 'P'},
461 {"command", required_argument
, 0, 'C'},
462 {"response", required_argument
, 0, 'R'},
463 {"verbose", no_argument
, 0, 'v'},
464 {"version", no_argument
, 0, 'V'},
465 {"use-ipv4", no_argument
, 0, '4'},
466 {"use-ipv6", no_argument
, 0, '6'},
467 {"help", no_argument
, 0, 'h'},
468 {"starttls",no_argument
,0,'S'},
469 {"certificate",required_argument
,0,'D'},
470 {"ignore-quit-failure",no_argument
,0,'q'},
477 for (c
= 1; c
< argc
; c
++) {
478 if (strcmp ("-to", argv
[c
]) == 0)
479 strcpy (argv
[c
], "-t");
480 else if (strcmp ("-wt", argv
[c
]) == 0)
481 strcpy (argv
[c
], "-w");
482 else if (strcmp ("-ct", argv
[c
]) == 0)
483 strcpy (argv
[c
], "-c");
487 c
= getopt_long (argc
, argv
, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:q",
490 if (c
== -1 || c
== EOF
)
494 case 'H': /* hostname */
495 if (is_host (optarg
)) {
496 server_address
= optarg
;
499 usage2 (_("Invalid hostname/address"), optarg
);
503 if (is_intpos (optarg
))
504 server_port
= atoi (optarg
);
506 usage4 (_("Port must be a positive integer"));
510 localhostname
= strdup(optarg
);
512 case 'f': /* from argument */
513 from_arg
= optarg
+ strspn(optarg
, "<");
514 from_arg
= strndup(from_arg
, strcspn(from_arg
, ">"));
527 case 'e': /* server expect string on 220 */
528 server_expect
= optarg
;
530 case 'C': /* commands */
531 if (ncommands
>= command_size
) {
533 commands
= realloc (commands
, sizeof(char *) * command_size
);
534 if (commands
== NULL
)
536 _("Could not realloc() units [%d]\n"), ncommands
);
538 commands
[ncommands
] = (char *) malloc (sizeof(char) * 255);
539 strncpy (commands
[ncommands
], optarg
, 255);
542 case 'R': /* server responses */
543 if (nresponses
>= response_size
) {
545 responses
= realloc (responses
, sizeof(char *) * response_size
);
546 if (responses
== NULL
)
548 _("Could not realloc() units [%d]\n"), nresponses
);
550 responses
[nresponses
] = (char *) malloc (sizeof(char) * 255);
551 strncpy (responses
[nresponses
], optarg
, 255);
554 case 'c': /* critical time threshold */
555 if (!is_nonnegative (optarg
))
556 usage4 (_("Critical time must be a positive"));
558 critical_time
= strtod (optarg
, NULL
);
559 check_critical_time
= TRUE
;
562 case 'w': /* warning time threshold */
563 if (!is_nonnegative (optarg
))
564 usage4 (_("Warning time must be a positive"));
566 warning_time
= strtod (optarg
, NULL
);
567 check_warning_time
= TRUE
;
570 case 'v': /* verbose */
574 ignore_send_quit_failure
++; /* ignore problem sending QUIT */
576 case 't': /* timeout */
577 if (is_intnonneg (optarg
)) {
578 socket_timeout
= atoi (optarg
);
581 usage4 (_("Timeout interval must be a positive integer"));
590 /* Check SSL cert validity */
592 if ((temp
=strchr(optarg
,','))!=NULL
) {
594 if (!is_intnonneg (optarg
))
595 usage2 ("Invalid certificate expiration period", optarg
);
596 days_till_exp_warn
= atoi(optarg
);
599 if (!is_intnonneg (temp
))
600 usage2 (_("Invalid certificate expiration period"), temp
);
601 days_till_exp_crit
= atoi (temp
);
604 days_till_exp_crit
=0;
605 if (!is_intnonneg (optarg
))
606 usage2 ("Invalid certificate expiration period", optarg
);
607 days_till_exp_warn
= atoi (optarg
);
611 usage (_("SSL support not available - install OpenSSL and recompile"));
615 address_family
= AF_INET
;
619 address_family
= AF_INET6
;
621 usage4 (_("IPv6 support not available"));
624 case 'V': /* version */
625 print_revision (progname
, NP_VERSION
);
636 if (server_address
== NULL
) {
638 if (is_host (argv
[c
]))
639 server_address
= argv
[c
];
641 usage2 (_("Invalid hostname/address"), argv
[c
]);
644 xasprintf (&server_address
, "127.0.0.1");
648 if (server_expect
== NULL
)
649 server_expect
= strdup (SMTP_EXPECT
);
651 if (mail_command
== NULL
)
652 mail_command
= strdup("MAIL ");
655 from_arg
= strdup(" ");
657 return validate_arguments ();
663 validate_arguments (void)
675 n
= my_send(SMTP_QUIT
, strlen(SMTP_QUIT
));
677 if(ignore_send_quit_failure
) {
679 printf(_("Connection closed by server before sending QUIT command\n"));
684 _("Connection closed by server before sending QUIT command\n"));
688 printf(_("sent %s\n"), "QUIT");
690 /* read the response but don't care about problems */
691 bytes
= recvlines(buffer
, MAX_INPUT_BUFFER
);
694 printf(_("recv() failed after QUIT."));
696 printf(_("Connection reset by peer."));
698 buffer
[bytes
] = '\0';
699 printf(_("received %s\n"), buffer
);
706 * Receive one line, copy it into buf and nul-terminate it. Returns the
707 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
710 * TODO: Reading one byte at a time is very inefficient. Replace this by a
711 * function which buffers the data, move that to netutils.c and change
712 * check_smtp and other plugins to use that. Also, remove (\r)\n.
715 recvline(char *buf
, size_t bufsize
)
720 for (i
= result
= 0; i
< bufsize
- 1; i
++) {
721 if ((result
= my_recv(&buf
[i
], 1)) != 1)
723 if (buf
[i
] == '\n') {
728 return (result
== 1 || i
== 0) ? -2 : result
; /* -2 if out of space */
733 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
734 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
735 * error. Works for all protocols which format multiline replies as follows:
737 * ``The format for multiline replies requires that every line, except the last,
738 * begin with the reply code, followed immediately by a hyphen, `-' (also known
739 * as minus), followed by text. The last line will begin with the reply code,
740 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
741 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
742 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
744 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
747 recvlines(char *buf
, size_t bufsize
)
751 for (i
= 0; /* forever */; i
+= result
)
752 if (!((result
= recvline(buf
+ i
, bufsize
- i
)) > 3 &&
753 isdigit((int)buf
[i
]) &&
754 isdigit((int)buf
[i
+ 1]) &&
755 isdigit((int)buf
[i
+ 2]) &&
759 return (result
<= 0) ? result
: result
+ i
;
767 np_net_ssl_cleanup();
777 xasprintf (&myport
, "%d", SMTP_PORT
);
779 print_revision (progname
, NP_VERSION
);
781 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
782 printf (COPYRIGHT
, copyright
, email
);
784 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
790 printf (UT_HELP_VRSN
);
791 printf (UT_EXTRA_OPTS
);
793 printf (UT_HOST_PORT
, 'p', myport
);
797 printf (" %s\n", "-e, --expect=STRING");
798 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT
);
799 printf (" %s\n", "-C, --command=STRING");
800 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
801 printf (" %s\n", "-R, --response=STRING");
802 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
803 printf (" %s\n", "-f, --from=STRING");
804 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
805 printf (" %s\n", "-F, --fqdn=STRING");
806 printf (" %s\n", _("FQDN used for HELO"));
808 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
809 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
810 printf (" %s\n", "-S, --starttls");
811 printf (" %s\n", _("Use STARTTLS for the connection."));
814 printf (" %s\n", "-A, --authtype=STRING");
815 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
816 printf (" %s\n", "-U, --authuser=STRING");
817 printf (" %s\n", _("SMTP AUTH username"));
818 printf (" %s\n", "-P, --authpass=STRING");
819 printf (" %s\n", _("SMTP AUTH password"));
820 printf (" %s\n", "-q, --ignore-quit-failure");
821 printf (" %s\n", _("Ignore failure when sending QUIT command to server"));
823 printf (UT_WARN_CRIT
);
825 printf (UT_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
830 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
831 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
832 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
833 printf ("%s\n", _("STATE_WARNING return values."));
843 printf ("%s\n", _("Usage:"));
844 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname
);
845 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
846 printf ("[-F fqdn] [-S] [-D warn days cert expire[,crit days cert expire]] [-v] \n");