1 /*****************************************************************************
3 * Monitoring check_smtp plugin
6 * Copyright (c) 2000-2007 Monitoring 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
= "devel@monitoring-plugins.org";
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
= "";
131 char *server_response
= NULL
;
134 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
135 (void) signal (SIGPIPE
, SIG_IGN
);
137 setlocale (LC_ALL
, "");
138 bindtextdomain (PACKAGE
, LOCALEDIR
);
139 textdomain (PACKAGE
);
141 /* Parse extra opts if any */
142 argv
=np_extra_opts (&argc
, argv
, progname
);
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 xasprintf (&helocmd
, "%s%s%s", SMTP_EHLO
, localhostname
, "\r\n");
162 xasprintf (&helocmd
, "%s%s%s", SMTP_HELO
, localhostname
, "\r\n");
165 printf("HELOCMD: %s", helocmd
);
167 /* initialize the MAIL command with optional FROM command */
168 xasprintf (&cmd_str
, "%sFROM:<%s>%s", mail_command
, from_arg
, "\r\n");
170 if (verbose
&& send_mail_from
)
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 return STATE_WARNING
;
194 /* save connect return (220 hostname ..) for later use */
195 xasprintf(&server_response
, "%s", buffer
);
197 /* send the HELO/EHLO command */
198 send(sd
, helocmd
, strlen(helocmd
), 0);
200 /* allow for response to helo command to reach us */
201 if (recvlines(buffer
, MAX_INPUT_BUFFER
) <= 0) {
202 printf (_("recv() failed\n"));
203 return STATE_WARNING
;
205 if(strstr(buffer
, "250 STARTTLS") != NULL
||
206 strstr(buffer
, "250-STARTTLS") != NULL
){
211 if(use_ssl
&& ! supports_tls
){
212 printf(_("WARNING - TLS not supported by server\n"));
214 return STATE_WARNING
;
219 /* send the STARTTLS command */
220 send(sd
, SMTP_STARTTLS
, strlen(SMTP_STARTTLS
), 0);
222 recvlines(buffer
, MAX_INPUT_BUFFER
); /* wait for it */
223 if (!strstr (buffer
, SMTP_EXPECT
)) {
224 printf (_("Server does not support STARTTLS\n"));
226 return STATE_UNKNOWN
;
228 result
= np_net_ssl_init(sd
);
229 if(result
!= STATE_OK
) {
230 printf (_("CRITICAL - Cannot create SSL context.\n"));
231 np_net_ssl_cleanup();
233 return STATE_CRITICAL
;
239 * Resend the EHLO command.
241 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
242 * obtained from the server, such as the list of SMTP service
243 * extensions, which was not obtained from the TLS negotiation
244 * itself. The client SHOULD send an EHLO command as the first
245 * command after a successful TLS negotiation.'' For this
246 * reason, some MTAs will not allow an AUTH LOGIN command before
247 * we resent EHLO via TLS.
249 if (my_send(helocmd
, strlen(helocmd
)) <= 0) {
250 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
252 return STATE_UNKNOWN
;
255 printf(_("sent %s"), helocmd
);
256 if ((n
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
257 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
259 return STATE_UNKNOWN
;
262 printf("%s", buffer
);
267 result
= np_net_ssl_check_cert(days_till_exp_warn
, days_till_exp_crit
);
272 # endif /* USE_OPENSSL */
277 printf ("%s", buffer
);
279 /* save buffer for later use */
280 xasprintf(&server_response
, "%s%s", server_response
, buffer
);
281 /* strip the buffer of carriage returns */
282 strip (server_response
);
284 /* make sure we find the droids we are looking for */
285 if (!strstr (server_response
, server_expect
)) {
286 if (server_port
== SMTP_PORT
)
287 printf (_("Invalid SMTP response received from host: %s\n"), server_response
);
289 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
290 server_port
, server_response
);
291 return STATE_WARNING
;
294 if (send_mail_from
) {
295 my_send(cmd_str
, strlen(cmd_str
));
296 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
297 printf("%s", buffer
);
300 while (n
< ncommands
) {
301 xasprintf (&cmd_str
, "%s%s", commands
[n
], "\r\n");
302 my_send(cmd_str
, strlen(cmd_str
));
303 if (recvlines(buffer
, MAX_INPUT_BUFFER
) >= 1 && verbose
)
304 printf("%s", buffer
);
306 if (n
< nresponses
) {
307 cflags
|= REG_EXTENDED
| REG_NOSUB
| REG_NEWLINE
;
308 errcode
= regcomp (&preg
, responses
[n
], cflags
);
310 regerror (errcode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
311 printf (_("Could Not Compile Regular Expression"));
314 excode
= regexec (&preg
, buffer
, 10, pmatch
, eflags
);
318 else if (excode
== REG_NOMATCH
) {
319 result
= STATE_WARNING
;
320 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result
), buffer
, commands
[n
]);
323 regerror (excode
, &preg
, errbuf
, MAX_INPUT_BUFFER
);
324 printf (_("Execute Error: %s\n"), errbuf
);
325 result
= STATE_UNKNOWN
;
331 if (authtype
!= NULL
) {
332 if (strcmp (authtype
, "LOGIN") == 0) {
336 if (authuser
== NULL
) {
337 result
= STATE_CRITICAL
;
338 xasprintf(&error_msg
, _("no authuser specified, "));
341 if (authpass
== NULL
) {
342 result
= STATE_CRITICAL
;
343 xasprintf(&error_msg
, _("no authpass specified, "));
347 /* send AUTH LOGIN */
348 my_send(SMTP_AUTH_LOGIN
, strlen(SMTP_AUTH_LOGIN
));
350 printf (_("sent %s\n"), "AUTH LOGIN");
352 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
353 xasprintf(&error_msg
, _("recv() failed after AUTH LOGIN, "));
354 result
= STATE_WARNING
;
358 printf (_("received %s\n"), buffer
);
360 if (strncmp (buffer
, "334", 3) != 0) {
361 result
= STATE_CRITICAL
;
362 xasprintf(&error_msg
, _("invalid response received after AUTH LOGIN, "));
366 /* encode authuser with base64 */
367 base64_encode_alloc (authuser
, strlen(authuser
), &abuf
);
368 xasprintf(&abuf
, "%s\r\n", abuf
);
369 my_send(abuf
, strlen(abuf
));
371 printf (_("sent %s\n"), abuf
);
373 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
374 result
= STATE_CRITICAL
;
375 xasprintf(&error_msg
, _("recv() failed after sending authuser, "));
379 printf (_("received %s\n"), buffer
);
381 if (strncmp (buffer
, "334", 3) != 0) {
382 result
= STATE_CRITICAL
;
383 xasprintf(&error_msg
, _("invalid response received after authuser, "));
386 /* encode authpass with base64 */
387 base64_encode_alloc (authpass
, strlen(authpass
), &abuf
);
388 xasprintf(&abuf
, "%s\r\n", abuf
);
389 my_send(abuf
, strlen(abuf
));
391 printf (_("sent %s\n"), abuf
);
393 if ((ret
= recvlines(buffer
, MAX_INPUT_BUFFER
)) <= 0) {
394 result
= STATE_CRITICAL
;
395 xasprintf(&error_msg
, _("recv() failed after sending authpass, "));
399 printf (_("received %s\n"), buffer
);
401 if (strncmp (buffer
, "235", 3) != 0) {
402 result
= STATE_CRITICAL
;
403 xasprintf(&error_msg
, _("invalid response received after authpass, "));
409 result
= STATE_CRITICAL
;
410 xasprintf(&error_msg
, _("only authtype LOGIN is supported, "));
414 /* tell the server we're done */
417 /* finally close the connection */
421 /* reset the alarm */
424 microsec
= deltime (tv
);
425 elapsed_time
= (double)microsec
/ 1.0e6
;
427 if (result
== STATE_OK
) {
428 if (check_critical_time
&& elapsed_time
> critical_time
)
429 result
= STATE_CRITICAL
;
430 else if (check_warning_time
&& elapsed_time
> warning_time
)
431 result
= STATE_WARNING
;
434 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
438 verbose
?", ":"", verbose
?buffer
:"",
439 fperfdata ("time", elapsed_time
, "s",
440 (int)check_warning_time
, warning_time
,
441 (int)check_critical_time
, critical_time
,
449 /* process command-line arguments */
451 process_arguments (int argc
, char **argv
)
457 static struct option longopts
[] = {
458 {"hostname", required_argument
, 0, 'H'},
459 {"expect", required_argument
, 0, 'e'},
460 {"critical", required_argument
, 0, 'c'},
461 {"warning", required_argument
, 0, 'w'},
462 {"timeout", required_argument
, 0, 't'},
463 {"port", required_argument
, 0, 'p'},
464 {"from", required_argument
, 0, 'f'},
465 {"fqdn", required_argument
, 0, 'F'},
466 {"authtype", required_argument
, 0, 'A'},
467 {"authuser", required_argument
, 0, 'U'},
468 {"authpass", required_argument
, 0, 'P'},
469 {"command", required_argument
, 0, 'C'},
470 {"response", required_argument
, 0, 'R'},
471 {"verbose", no_argument
, 0, 'v'},
472 {"version", no_argument
, 0, 'V'},
473 {"use-ipv4", no_argument
, 0, '4'},
474 {"use-ipv6", no_argument
, 0, '6'},
475 {"help", no_argument
, 0, 'h'},
476 {"starttls",no_argument
,0,'S'},
477 {"certificate",required_argument
,0,'D'},
478 {"ignore-quit-failure",no_argument
,0,'q'},
485 for (c
= 1; c
< argc
; c
++) {
486 if (strcmp ("-to", argv
[c
]) == 0)
487 strcpy (argv
[c
], "-t");
488 else if (strcmp ("-wt", argv
[c
]) == 0)
489 strcpy (argv
[c
], "-w");
490 else if (strcmp ("-ct", argv
[c
]) == 0)
491 strcpy (argv
[c
], "-c");
495 c
= getopt_long (argc
, argv
, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:q",
498 if (c
== -1 || c
== EOF
)
502 case 'H': /* hostname */
503 if (is_host (optarg
)) {
504 server_address
= optarg
;
507 usage2 (_("Invalid hostname/address"), optarg
);
511 if (is_intpos (optarg
))
512 server_port
= atoi (optarg
);
514 usage4 (_("Port must be a positive integer"));
518 localhostname
= strdup(optarg
);
520 case 'f': /* from argument */
521 from_arg
= optarg
+ strspn(optarg
, "<");
522 from_arg
= strndup(from_arg
, strcspn(from_arg
, ">"));
535 case 'e': /* server expect string on 220 */
536 server_expect
= optarg
;
538 case 'C': /* commands */
539 if (ncommands
>= command_size
) {
541 commands
= realloc (commands
, sizeof(char *) * command_size
);
542 if (commands
== NULL
)
544 _("Could not realloc() units [%d]\n"), ncommands
);
546 commands
[ncommands
] = (char *) malloc (sizeof(char) * 255);
547 strncpy (commands
[ncommands
], optarg
, 255);
550 case 'R': /* server responses */
551 if (nresponses
>= response_size
) {
553 responses
= realloc (responses
, sizeof(char *) * response_size
);
554 if (responses
== NULL
)
556 _("Could not realloc() units [%d]\n"), nresponses
);
558 responses
[nresponses
] = (char *) malloc (sizeof(char) * 255);
559 strncpy (responses
[nresponses
], optarg
, 255);
562 case 'c': /* critical time threshold */
563 if (!is_nonnegative (optarg
))
564 usage4 (_("Critical time must be a positive"));
566 critical_time
= strtod (optarg
, NULL
);
567 check_critical_time
= TRUE
;
570 case 'w': /* warning time threshold */
571 if (!is_nonnegative (optarg
))
572 usage4 (_("Warning time must be a positive"));
574 warning_time
= strtod (optarg
, NULL
);
575 check_warning_time
= TRUE
;
578 case 'v': /* verbose */
582 ignore_send_quit_failure
++; /* ignore problem sending QUIT */
584 case 't': /* timeout */
585 if (is_intnonneg (optarg
)) {
586 socket_timeout
= atoi (optarg
);
589 usage4 (_("Timeout interval must be a positive integer"));
593 /* Check SSL cert validity */
595 if ((temp
=strchr(optarg
,','))!=NULL
) {
597 if (!is_intnonneg (optarg
))
598 usage2 ("Invalid certificate expiration period", optarg
);
599 days_till_exp_warn
= atoi(optarg
);
602 if (!is_intnonneg (temp
))
603 usage2 (_("Invalid certificate expiration period"), temp
);
604 days_till_exp_crit
= atoi (temp
);
607 days_till_exp_crit
=0;
608 if (!is_intnonneg (optarg
))
609 usage2 ("Invalid certificate expiration period", optarg
);
610 days_till_exp_warn
= atoi (optarg
);
613 ignore_send_quit_failure
= TRUE
;
615 usage (_("SSL support not available - install OpenSSL and recompile"));
623 address_family
= AF_INET
;
627 address_family
= AF_INET6
;
629 usage4 (_("IPv6 support not available"));
632 case 'V': /* version */
633 print_revision (progname
, NP_VERSION
);
634 exit (STATE_UNKNOWN
);
637 exit (STATE_UNKNOWN
);
644 if (server_address
== NULL
) {
646 if (is_host (argv
[c
]))
647 server_address
= argv
[c
];
649 usage2 (_("Invalid hostname/address"), argv
[c
]);
652 xasprintf (&server_address
, "127.0.0.1");
656 if (server_expect
== NULL
)
657 server_expect
= strdup (SMTP_EXPECT
);
659 if (mail_command
== NULL
)
660 mail_command
= strdup("MAIL ");
663 from_arg
= strdup(" ");
665 return validate_arguments ();
671 validate_arguments (void)
683 n
= my_send(SMTP_QUIT
, strlen(SMTP_QUIT
));
685 if(ignore_send_quit_failure
) {
687 printf(_("Connection closed by server before sending QUIT command\n"));
692 _("Connection closed by server before sending QUIT command\n"));
696 printf(_("sent %s\n"), "QUIT");
698 /* read the response but don't care about problems */
699 bytes
= recvlines(buffer
, MAX_INPUT_BUFFER
);
702 printf(_("recv() failed after QUIT."));
704 printf(_("Connection reset by peer."));
706 buffer
[bytes
] = '\0';
707 printf(_("received %s\n"), buffer
);
714 * Receive one line, copy it into buf and nul-terminate it. Returns the
715 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
718 * TODO: Reading one byte at a time is very inefficient. Replace this by a
719 * function which buffers the data, move that to netutils.c and change
720 * check_smtp and other plugins to use that. Also, remove (\r)\n.
723 recvline(char *buf
, size_t bufsize
)
728 for (i
= result
= 0; i
< bufsize
- 1; i
++) {
729 if ((result
= my_recv(&buf
[i
], 1)) != 1)
731 if (buf
[i
] == '\n') {
736 return (result
== 1 || i
== 0) ? -2 : result
; /* -2 if out of space */
741 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
742 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
743 * error. Works for all protocols which format multiline replies as follows:
745 * ``The format for multiline replies requires that every line, except the last,
746 * begin with the reply code, followed immediately by a hyphen, `-' (also known
747 * as minus), followed by text. The last line will begin with the reply code,
748 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
749 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
750 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
752 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
755 recvlines(char *buf
, size_t bufsize
)
759 for (i
= 0; /* forever */; i
+= result
)
760 if (!((result
= recvline(buf
+ i
, bufsize
- i
)) > 3 &&
761 isdigit((int)buf
[i
]) &&
762 isdigit((int)buf
[i
+ 1]) &&
763 isdigit((int)buf
[i
+ 2]) &&
767 return (result
<= 0) ? result
: result
+ i
;
775 np_net_ssl_cleanup();
785 xasprintf (&myport
, "%d", SMTP_PORT
);
787 print_revision (progname
, NP_VERSION
);
789 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
790 printf (COPYRIGHT
, copyright
, email
);
792 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
798 printf (UT_HELP_VRSN
);
799 printf (UT_EXTRA_OPTS
);
801 printf (UT_HOST_PORT
, 'p', myport
);
805 printf (" %s\n", "-e, --expect=STRING");
806 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT
);
807 printf (" %s\n", "-C, --command=STRING");
808 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
809 printf (" %s\n", "-R, --response=STRING");
810 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
811 printf (" %s\n", "-f, --from=STRING");
812 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
813 printf (" %s\n", "-F, --fqdn=STRING");
814 printf (" %s\n", _("FQDN used for HELO"));
816 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
817 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
818 printf (" %s\n", "-S, --starttls");
819 printf (" %s\n", _("Use STARTTLS for the connection."));
822 printf (" %s\n", "-A, --authtype=STRING");
823 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
824 printf (" %s\n", "-U, --authuser=STRING");
825 printf (" %s\n", _("SMTP AUTH username"));
826 printf (" %s\n", "-P, --authpass=STRING");
827 printf (" %s\n", _("SMTP AUTH password"));
828 printf (" %s\n", "-q, --ignore-quit-failure");
829 printf (" %s\n", _("Ignore failure when sending QUIT command to server"));
831 printf (UT_WARN_CRIT
);
833 printf (UT_CONN_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
838 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
839 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
840 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
841 printf ("%s\n", _("STATE_WARNING return values."));
851 printf ("%s\n", _("Usage:"));
852 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname
);
853 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
854 printf ("[-F fqdn] [-S] [-D warn days cert expire[,crit days cert expire]] [-v] \n");