summaryrefslogtreecommitdiffstats
path: root/plugins/check_smtp.c
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_smtp.c')
-rw-r--r--plugins/check_smtp.c1456
1 files changed, 798 insertions, 658 deletions
diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c
index 986c3e18..e1f2842e 100644
--- a/plugins/check_smtp.c
+++ b/plugins/check_smtp.c
@@ -1,265 +1,316 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring check_smtp plugin 3 * Monitoring check_smtp plugin
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2000-2023 Monitoring Plugins Development Team 6 * Copyright (c) 2000-2024 Monitoring Plugins Development Team
7* 7 *
8* Description: 8 * Description:
9* 9 *
10* This file contains the check_smtp plugin 10 * This file contains the check_smtp plugin
11* 11 *
12* This plugin will attempt to open an SMTP connection with the host. 12 * This plugin will attempt to open an SMTP connection with the host.
13* 13 *
14* 14 *
15* This program is free software: you can redistribute it and/or modify 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 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 17 * the Free Software Foundation, either version 3 of the License, or
18* (at your option) any later version. 18 * (at your option) any later version.
19* 19 *
20* This program is distributed in the hope that it will be useful, 20 * This program is distributed in the hope that it will be useful,
21* but WITHOUT ANY WARRANTY; without even the implied warranty of 21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23* GNU General Public License for more details. 23 * GNU General Public License for more details.
24* 24 *
25* You should have received a copy of the GNU General Public License 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/>. 26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27* 27 *
28* 28 *
29*****************************************************************************/ 29 *****************************************************************************/
30
31const char *progname = "check_smtp";
32const char *copyright = "2000-2007";
33const char *email = "devel@monitoring-plugins.org";
34 30
35#include "common.h" 31#include "common.h"
36#include "netutils.h" 32#include "netutils.h"
33#include "output.h"
34#include "perfdata.h"
35#include "thresholds.h"
37#include "utils.h" 36#include "utils.h"
38#include "base64.h" 37#include "base64.h"
38#include "regex.h"
39 39
40#include <ctype.h> 40#include <ctype.h>
41#include <string.h>
42#include "check_smtp.d/config.h"
43#include "../lib/states.h"
41 44
42#ifdef HAVE_SSL 45const char *progname = "check_smtp";
43bool check_cert = false; 46const char *copyright = "2000-2024";
44int days_till_exp_warn, days_till_exp_crit; 47const char *email = "devel@monitoring-plugins.org";
45# define my_recv(buf, len) (((use_starttls || use_ssl) && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
46# define my_send(buf, len) (((use_starttls || 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)
50#endif
51 48
52enum { 49#define PROXY_PREFIX "PROXY TCP4 0.0.0.0 0.0.0.0 25 25\r\n"
53 SMTP_PORT = 25, 50#define SMTP_HELO "HELO "
54 SMTPS_PORT = 465 51#define SMTP_EHLO "EHLO "
55}; 52#define SMTP_LHLO "LHLO "
56#define PROXY_PREFIX "PROXY TCP4 0.0.0.0 0.0.0.0 25 25\r\n" 53#define SMTP_QUIT "QUIT\r\n"
57#define SMTP_EXPECT "220" 54#define SMTP_STARTTLS "STARTTLS\r\n"
58#define SMTP_HELO "HELO "
59#define SMTP_EHLO "EHLO "
60#define SMTP_LHLO "LHLO "
61#define SMTP_QUIT "QUIT\r\n"
62#define SMTP_STARTTLS "STARTTLS\r\n"
63#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n" 55#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
64 56
65#define EHLO_SUPPORTS_STARTTLS 1 57#define EHLO_SUPPORTS_STARTTLS 1
66 58
67int process_arguments (int, char **); 59typedef struct {
68int validate_arguments (void); 60 int errorcode;
69void print_help (void); 61 check_smtp_config config;
70void print_usage (void); 62} check_smtp_config_wrapper;
71void smtp_quit(void); 63static check_smtp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
72int recvline(char *, size_t);
73int recvlines(char *, size_t);
74int my_close(void);
75 64
76#include "regex.h" 65int my_recv(check_smtp_config config, void *buf, int num, int socket_descriptor,
77char regex_expect[MAX_INPUT_BUFFER] = ""; 66 bool ssl_established) {
78regex_t preg; 67#ifdef HAVE_SSL
79regmatch_t pmatch[10]; 68 if ((config.use_starttls || config.use_ssl) && ssl_established) {
80char timestamp[20] = ""; 69 return np_net_ssl_read(buf, num);
81char errbuf[MAX_INPUT_BUFFER]; 70 }
82int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE; 71 return (int)read(socket_descriptor, buf, (size_t)num);
83int eflags = 0; 72#else /* ifndef HAVE_SSL */
84int errcode, excode; 73 return read(socket_descriptor, buf, len)
85 74#endif
86int server_port = SMTP_PORT; 75}
87int server_port_option = 0;
88char *server_address = NULL;
89char *server_expect = NULL;
90char *mail_command = NULL;
91char *from_arg = NULL;
92int send_mail_from=0;
93int ncommands=0;
94int command_size=0;
95int nresponses=0;
96int response_size=0;
97char **commands = NULL;
98char **responses = NULL;
99char *authtype = NULL;
100char *authuser = NULL;
101char *authpass = NULL;
102double warning_time = 0;
103bool check_warning_time = false;
104double critical_time = 0;
105bool check_critical_time = false;
106int verbose = 0;
107bool use_ssl = false;
108bool use_starttls = false;
109bool use_sni = false;
110bool use_proxy_prefix = false;
111bool use_ehlo = false;
112bool use_lhlo = false;
113bool ssl_established = false;
114char *localhostname = NULL;
115int sd;
116char buffer[MAX_INPUT_BUFFER];
117enum {
118 TCP_PROTOCOL = 1,
119 UDP_PROTOCOL = 2,
120};
121bool ignore_send_quit_failure = false;
122
123
124int
125main (int argc, char **argv)
126{
127 bool supports_tls = false;
128 int n = 0;
129 double elapsed_time;
130 long microsec;
131 int result = STATE_UNKNOWN;
132 char *cmd_str = NULL;
133 char *helocmd = NULL;
134 char *error_msg = "";
135 char *server_response = NULL;
136 struct timeval tv;
137 76
138 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ 77int my_send(check_smtp_config config, void *buf, int num, int socket_descriptor,
139 (void) signal (SIGPIPE, SIG_IGN); 78 bool ssl_established) {
79#ifdef HAVE_SSL
80 if ((config.use_starttls || config.use_ssl) && ssl_established) {
81
82 return np_net_ssl_write(buf, num);
83 }
84 return (int)send(socket_descriptor, buf, (size_t)num, 0);
85#else /* ifndef HAVE_SSL */
86 return send(socket_descriptor, buf, len, 0);
87#endif
88}
140 89
141 setlocale (LC_ALL, ""); 90static void print_help(void);
142 bindtextdomain (PACKAGE, LOCALEDIR); 91void print_usage(void);
143 textdomain (PACKAGE); 92static char *smtp_quit(check_smtp_config /*config*/, char /*buffer*/[MAX_INPUT_BUFFER],
93 int /*socket_descriptor*/, bool /*ssl_established*/);
94static int recvline(char * /*buf*/, size_t /*bufsize*/, check_smtp_config /*config*/,
95 int /*socket_descriptor*/, bool /*ssl_established*/);
96static int recvlines(check_smtp_config /*config*/, char * /*buf*/, size_t /*bufsize*/,
97 int /*socket_descriptor*/, bool /*ssl_established*/);
98static int my_close(int /*socket_descriptor*/);
99
100static int verbose = 0;
101
102int main(int argc, char **argv) {
103#ifdef __OpenBSD__
104 /* - rpath is required to read --extra-opts (given up later)
105 * - inet is required for sockets
106 * - unix is required for Unix domain sockets
107 * - dns is required for name lookups */
108 pledge("stdio rpath inet unix dns", NULL);
109#endif // __OpenBSD__
110
111 setlocale(LC_ALL, "");
112 bindtextdomain(PACKAGE, LOCALEDIR);
113 textdomain(PACKAGE);
144 114
145 /* Parse extra opts if any */ 115 /* Parse extra opts if any */
146 argv=np_extra_opts (&argc, argv, progname); 116 argv = np_extra_opts(&argc, argv, progname);
147 117
148 if (process_arguments (argc, argv) == ERROR) 118 check_smtp_config_wrapper tmp_config = process_arguments(argc, argv);
149 usage4 (_("Could not parse arguments")); 119
120 if (tmp_config.errorcode == ERROR) {
121 usage4(_("Could not parse arguments"));
122 }
123
124#ifdef __OpenBSD__
125 pledge("stdio inet unix dns", NULL);
126#endif // __OpenBSD__
127
128 const check_smtp_config config = tmp_config.config;
129
130 if (config.output_format_is_set) {
131 mp_set_format(config.output_format);
132 }
150 133
151 /* If localhostname not set on command line, use gethostname to set */ 134 /* If localhostname not set on command line, use gethostname to set */
152 if(! localhostname){ 135 char *localhostname = config.localhostname;
153 localhostname = malloc (HOST_MAX_BYTES); 136 if (!localhostname) {
154 if(!localhostname){ 137 localhostname = malloc(HOST_MAX_BYTES);
138 if (!localhostname) {
155 printf(_("malloc() failed!\n")); 139 printf(_("malloc() failed!\n"));
156 return STATE_CRITICAL; 140 exit(STATE_CRITICAL);
157 } 141 }
158 if(gethostname(localhostname, HOST_MAX_BYTES)){ 142 if (gethostname(localhostname, HOST_MAX_BYTES)) {
159 printf(_("gethostname() failed!\n")); 143 printf(_("gethostname() failed!\n"));
160 return STATE_CRITICAL; 144 exit(STATE_CRITICAL);
161 } 145 }
162 } 146 }
163 if(use_lhlo)
164 xasprintf (&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
165 else if(use_ehlo)
166 xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
167 else
168 xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
169 147
170 if (verbose) 148 char *helocmd = NULL;
149 if (config.use_lhlo) {
150 xasprintf(&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
151 } else if (config.use_ehlo) {
152 xasprintf(&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
153 } else {
154 xasprintf(&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
155 }
156
157 if (verbose) {
171 printf("HELOCMD: %s", helocmd); 158 printf("HELOCMD: %s", helocmd);
159 }
172 160
161 char *mail_command = strdup("MAIL ");
162 char *cmd_str = NULL;
173 /* initialize the MAIL command with optional FROM command */ 163 /* initialize the MAIL command with optional FROM command */
174 xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); 164 xasprintf(&cmd_str, "%sFROM:<%s>%s", mail_command, config.from_arg, "\r\n");
175 165
176 if (verbose && send_mail_from) 166 if (verbose && config.send_mail_from) {
177 printf ("FROM CMD: %s", cmd_str); 167 printf("FROM CMD: %s", cmd_str);
168 }
169
170 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
171 (void)signal(SIGPIPE, SIG_IGN);
178 172
179 /* initialize alarm signal handling */ 173 /* initialize alarm signal handling */
180 (void) signal (SIGALRM, socket_timeout_alarm_handler); 174 (void)signal(SIGALRM, socket_timeout_alarm_handler);
181 175
182 /* set socket timeout */ 176 /* set socket timeout */
183 (void) alarm (socket_timeout); 177 (void)alarm(socket_timeout);
184 178
179 struct timeval start_time;
185 /* start timer */ 180 /* start timer */
186 gettimeofday (&tv, NULL); 181 gettimeofday(&start_time, NULL);
182
183 int socket_descriptor = 0;
187 184
188 /* try to connect to the host at the given port number */ 185 /* try to connect to the host at the given port number */
189 result = my_tcp_connect (server_address, server_port, &sd); 186 mp_state_enum tcp_result =
190 187 my_tcp_connect(config.server_address, config.server_port, &socket_descriptor);
191 if (result == STATE_OK) { /* we connected */ 188
192 /* If requested, send PROXY header */ 189 mp_check overall = mp_check_init();
193 if (use_proxy_prefix) { 190
194 if (verbose) 191 mp_set_ok_summary(&overall, "SMTP connection check is OK");
195 printf ("Sending header %s\n", PROXY_PREFIX); 192
196 my_send(PROXY_PREFIX, strlen(PROXY_PREFIX)); 193 mp_subcheck sc_tcp_connect = mp_subcheck_init();
194 char buffer[MAX_INPUT_BUFFER];
195 bool ssl_established = false;
196
197 if (tcp_result != STATE_OK) {
198 // Connect failed
199 sc_tcp_connect = mp_set_subcheck_state(sc_tcp_connect, STATE_CRITICAL);
200 xasprintf(&sc_tcp_connect.output, "TCP connect to '%s' failed", config.server_address);
201 mp_add_subcheck_to_check(&overall, sc_tcp_connect);
202 mp_exit(overall);
203 }
204
205 /* we connected */
206 /* If requested, send PROXY header */
207 if (config.use_proxy_prefix) {
208 if (verbose) {
209 printf("Sending header %s\n", PROXY_PREFIX);
197 } 210 }
211 my_send(config, PROXY_PREFIX, strlen(PROXY_PREFIX), socket_descriptor, ssl_established);
212 }
198 213
199#ifdef HAVE_SSL 214#ifdef HAVE_SSL
200 if (use_ssl) { 215 if (config.use_ssl) {
201 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL)); 216 int tls_result = np_net_ssl_init_with_hostname(
202 if (result != STATE_OK) { 217 socket_descriptor, (config.use_sni ? config.server_address : NULL));
203 printf (_("CRITICAL - Cannot create SSL context.\n")); 218
204 close(sd); 219 mp_subcheck sc_tls_connection = mp_subcheck_init();
205 np_net_ssl_cleanup(); 220
206 return STATE_CRITICAL; 221 if (tls_result != STATE_OK) {
207 } else { 222 close(socket_descriptor);
208 ssl_established = 1; 223 np_net_ssl_cleanup();
209 } 224
225 sc_tls_connection = mp_set_subcheck_state(sc_tls_connection, STATE_CRITICAL);
226 xasprintf(&sc_tls_connection.output, "cannot create TLS context");
227 mp_add_subcheck_to_check(&overall, sc_tls_connection);
228 mp_exit(overall);
210 } 229 }
230
231 sc_tls_connection = mp_set_subcheck_state(sc_tls_connection, STATE_OK);
232 xasprintf(&sc_tls_connection.output, "TLS context established");
233 mp_add_subcheck_to_check(&overall, sc_tls_connection);
234 ssl_established = true;
235 }
211#endif 236#endif
212 237
213 /* watch for the SMTP connection string and */ 238 /* watch for the SMTP connection string and */
214 /* return a WARNING status if we couldn't read any data */ 239 /* return a WARNING status if we couldn't read any data */
215 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { 240 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
216 printf (_("recv() failed\n")); 241 mp_subcheck sc_read_data = mp_subcheck_init();
217 return STATE_WARNING; 242 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
243 xasprintf(&sc_read_data.output, "recv() failed");
244 mp_add_subcheck_to_check(&overall, sc_read_data);
245 mp_exit(overall);
246 }
247
248 char *server_response = NULL;
249 /* save connect return (220 hostname ..) for later use */
250 xasprintf(&server_response, "%s", buffer);
251
252 /* send the HELO/EHLO command */
253 my_send(config, helocmd, (int)strlen(helocmd), socket_descriptor, ssl_established);
254
255 /* allow for response to helo command to reach us */
256 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
257 mp_subcheck sc_read_data = mp_subcheck_init();
258 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
259 xasprintf(&sc_read_data.output, "recv() failed");
260 mp_add_subcheck_to_check(&overall, sc_read_data);
261 mp_exit(overall);
262 }
263
264 bool supports_tls = false;
265 if (config.use_ehlo || config.use_lhlo) {
266 if (strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL) {
267 supports_tls = true;
218 } 268 }
269 }
219 270
220 /* save connect return (220 hostname ..) for later use */ 271 if (config.use_starttls && !supports_tls) {
221 xasprintf(&server_response, "%s", buffer); 272 smtp_quit(config, buffer, socket_descriptor, ssl_established);
222 273
223 /* send the HELO/EHLO command */ 274 mp_subcheck sc_read_data = mp_subcheck_init();
224 my_send(helocmd, strlen(helocmd)); 275 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
276 xasprintf(&sc_read_data.output, "StartTLS not supported by server");
277 mp_add_subcheck_to_check(&overall, sc_read_data);
278 mp_exit(overall);
279 }
225 280
226 /* allow for response to helo command to reach us */ 281#ifdef HAVE_SSL
227 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { 282 if (config.use_starttls) {
228 printf (_("recv() failed\n")); 283 /* send the STARTTLS command */
229 return STATE_WARNING; 284 send(socket_descriptor, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
230 } else if(use_ehlo || use_lhlo){ 285
231 if(strstr(buffer, "250 STARTTLS") != NULL || 286 mp_subcheck sc_starttls_init = mp_subcheck_init();
232 strstr(buffer, "250-STARTTLS") != NULL){ 287 recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
233 supports_tls=true; 288 ssl_established); /* wait for it */
234 } 289 if (!strstr(buffer, SMTP_EXPECT)) {
290 smtp_quit(config, buffer, socket_descriptor, ssl_established);
291
292 xasprintf(&sc_starttls_init.output, "StartTLS not supported by server");
293 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_UNKNOWN);
294 mp_add_subcheck_to_check(&overall, sc_starttls_init);
295 mp_exit(overall);
235 } 296 }
236 297
237 if(use_starttls && ! supports_tls){ 298 mp_state_enum starttls_result = np_net_ssl_init_with_hostname(
238 printf(_("WARNING - TLS not supported by server\n")); 299 socket_descriptor, (config.use_sni ? config.server_address : NULL));
239 smtp_quit(); 300 if (starttls_result != STATE_OK) {
240 return STATE_WARNING; 301 close(socket_descriptor);
302 np_net_ssl_cleanup();
303
304 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_CRITICAL);
305 xasprintf(&sc_starttls_init.output, "failed to create StartTLS context");
306 mp_add_subcheck_to_check(&overall, sc_starttls_init);
307 mp_exit(overall);
241 } 308 }
309 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_OK);
310 xasprintf(&sc_starttls_init.output, "created StartTLS context");
311 mp_add_subcheck_to_check(&overall, sc_starttls_init);
242 312
243#ifdef HAVE_SSL 313 ssl_established = true;
244 if(use_starttls) {
245 /* send the STARTTLS command */
246 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
247
248 recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
249 if (!strstr (buffer, SMTP_EXPECT)) {
250 printf (_("Server does not support STARTTLS\n"));
251 smtp_quit();
252 return STATE_UNKNOWN;
253 }
254 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL));
255 if(result != STATE_OK) {
256 printf (_("CRITICAL - Cannot create SSL context.\n"));
257 close(sd);
258 np_net_ssl_cleanup();
259 return STATE_CRITICAL;
260 } else {
261 ssl_established = 1;
262 }
263 314
264 /* 315 /*
265 * Resend the EHLO command. 316 * Resend the EHLO command.
@@ -272,218 +323,287 @@ main (int argc, char **argv)
272 * reason, some MTAs will not allow an AUTH LOGIN command before 323 * reason, some MTAs will not allow an AUTH LOGIN command before
273 * we resent EHLO via TLS. 324 * we resent EHLO via TLS.
274 */ 325 */
275 if (my_send(helocmd, strlen(helocmd)) <= 0) { 326 if (my_send(config, helocmd, (int)strlen(helocmd), socket_descriptor, ssl_established) <=
276 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); 327 0) {
277 my_close(); 328 my_close(socket_descriptor);
278 return STATE_UNKNOWN; 329
330 mp_subcheck sc_ehlo = mp_subcheck_init();
331 sc_ehlo = mp_set_subcheck_state(sc_ehlo, STATE_UNKNOWN);
332 xasprintf(&sc_ehlo.output, "cannot send EHLO command via StartTLS");
333 mp_add_subcheck_to_check(&overall, sc_ehlo);
334 mp_exit(overall);
279 } 335 }
280 if (verbose) 336
337 if (verbose) {
281 printf(_("sent %s"), helocmd); 338 printf(_("sent %s"), helocmd);
282 if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
283 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
284 my_close();
285 return STATE_UNKNOWN;
286 } 339 }
340
341 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
342 my_close(socket_descriptor);
343
344 mp_subcheck sc_ehlo = mp_subcheck_init();
345 sc_ehlo = mp_set_subcheck_state(sc_ehlo, STATE_UNKNOWN);
346 xasprintf(&sc_ehlo.output, "cannot read EHLO response via StartTLS");
347 mp_add_subcheck_to_check(&overall, sc_ehlo);
348 mp_exit(overall);
349 }
350
287 if (verbose) { 351 if (verbose) {
288 printf("%s", buffer); 352 printf("%s", buffer);
289 } 353 }
354 }
355
356# ifdef MOPL_USE_OPENSSL
357 if (ssl_established) {
358 net_ssl_check_cert_result cert_check_result =
359 np_net_ssl_check_cert2(config.days_till_exp_warn, config.days_till_exp_crit);
360
361 mp_subcheck sc_cert_check = mp_subcheck_init();
362
363 switch (cert_check_result.errors) {
364 case ALL_OK: {
365
366 if (cert_check_result.result_state != STATE_OK &&
367 config.ignore_certificate_expiration) {
368 xasprintf(&sc_cert_check.output,
369 "Remaining certificate lifetime: %d days. Expiration will be ignored",
370 (int)(cert_check_result.remaining_seconds / 86400));
371 sc_cert_check = mp_set_subcheck_state(sc_cert_check, STATE_OK);
372 } else {
373 xasprintf(&sc_cert_check.output, "Remaining certificate lifetime: %d days",
374 (int)(cert_check_result.remaining_seconds / 86400));
375 sc_cert_check =
376 mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
377 }
378 } break;
379 case NO_SERVER_CERTIFICATE_PRESENT: {
380 xasprintf(&sc_cert_check.output, "no server certificate present");
381 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
382 } break;
383 case UNABLE_TO_RETRIEVE_CERTIFICATE_SUBJECT: {
384 xasprintf(&sc_cert_check.output, "can not retrieve certificate subject");
385 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
386 } break;
387 case WRONG_TIME_FORMAT_IN_CERTIFICATE: {
388 xasprintf(&sc_cert_check.output, "wrong time format in certificate");
389 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
390 } break;
391 };
392
393 mp_add_subcheck_to_check(&overall, sc_cert_check);
394 }
395# endif /* MOPL_USE_OPENSSL */
290 396
291# ifdef USE_OPENSSL
292 if ( check_cert ) {
293 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
294 smtp_quit();
295 my_close();
296 return result;
297 }
298# endif /* USE_OPENSSL */
299 }
300#endif 397#endif
301 398
302 if (verbose) 399 if (verbose) {
303 printf ("%s", buffer); 400 printf("%s", buffer);
304 401 }
305 /* save buffer for later use */ 402
306 xasprintf(&server_response, "%s%s", server_response, buffer); 403 /* save buffer for later use */
307 /* strip the buffer of carriage returns */ 404 xasprintf(&server_response, "%s%s", server_response, buffer);
308 strip (server_response); 405 /* strip the buffer of carriage returns */
309 406 strip(server_response);
310 /* make sure we find the droids we are looking for */ 407
311 if (!strstr (server_response, server_expect)) { 408 /* make sure we find the droids we are looking for */
312 if (server_port == SMTP_PORT) 409 mp_subcheck sc_expect_response = mp_subcheck_init();
313 printf (_("Invalid SMTP response received from host: %s\n"), server_response); 410
314 else 411 if (!strstr(server_response, config.server_expect)) {
315 printf (_("Invalid SMTP response received from host on port %d: %s\n"), 412 sc_expect_response = mp_set_subcheck_state(sc_expect_response, STATE_WARNING);
316 server_port, server_response); 413 if (config.server_port == SMTP_PORT) {
317 return STATE_WARNING; 414 xasprintf(&sc_expect_response.output, _("invalid SMTP response received from host: %s"),
415 server_response);
416 } else {
417 xasprintf(&sc_expect_response.output,
418 _("invalid SMTP response received from host on port %d: %s"),
419 config.server_port, server_response);
420 }
421 exit(STATE_WARNING);
422 } else {
423 xasprintf(&sc_expect_response.output, "received valid SMTP response '%s' from host: '%s'",
424 config.server_expect, server_response);
425 sc_expect_response = mp_set_subcheck_state(sc_expect_response, STATE_OK);
426 }
427
428 mp_add_subcheck_to_check(&overall, sc_expect_response);
429
430 if (config.send_mail_from) {
431 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
432 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 &&
433 verbose) {
434 printf("%s", buffer);
435 }
436 }
437
438 size_t counter = 0;
439 while (counter < config.ncommands) {
440 xasprintf(&cmd_str, "%s%s", config.commands[counter], "\r\n");
441 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
442 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 &&
443 verbose) {
444 printf("%s", buffer);
318 } 445 }
319 446
320 if (send_mail_from) { 447 strip(buffer);
321 my_send(cmd_str, strlen(cmd_str)); 448
322 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) 449 if (counter < config.nresponses) {
323 printf("%s", buffer); 450 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
451 regex_t preg;
452 int errcode = regcomp(&preg, config.responses[counter], cflags);
453 char errbuf[MAX_INPUT_BUFFER];
454 if (errcode != 0) {
455 regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER);
456 printf(_("Could Not Compile Regular Expression"));
457 exit(STATE_UNKNOWN);
458 }
459
460 regmatch_t pmatch[10];
461 int eflags = 0;
462 int excode = regexec(&preg, buffer, 10, pmatch, eflags);
463 mp_subcheck sc_expected_responses = mp_subcheck_init();
464 if (excode == 0) {
465 xasprintf(&sc_expected_responses.output, "valid response '%s' to command '%s'",
466 buffer, config.commands[counter]);
467 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_OK);
468 } else if (excode == REG_NOMATCH) {
469 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_WARNING);
470 xasprintf(&sc_expected_responses.output, "invalid response '%s' to command '%s'",
471 buffer, config.commands[counter]);
472 } else {
473 regerror(excode, &preg, errbuf, MAX_INPUT_BUFFER);
474 xasprintf(&sc_expected_responses.output, "regexec execute error: %s", errbuf);
475 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_UNKNOWN);
476 }
324 } 477 }
478 counter++;
479 }
480
481 if (config.authtype != NULL) {
482 mp_subcheck sc_auth = mp_subcheck_init();
325 483
326 n = 0; 484 if (strcmp(config.authtype, "LOGIN") == 0) {
327 while (n < ncommands) { 485 char *abuf;
328 xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); 486 int ret;
329 my_send(cmd_str, strlen(cmd_str)); 487 do {
330 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) 488 /* send AUTH LOGIN */
331 printf("%s", buffer); 489 my_send(config, SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN), socket_descriptor,
332 strip (buffer); 490 ssl_established);
333 if (n < nresponses) { 491
334 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; 492 if (verbose) {
335 errcode = regcomp (&preg, responses[n], cflags); 493 printf(_("sent %s\n"), "AUTH LOGIN");
336 if (errcode != 0) {
337 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
338 printf (_("Could Not Compile Regular Expression"));
339 return ERROR;
340 } 494 }
341 excode = regexec (&preg, buffer, 10, pmatch, eflags); 495
342 if (excode == 0) { 496 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
343 result = STATE_OK; 497 ssl_established)) <= 0) {
498 xasprintf(&sc_auth.output, _("recv() failed after AUTH LOGIN"));
499 sc_auth = mp_set_subcheck_state(sc_auth, STATE_WARNING);
500 break;
344 } 501 }
345 else if (excode == REG_NOMATCH) { 502
346 result = STATE_WARNING; 503 if (verbose) {
347 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); 504 printf(_("received %s\n"), buffer);
348 } 505 }
349 else { 506
350 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); 507 if (strncmp(buffer, "334", 3) != 0) {
351 printf (_("Execute Error: %s\n"), errbuf); 508 xasprintf(&sc_auth.output, "invalid response received after AUTH LOGIN");
352 result = STATE_UNKNOWN; 509 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
510 break;
511 }
512
513 /* encode authuser with base64 */
514 base64_encode_alloc(config.authuser, strlen(config.authuser), &abuf);
515 xasprintf(&abuf, "%s\r\n", abuf);
516 my_send(config, abuf, (int)strlen(abuf), socket_descriptor, ssl_established);
517 if (verbose) {
518 printf(_("sent %s\n"), abuf);
353 } 519 }
354 }
355 n++;
356 }
357 520
358 if (authtype != NULL) { 521 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
359 if (strcmp (authtype, "LOGIN") == 0) { 522 ssl_established)) <= 0) {
360 char *abuf; 523 xasprintf(&sc_auth.output, "recv() failed after sending authuser");
361 int ret; 524 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
362 do {
363 if (authuser == NULL) {
364 result = STATE_CRITICAL;
365 xasprintf(&error_msg, _("no authuser specified, "));
366 break;
367 }
368 if (authpass == NULL) {
369 result = STATE_CRITICAL;
370 xasprintf(&error_msg, _("no authpass specified, "));
371 break;
372 }
373
374 /* send AUTH LOGIN */
375 my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
376 if (verbose)
377 printf (_("sent %s\n"), "AUTH LOGIN");
378
379 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
380 xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
381 result = STATE_WARNING;
382 break;
383 }
384 if (verbose)
385 printf (_("received %s\n"), buffer);
386
387 if (strncmp (buffer, "334", 3) != 0) {
388 result = STATE_CRITICAL;
389 xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
390 break;
391 }
392
393 /* encode authuser with base64 */
394 base64_encode_alloc (authuser, strlen(authuser), &abuf);
395 xasprintf(&abuf, "%s\r\n", abuf);
396 my_send(abuf, strlen(abuf));
397 if (verbose)
398 printf (_("sent %s\n"), abuf);
399
400 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
401 result = STATE_CRITICAL;
402 xasprintf(&error_msg, _("recv() failed after sending authuser, "));
403 break;
404 }
405 if (verbose) {
406 printf (_("received %s\n"), buffer);
407 }
408 if (strncmp (buffer, "334", 3) != 0) {
409 result = STATE_CRITICAL;
410 xasprintf(&error_msg, _("invalid response received after authuser, "));
411 break;
412 }
413 /* encode authpass with base64 */
414 base64_encode_alloc (authpass, strlen(authpass), &abuf);
415 xasprintf(&abuf, "%s\r\n", abuf);
416 my_send(abuf, strlen(abuf));
417 if (verbose) {
418 printf (_("sent %s\n"), abuf);
419 }
420 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
421 result = STATE_CRITICAL;
422 xasprintf(&error_msg, _("recv() failed after sending authpass, "));
423 break;
424 }
425 if (verbose) {
426 printf (_("received %s\n"), buffer);
427 }
428 if (strncmp (buffer, "235", 3) != 0) {
429 result = STATE_CRITICAL;
430 xasprintf(&error_msg, _("invalid response received after authpass, "));
431 break;
432 }
433 break; 525 break;
434 } while (0); 526 }
435 } else {
436 result = STATE_CRITICAL;
437 xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
438 }
439 }
440 527
441 /* tell the server we're done */ 528 if (verbose) {
442 smtp_quit(); 529 printf(_("received %s\n"), buffer);
530 }
443 531
444 /* finally close the connection */ 532 if (strncmp(buffer, "334", 3) != 0) {
445 close (sd); 533 xasprintf(&sc_auth.output, "invalid response received after authuser");
446 } 534 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
535 break;
536 }
447 537
448 /* reset the alarm */ 538 /* encode authpass with base64 */
449 alarm (0); 539 base64_encode_alloc(config.authpass, strlen(config.authpass), &abuf);
540 xasprintf(&abuf, "%s\r\n", abuf);
541 my_send(config, abuf, (int)strlen(abuf), socket_descriptor, ssl_established);
450 542
451 microsec = deltime (tv); 543 if (verbose) {
452 elapsed_time = (double)microsec / 1.0e6; 544 printf(_("sent %s\n"), abuf);
545 }
453 546
454 if (result == STATE_OK) { 547 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
455 if (check_critical_time && elapsed_time > critical_time) 548 ssl_established)) <= 0) {
456 result = STATE_CRITICAL; 549 xasprintf(&sc_auth.output, "recv() failed after sending authpass");
457 else if (check_warning_time && elapsed_time > warning_time) 550 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
458 result = STATE_WARNING; 551 break;
552 }
553
554 if (verbose) {
555 printf(_("received %s\n"), buffer);
556 }
557
558 if (strncmp(buffer, "235", 3) != 0) {
559 xasprintf(&sc_auth.output, "invalid response received after authpass");
560 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
561 break;
562 }
563 break;
564 } while (false);
565 } else {
566 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
567 xasprintf(&sc_auth.output, "only authtype LOGIN is supported");
568 }
569
570 mp_add_subcheck_to_check(&overall, sc_auth);
459 } 571 }
460 572
461 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), 573 /* tell the server we're done */
462 state_text (result), 574 smtp_quit(config, buffer, socket_descriptor, ssl_established);
463 error_msg,
464 elapsed_time,
465 verbose?", ":"", verbose?buffer:"",
466 fperfdata ("time", elapsed_time, "s",
467 (int)check_warning_time, warning_time,
468 (int)check_critical_time, critical_time,
469 true, 0, false, 0));
470 575
471 return result; 576 /* finally close the connection */
472} 577 close(socket_descriptor);
473 578
579 /* reset the alarm */
580 alarm(0);
474 581
582 long microsec = deltime(start_time);
583 double elapsed_time = (double)microsec / 1.0e6;
475 584
476/* process command-line arguments */ 585 mp_perfdata pd_elapsed_time = perfdata_init();
477int 586 pd_elapsed_time = mp_set_pd_value(pd_elapsed_time, elapsed_time);
478process_arguments (int argc, char **argv) 587 pd_elapsed_time.label = "time";
479{ 588 pd_elapsed_time.uom = "s";
480 int c;
481 char* temp;
482 589
483 bool implicit_tls = false; 590 pd_elapsed_time = mp_pd_set_thresholds(pd_elapsed_time, config.connection_time);
484 591
592 mp_subcheck sc_connection_time = mp_subcheck_init();
593 xasprintf(&sc_connection_time.output, "connection time: %.3gs", elapsed_time);
594 sc_connection_time =
595 mp_set_subcheck_state(sc_connection_time, mp_get_pd_status(pd_elapsed_time));
596 mp_add_subcheck_to_check(&overall, sc_connection_time);
597
598 mp_exit(overall);
599}
600
601/* process command-line arguments */
602check_smtp_config_wrapper process_arguments(int argc, char **argv) {
485 enum { 603 enum {
486 SNI_OPTION 604 SNI_OPTION = CHAR_MAX + 1,
605 output_format_index,
606 ignore_certificate_expiration_index,
487 }; 607 };
488 608
489 int option = 0; 609 int option = 0;
@@ -509,277 +629,301 @@ process_arguments (int argc, char **argv)
509 {"lmtp", no_argument, 0, 'L'}, 629 {"lmtp", no_argument, 0, 'L'},
510 {"ssl", no_argument, 0, 's'}, 630 {"ssl", no_argument, 0, 's'},
511 {"tls", no_argument, 0, 's'}, 631 {"tls", no_argument, 0, 's'},
512 {"starttls",no_argument,0,'S'}, 632 {"starttls", no_argument, 0, 'S'},
513 {"sni", no_argument, 0, SNI_OPTION}, 633 {"sni", no_argument, 0, SNI_OPTION},
514 {"certificate",required_argument,0,'D'}, 634 {"certificate", required_argument, 0, 'D'},
515 {"ignore-quit-failure",no_argument,0,'q'}, 635 {"ignore-quit-failure", no_argument, 0, 'q'},
516 {"proxy",no_argument,0,'r'}, 636 {"proxy", no_argument, 0, 'r'},
517 {0, 0, 0, 0} 637 {"ignore-certificate-expiration", no_argument, 0, ignore_certificate_expiration_index},
638 {"output-format", required_argument, 0, output_format_index},
639 {0, 0, 0, 0}};
640
641 check_smtp_config_wrapper result = {
642 .config = check_smtp_config_init(),
643 .errorcode = OK,
518 }; 644 };
519 645
520 if (argc < 2) 646 if (argc < 2) {
521 return ERROR; 647 result.errorcode = ERROR;
648 return result;
649 }
522 650
523 for (c = 1; c < argc; c++) { 651 for (int index = 1; index < argc; index++) {
524 if (strcmp ("-to", argv[c]) == 0) 652 if (strcmp("-to", argv[index]) == 0) {
525 strcpy (argv[c], "-t"); 653 strcpy(argv[index], "-t");
526 else if (strcmp ("-wt", argv[c]) == 0) 654 } else if (strcmp("-wt", argv[index]) == 0) {
527 strcpy (argv[c], "-w"); 655 strcpy(argv[index], "-w");
528 else if (strcmp ("-ct", argv[c]) == 0) 656 } else if (strcmp("-ct", argv[index]) == 0) {
529 strcpy (argv[c], "-c"); 657 strcpy(argv[index], "-c");
658 }
530 } 659 }
531 660
532 while (1) { 661 unsigned long command_size = 0;
533 c = getopt_long (argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", 662 unsigned long response_size = 0;
534 longopts, &option); 663 bool implicit_tls = false;
664 int server_port_option = 0;
665 while (true) {
666 int opt_index =
667 getopt_long(argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", longopts, &option);
535 668
536 if (c == -1 || c == EOF) 669 if (opt_index == -1 || opt_index == EOF) {
537 break; 670 break;
671 }
538 672
539 switch (c) { 673 switch (opt_index) {
540 case 'H': /* hostname */ 674 case 'H': /* hostname */
541 if (is_host (optarg)) { 675 if (is_host(optarg)) {
542 server_address = optarg; 676 result.config.server_address = optarg;
543 } 677 } else {
544 else { 678 usage2(_("Invalid hostname/address"), optarg);
545 usage2 (_("Invalid hostname/address"), optarg);
546 } 679 }
547 break; 680 break;
548 case 'p': /* port */ 681 case 'p': /* port */
549 if (is_intpos (optarg)) 682 if (is_intpos(optarg)) {
550 server_port_option = atoi (optarg); 683 server_port_option = atoi(optarg);
551 else 684 } else {
552 usage4 (_("Port must be a positive integer")); 685 usage4(_("Port must be a positive integer"));
686 }
553 break; 687 break;
554 case 'F': 688 case 'F':
555 /* localhostname */ 689 /* localhostname */
556 localhostname = strdup(optarg); 690 result.config.localhostname = strdup(optarg);
557 break; 691 break;
558 case 'f': /* from argument */ 692 case 'f': /* from argument */
559 from_arg = optarg + strspn(optarg, "<"); 693 result.config.from_arg = optarg + strspn(optarg, "<");
560 from_arg = strndup(from_arg, strcspn(from_arg, ">")); 694 result.config.from_arg =
561 send_mail_from = 1; 695 strndup(result.config.from_arg, strcspn(result.config.from_arg, ">"));
696 result.config.send_mail_from = true;
562 break; 697 break;
563 case 'A': 698 case 'A':
564 authtype = optarg; 699 result.config.authtype = optarg;
565 use_ehlo = true; 700 result.config.use_ehlo = true;
566 break; 701 break;
567 case 'U': 702 case 'U':
568 authuser = optarg; 703 result.config.authuser = optarg;
569 break; 704 break;
570 case 'P': 705 case 'P':
571 authpass = optarg; 706 result.config.authpass = optarg;
572 break; 707 break;
573 case 'e': /* server expect string on 220 */ 708 case 'e': /* server expect string on 220 */
574 server_expect = optarg; 709 result.config.server_expect = optarg;
575 break; 710 break;
576 case 'C': /* commands */ 711 case 'C': /* commands */
577 if (ncommands >= command_size) { 712 if (result.config.ncommands >= command_size) {
578 command_size+=8; 713 command_size += 8;
579 commands = realloc (commands, sizeof(char *) * command_size); 714 result.config.commands =
580 if (commands == NULL) 715 realloc(result.config.commands, sizeof(char *) * command_size);
581 die (STATE_UNKNOWN, 716 if (result.config.commands == NULL) {
582 _("Could not realloc() units [%d]\n"), ncommands); 717 die(STATE_UNKNOWN, _("Could not realloc() units [%lu]\n"),
718 result.config.ncommands);
719 }
583 } 720 }
584 commands[ncommands] = (char *) malloc (sizeof(char) * 255); 721 result.config.commands[result.config.ncommands] = (char *)malloc(sizeof(char) * 255);
585 strncpy (commands[ncommands], optarg, 255); 722 strncpy(result.config.commands[result.config.ncommands], optarg, 255);
586 ncommands++; 723 result.config.ncommands++;
587 break; 724 break;
588 case 'R': /* server responses */ 725 case 'R': /* server responses */
589 if (nresponses >= response_size) { 726 if (result.config.nresponses >= response_size) {
590 response_size += 8; 727 response_size += 8;
591 responses = realloc (responses, sizeof(char *) * response_size); 728 result.config.responses =
592 if (responses == NULL) 729 realloc(result.config.responses, sizeof(char *) * response_size);
593 die (STATE_UNKNOWN, 730 if (result.config.responses == NULL) {
594 _("Could not realloc() units [%d]\n"), nresponses); 731 die(STATE_UNKNOWN, _("Could not realloc() units [%lu]\n"),
732 result.config.nresponses);
733 }
595 } 734 }
596 responses[nresponses] = (char *) malloc (sizeof(char) * 255); 735 result.config.responses[result.config.nresponses] = (char *)malloc(sizeof(char) * 255);
597 strncpy (responses[nresponses], optarg, 255); 736 strncpy(result.config.responses[result.config.nresponses], optarg, 255);
598 nresponses++; 737 result.config.nresponses++;
599 break; 738 break;
600 case 'c': /* critical time threshold */ 739 case 'c': /* critical time threshold */ {
601 if (!is_nonnegative (optarg)) 740 mp_range_parsed tmp = mp_parse_range_string(optarg);
602 usage4 (_("Critical time must be a positive")); 741 if (tmp.error != MP_PARSING_SUCCESS) {
603 else { 742 die(STATE_UNKNOWN, "failed to parse critical time threshold");
604 critical_time = strtod (optarg, NULL);
605 check_critical_time = true;
606 } 743 }
607 break; 744 result.config.connection_time =
608 case 'w': /* warning time threshold */ 745 mp_thresholds_set_warn(result.config.connection_time, tmp.range);
609 if (!is_nonnegative (optarg)) 746 } break;
610 usage4 (_("Warning time must be a positive")); 747 case 'w': /* warning time threshold */ {
611 else { 748 mp_range_parsed tmp = mp_parse_range_string(optarg);
612 warning_time = strtod (optarg, NULL); 749 if (tmp.error != MP_PARSING_SUCCESS) {
613 check_warning_time = true; 750 die(STATE_UNKNOWN, "failed to parse warning time threshold");
614 } 751 }
615 break; 752 result.config.connection_time =
616 case 'v': /* verbose */ 753 mp_thresholds_set_crit(result.config.connection_time, tmp.range);
754 } break;
755 case 'v': /* verbose */
617 verbose++; 756 verbose++;
618 break; 757 break;
619 case 'q': 758 case 'q':
620 ignore_send_quit_failure = true; /* ignore problem sending QUIT */ 759 result.config.ignore_send_quit_failure = true; /* ignore problem sending QUIT */
621 break; 760 break;
622 case 't': /* timeout */ 761 case 't': /* timeout */
623 if (is_intnonneg (optarg)) { 762 if (is_intnonneg(optarg)) {
624 socket_timeout = atoi (optarg); 763 socket_timeout = atoi(optarg);
625 } 764 } else {
626 else { 765 usage4(_("Timeout interval must be a positive integer"));
627 usage4 (_("Timeout interval must be a positive integer"));
628 } 766 }
629 break; 767 break;
630 case 'D': 768 case 'D': {
631 /* Check SSL cert validity */ 769 /* Check SSL cert validity */
632#ifdef USE_OPENSSL 770#ifdef MOPL_USE_OPENSSL
633 if ((temp=strchr(optarg,','))!=NULL) { 771 char *temp;
634 *temp='\0'; 772 if ((temp = strchr(optarg, ',')) != NULL) {
635 if (!is_intnonneg (optarg)) 773 *temp = '\0';
636 usage2 ("Invalid certificate expiration period", optarg); 774 if (!is_intnonneg(optarg)) {
637 days_till_exp_warn = atoi(optarg); 775 usage2("Invalid certificate expiration period", optarg);
638 *temp=','; 776 }
639 temp++; 777 result.config.days_till_exp_warn = atoi(optarg);
640 if (!is_intnonneg (temp)) 778 *temp = ',';
641 usage2 (_("Invalid certificate expiration period"), temp); 779 temp++;
642 days_till_exp_crit = atoi (temp); 780 if (!is_intnonneg(temp)) {
643 } 781 usage2(_("Invalid certificate expiration period"), temp);
644 else { 782 }
645 days_till_exp_crit=0; 783 result.config.days_till_exp_crit = atoi(temp);
646 if (!is_intnonneg (optarg)) 784 } else {
647 usage2 ("Invalid certificate expiration period", optarg); 785 result.config.days_till_exp_crit = 0;
648 days_till_exp_warn = atoi (optarg); 786 if (!is_intnonneg(optarg)) {
649 } 787 usage2("Invalid certificate expiration period", optarg);
650 check_cert = true; 788 }
651 ignore_send_quit_failure = true; 789 result.config.days_till_exp_warn = atoi(optarg);
790 }
791 result.config.ignore_send_quit_failure = true;
652#else 792#else
653 usage (_("SSL support not available - install OpenSSL and recompile")); 793 usage(_("SSL support not available - install OpenSSL and recompile"));
654#endif 794#endif
655 implicit_tls = true; 795 implicit_tls = true;
656 // fallthrough 796 // fallthrough
657 case 's': 797 case 's':
658 /* ssl */ 798 /* ssl */
659 use_ssl = true; 799 result.config.use_ssl = true;
660 server_port = SMTPS_PORT; 800 result.config.server_port = SMTPS_PORT;
661 break; 801 break;
662 case 'S': 802 case 'S':
663 /* starttls */ 803 /* starttls */
664 use_starttls = true; 804 result.config.use_starttls = true;
665 use_ehlo = true; 805 result.config.use_ehlo = true;
666 break; 806 break;
807 }
667 case SNI_OPTION: 808 case SNI_OPTION:
668#ifdef HAVE_SSL 809#ifdef HAVE_SSL
669 use_sni = true; 810 result.config.use_sni = true;
670#else 811#else
671 usage (_("SSL support not available - install OpenSSL and recompile")); 812 usage(_("SSL support not available - install OpenSSL and recompile"));
672#endif 813#endif
673 break; 814 break;
674 case 'r': 815 case 'r':
675 use_proxy_prefix = true; 816 result.config.use_proxy_prefix = true;
676 break; 817 break;
677 case 'L': 818 case 'L':
678 use_lhlo = true; 819 result.config.use_lhlo = true;
679 break; 820 break;
680 case '4': 821 case '4':
681 address_family = AF_INET; 822 address_family = AF_INET;
682 break; 823 break;
683 case '6': 824 case '6':
684#ifdef USE_IPV6
685 address_family = AF_INET6; 825 address_family = AF_INET6;
686#else
687 usage4 (_("IPv6 support not available"));
688#endif
689 break; 826 break;
690 case 'V': /* version */ 827 case 'V': /* version */
691 print_revision (progname, NP_VERSION); 828 print_revision(progname, NP_VERSION);
692 exit (STATE_UNKNOWN); 829 exit(STATE_UNKNOWN);
693 case 'h': /* help */ 830 case 'h': /* help */
694 print_help (); 831 print_help();
695 exit (STATE_UNKNOWN); 832 exit(STATE_UNKNOWN);
696 case '?': /* help */ 833 case '?': /* help */
697 usage5 (); 834 usage5();
835 case output_format_index: {
836 parsed_output_format parser = mp_parse_output_format(optarg);
837 if (!parser.parsing_success) {
838 // TODO List all available formats here, maybe add anothoer usage function
839 printf("Invalid output format: %s\n", optarg);
840 exit(STATE_UNKNOWN);
841 }
842
843 result.config.output_format_is_set = true;
844 result.config.output_format = parser.output_format;
845 break;
846 }
847 case ignore_certificate_expiration_index: {
848 result.config.ignore_certificate_expiration = true;
849 }
698 } 850 }
699 } 851 }
700 852
701 c = optind; 853 int c = optind;
702 if (server_address == NULL) { 854 if (result.config.server_address == NULL) {
703 if (argv[c]) { 855 if (argv[c]) {
704 if (is_host (argv[c])) 856 if (is_host(argv[c])) {
705 server_address = argv[c]; 857 result.config.server_address = argv[c];
706 else 858 } else {
707 usage2 (_("Invalid hostname/address"), argv[c]); 859 usage2(_("Invalid hostname/address"), argv[c]);
708 } 860 }
709 else { 861 } else {
710 xasprintf (&server_address, "127.0.0.1"); 862 result.config.server_address = strdup("localhost");
711 } 863 }
712 } 864 }
713 865
714 if (server_expect == NULL) 866 if (result.config.use_starttls && result.config.use_ssl) {
715 server_expect = strdup (SMTP_EXPECT);
716
717 if (mail_command == NULL)
718 mail_command = strdup("MAIL ");
719
720 if (from_arg==NULL)
721 from_arg = strdup(" ");
722
723 if (use_starttls && use_ssl) {
724 if (implicit_tls) { 867 if (implicit_tls) {
725 use_ssl = false; 868 result.config.use_ssl = false;
726 server_port = SMTP_PORT;
727 } else { 869 } else {
728 usage4 (_("Set either -s/--ssl/--tls or -S/--starttls")); 870 usage4(_("Set either -s/--ssl/--tls or -S/--starttls"));
729 } 871 }
730 } 872 }
731 873
732 if (server_port_option != 0) { 874 if (server_port_option != 0) {
733 server_port = server_port_option; 875 result.config.server_port = server_port_option;
734 } 876 }
735 877
736 return validate_arguments (); 878 if (result.config.authtype) {
737} 879 if (strcmp(result.config.authtype, "LOGIN") == 0) {
738 880 if (result.config.authuser == NULL) {
739 881 usage4("no authuser specified");
882 }
883 if (result.config.authpass == NULL) {
884 usage4("no authpass specified");
885 }
886 } else {
887 usage4("only authtype LOGIN is supported");
888 }
889 }
740 890
741int 891 return result;
742validate_arguments (void)
743{
744 return OK;
745} 892}
746 893
747 894char *smtp_quit(check_smtp_config config, char buffer[MAX_INPUT_BUFFER], int socket_descriptor,
748void 895 bool ssl_established) {
749smtp_quit(void) 896 int sent_bytes =
750{ 897 my_send(config, SMTP_QUIT, strlen(SMTP_QUIT), socket_descriptor, ssl_established);
751 int bytes; 898 if (sent_bytes < 0) {
752 int n; 899 if (config.ignore_send_quit_failure) {
753 900 if (verbose) {
754 n = my_send(SMTP_QUIT, strlen(SMTP_QUIT));
755 if(n < 0) {
756 if(ignore_send_quit_failure) {
757 if(verbose) {
758 printf(_("Connection closed by server before sending QUIT command\n")); 901 printf(_("Connection closed by server before sending QUIT command\n"));
759 } 902 }
760 return; 903 return buffer;
761 } 904 }
762 die (STATE_UNKNOWN, 905 die(STATE_UNKNOWN, _("Connection closed by server before sending QUIT command\n"));
763 _("Connection closed by server before sending QUIT command\n"));
764 } 906 }
765 907
766 if (verbose) 908 if (verbose) {
767 printf(_("sent %s\n"), "QUIT"); 909 printf(_("sent %s\n"), "QUIT");
910 }
768 911
769 /* read the response but don't care about problems */ 912 /* read the response but don't care about problems */
770 bytes = recvlines(buffer, MAX_INPUT_BUFFER); 913 int bytes = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established);
771 if (verbose) { 914 if (verbose) {
772 if (bytes < 0) 915 if (bytes < 0) {
773 printf(_("recv() failed after QUIT.")); 916 printf(_("recv() failed after QUIT."));
774 else if (bytes == 0) 917 } else if (bytes == 0) {
775 printf(_("Connection reset by peer.")); 918 printf(_("Connection reset by peer."));
776 else { 919 } else {
777 buffer[bytes] = '\0'; 920 buffer[bytes] = '\0';
778 printf(_("received %s\n"), buffer); 921 printf(_("received %s\n"), buffer);
779 } 922 }
780 } 923 }
781}
782 924
925 return buffer;
926}
783 927
784/* 928/*
785 * Receive one line, copy it into buf and nul-terminate it. Returns the 929 * Receive one line, copy it into buf and nul-terminate it. Returns the
@@ -790,24 +934,23 @@ smtp_quit(void)
790 * function which buffers the data, move that to netutils.c and change 934 * function which buffers the data, move that to netutils.c and change
791 * check_smtp and other plugins to use that. Also, remove (\r)\n. 935 * check_smtp and other plugins to use that. Also, remove (\r)\n.
792 */ 936 */
793int 937int recvline(char *buf, size_t bufsize, check_smtp_config config, int socket_descriptor,
794recvline(char *buf, size_t bufsize) 938 bool ssl_established) {
795{
796 int result; 939 int result;
797 unsigned i; 940 size_t counter;
798 941
799 for (i = result = 0; i < bufsize - 1; i++) { 942 for (counter = result = 0; counter < bufsize - 1; counter++) {
800 if ((result = my_recv(&buf[i], 1)) != 1) 943 if ((result = my_recv(config, &buf[counter], 1, socket_descriptor, ssl_established)) != 1) {
801 break; 944 break;
802 if (buf[i] == '\n') { 945 }
803 buf[++i] = '\0'; 946 if (buf[counter] == '\n') {
804 return i; 947 buf[++counter] = '\0';
948 return (int)counter;
805 } 949 }
806 } 950 }
807 return (result == 1 || i == 0) ? -2 : result; /* -2 if out of space */ 951 return (result == 1 || counter == 0) ? -2 : result; /* -2 if out of space */
808} 952}
809 953
810
811/* 954/*
812 * Receive one or more lines, copy them into buf and nul-terminate it. Returns 955 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
813 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on 956 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
@@ -822,117 +965,114 @@ recvline(char *buf, size_t bufsize)
822 * 965 *
823 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n. 966 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
824 */ 967 */
825int 968int recvlines(check_smtp_config config, char *buf, size_t bufsize, int socket_descriptor,
826recvlines(char *buf, size_t bufsize) 969 bool ssl_established) {
827{ 970 int result;
828 int result, i; 971 int counter;
829 972
830 for (i = 0; /* forever */; i += result) 973 for (counter = 0; /* forever */; counter += result) {
831 if (!((result = recvline(buf + i, bufsize - i)) > 3 && 974 if (!((result = recvline(buf + counter, bufsize - counter, config, socket_descriptor,
832 isdigit((int)buf[i]) && 975 ssl_established)) > 3 &&
833 isdigit((int)buf[i + 1]) && 976 isdigit((int)buf[counter]) && isdigit((int)buf[counter + 1]) &&
834 isdigit((int)buf[i + 2]) && 977 isdigit((int)buf[counter + 2]) && buf[counter + 3] == '-')) {
835 buf[i + 3] == '-'))
836 break; 978 break;
979 }
980 }
837 981
838 return (result <= 0) ? result : result + i; 982 return (result <= 0) ? result : result + counter;
839} 983}
840 984
841 985int my_close(int socket_descriptor) {
842int
843my_close (void)
844{
845 int result; 986 int result;
846 result = close(sd); 987 result = close(socket_descriptor);
847#ifdef HAVE_SSL 988#ifdef HAVE_SSL
848 np_net_ssl_cleanup(); 989 np_net_ssl_cleanup();
849#endif 990#endif
850 return result; 991 return result;
851} 992}
852 993
853 994void print_help(void) {
854void
855print_help (void)
856{
857 char *myport; 995 char *myport;
858 xasprintf (&myport, "%d", SMTP_PORT); 996 xasprintf(&myport, "%d", SMTP_PORT);
859 997
860 print_revision (progname, NP_VERSION); 998 print_revision(progname, NP_VERSION);
861 999
862 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n"); 1000 printf("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
863 printf (COPYRIGHT, copyright, email); 1001 printf(COPYRIGHT, copyright, email);
864 1002
865 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host.")); 1003 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
866 1004
867 printf ("\n\n"); 1005 printf("\n\n");
868 1006
869 print_usage (); 1007 print_usage();
870 1008
871 printf (UT_HELP_VRSN); 1009 printf(UT_HELP_VRSN);
872 printf (UT_EXTRA_OPTS); 1010 printf(UT_EXTRA_OPTS);
873 1011
874 printf (UT_HOST_PORT, 'p', myport); 1012 printf(UT_HOST_PORT, 'p', myport);
875 1013
876 printf (UT_IPv46); 1014 printf(UT_IPv46);
877 1015
878 printf (" %s\n", "-e, --expect=STRING"); 1016 printf(" %s\n", "-e, --expect=STRING");
879 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT); 1017 printf(_(" String to expect in first line of server response (default: '%s')\n"),
880 printf (" %s\n", "-C, --command=STRING"); 1018 SMTP_EXPECT);
881 printf (" %s\n", _("SMTP command (may be used repeatedly)")); 1019 printf(" %s\n", "-C, --command=STRING");
882 printf (" %s\n", "-R, --response=STRING"); 1020 printf(" %s\n", _("SMTP command (may be used repeatedly)"));
883 printf (" %s\n", _("Expected response to command (may be used repeatedly)")); 1021 printf(" %s\n", "-R, --response=STRING");
884 printf (" %s\n", "-f, --from=STRING"); 1022 printf(" %s\n", _("Expected response to command (may be used repeatedly)"));
885 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")), 1023 printf(" %s\n", "-f, --from=STRING");
886 printf (" %s\n", "-F, --fqdn=STRING"); 1024 printf(" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
887 printf (" %s\n", _("FQDN used for HELO")); 1025 printf(" %s\n", "-F, --fqdn=STRING");
888 printf (" %s\n", "-r, --proxy"); 1026 printf(" %s\n", _("FQDN used for HELO"));
889 printf (" %s\n", _("Use PROXY protocol prefix for the connection.")); 1027 printf(" %s\n", "-r, --proxy");
1028 printf(" %s\n", _("Use PROXY protocol prefix for the connection."));
890#ifdef HAVE_SSL 1029#ifdef HAVE_SSL
891 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]"); 1030 printf(" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
892 printf (" %s\n", _("Minimum number of days a certificate has to be valid.")); 1031 printf(" %s\n", _("Minimum number of days a certificate has to be valid."));
893 printf (" %s\n", "-s, --ssl, --tls"); 1032 printf(" %s\n", "-s, --ssl, --tls");
894 printf (" %s\n", _("Use SSL/TLS for the connection.")); 1033 printf(" %s\n", _("Use SSL/TLS for the connection."));
895 printf (_(" Sets default port to %d.\n"), SMTPS_PORT); 1034 printf(_(" Sets default port to %d.\n"), SMTPS_PORT);
896 printf (" %s\n", "-S, --starttls"); 1035 printf(" %s\n", "-S, --starttls");
897 printf (" %s\n", _("Use STARTTLS for the connection.")); 1036 printf(" %s\n", _("Use STARTTLS for the connection."));
898 printf (" %s\n", "--sni"); 1037 printf(" %s\n", "--sni");
899 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); 1038 printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
900#endif 1039#endif
901 1040
902 printf (" %s\n", "-A, --authtype=STRING"); 1041 printf(" %s\n", "-A, --authtype=STRING");
903 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)")); 1042 printf(" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
904 printf (" %s\n", "-U, --authuser=STRING"); 1043 printf(" %s\n", "-U, --authuser=STRING");
905 printf (" %s\n", _("SMTP AUTH username")); 1044 printf(" %s\n", _("SMTP AUTH username"));
906 printf (" %s\n", "-P, --authpass=STRING"); 1045 printf(" %s\n", "-P, --authpass=STRING");
907 printf (" %s\n", _("SMTP AUTH password")); 1046 printf(" %s\n", _("SMTP AUTH password"));
908 printf (" %s\n", "-L, --lmtp"); 1047 printf(" %s\n", "-L, --lmtp");
909 printf (" %s\n", _("Send LHLO instead of HELO/EHLO")); 1048 printf(" %s\n", _("Send LHLO instead of HELO/EHLO"));
910 printf (" %s\n", "-q, --ignore-quit-failure"); 1049 printf(" %s\n", "-q, --ignore-quit-failure");
911 printf (" %s\n", _("Ignore failure when sending QUIT command to server")); 1050 printf(" %s\n", _("Ignore failure when sending QUIT command to server"));
912 1051 printf(" %s\n", "--ignore-certificate-expiration");
913 printf (UT_WARN_CRIT); 1052 printf(" %s\n", _("Ignore certificate expiration"));
914
915 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
916 1053
917 printf (UT_VERBOSE); 1054 printf(UT_WARN_CRIT);
918 1055
919 printf("\n"); 1056 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
920 printf ("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
921 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
922 printf ("%s\n", _("connects, but incorrect response messages from the host result in"));
923 printf ("%s\n", _("STATE_WARNING return values."));
924 1057
925 printf (UT_SUPPORT); 1058 printf(UT_OUTPUT_FORMAT);
926}
927 1059
1060 printf(UT_VERBOSE);
928 1061
1062 printf("\n");
1063 printf("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
1064 printf("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
1065 printf("%s\n", _("connects, but incorrect response messages from the host result in"));
1066 printf("%s\n", _("STATE_WARNING return values."));
929 1067
930void 1068 printf(UT_SUPPORT);
931print_usage (void)
932{
933 printf ("%s\n", _("Usage:"));
934 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname);
935 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
936 printf ("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] [-v] \n");
937} 1069}
938 1070
1071void print_usage(void) {
1072 printf("%s\n", _("Usage:"));
1073 printf("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n",
1074 progname);
1075 printf("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
1076 printf("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] "
1077 "[-v] \n");
1078}