check_smtp.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /******************************************************************************
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; either version 2 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program; if not, write to the Free Software
  12. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  13. $Id$
  14. ******************************************************************************/
  15. const char *progname = "check_smtp";
  16. const char *revision = "$Revision$";
  17. const char *copyright = "2000-2004";
  18. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  19. #include "common.h"
  20. #include "netutils.h"
  21. #include "utils.h"
  22. #ifdef HAVE_SSL
  23. int check_cert = FALSE;
  24. int days_till_exp;
  25. # define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
  26. # define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
  27. #else /* ifndef HAVE_SSL */
  28. # define my_recv(buf, len) read(sd, buf, len)
  29. # define my_send(buf, len) send(sd, buf, len, 0)
  30. #endif
  31. enum {
  32. SMTP_PORT = 25
  33. };
  34. #define SMTP_EXPECT "220"
  35. #define SMTP_HELO "HELO "
  36. #define SMTP_EHLO "EHLO "
  37. #define SMTP_QUIT "QUIT\r\n"
  38. #define SMTP_STARTTLS "STARTTLS\r\n"
  39. #ifndef HOST_MAX_BYTES
  40. #define HOST_MAX_BYTES 255
  41. #endif
  42. #define EHLO_SUPPORTS_STARTTLS 1
  43. int process_arguments (int, char **);
  44. int validate_arguments (void);
  45. void print_help (void);
  46. void print_usage (void);
  47. int my_close(void);
  48. #ifdef HAVE_REGEX_H
  49. #include <regex.h>
  50. char regex_expect[MAX_INPUT_BUFFER] = "";
  51. regex_t preg;
  52. regmatch_t pmatch[10];
  53. char timestamp[20] = "";
  54. char errbuf[MAX_INPUT_BUFFER];
  55. int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  56. int eflags = 0;
  57. int errcode, excode;
  58. #endif
  59. int server_port = SMTP_PORT;
  60. char *server_address = NULL;
  61. char *server_expect = NULL;
  62. int smtp_use_dummycmd = 0;
  63. char *mail_command = NULL;
  64. char *from_arg = NULL;
  65. int ncommands=0;
  66. int command_size=0;
  67. int nresponses=0;
  68. int response_size=0;
  69. char **commands = NULL;
  70. char **responses = NULL;
  71. int warning_time = 0;
  72. int check_warning_time = FALSE;
  73. int critical_time = 0;
  74. int check_critical_time = FALSE;
  75. int verbose = 0;
  76. int use_ssl = FALSE;
  77. short use_ehlo = FALSE;
  78. short ssl_established = 0;
  79. char *localhostname = NULL;
  80. int sd;
  81. char buffer[MAX_INPUT_BUFFER];
  82. enum {
  83. TCP_PROTOCOL = 1,
  84. UDP_PROTOCOL = 2,
  85. MAXBUF = 1024
  86. };
  87. int
  88. main (int argc, char **argv)
  89. {
  90. short supports_tls=FALSE;
  91. int n = 0;
  92. double elapsed_time;
  93. long microsec;
  94. int result = STATE_UNKNOWN;
  95. char *cmd_str = NULL;
  96. char *helocmd = NULL;
  97. struct timeval tv;
  98. struct hostent *hp;
  99. setlocale (LC_ALL, "");
  100. bindtextdomain (PACKAGE, LOCALEDIR);
  101. textdomain (PACKAGE);
  102. if (process_arguments (argc, argv) == ERROR)
  103. usage4 (_("Could not parse arguments"));
  104. /* initialize the HELO command with the localhostname */
  105. if(! localhostname){
  106. localhostname = malloc (HOST_MAX_BYTES);
  107. if(!localhostname){
  108. printf(_("malloc() failed!\n"));
  109. return STATE_CRITICAL;
  110. }
  111. if(gethostname(localhostname, HOST_MAX_BYTES)){
  112. printf(_("gethostname() failed!\n"));
  113. return STATE_CRITICAL;
  114. }
  115. hp = gethostbyname(localhostname);
  116. if(!hp) helocmd = localhostname;
  117. else helocmd = hp->h_name;
  118. } else {
  119. helocmd = localhostname;
  120. }
  121. if(use_ehlo)
  122. asprintf (&helocmd, "%s%s%s", SMTP_EHLO, helocmd, "\r\n");
  123. else
  124. asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
  125. /* initialize the MAIL command with optional FROM command */
  126. asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
  127. if (verbose && smtp_use_dummycmd)
  128. printf ("FROM CMD: %s", cmd_str);
  129. /* initialize alarm signal handling */
  130. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  131. /* set socket timeout */
  132. (void) alarm (socket_timeout);
  133. /* start timer */
  134. gettimeofday (&tv, NULL);
  135. /* try to connect to the host at the given port number */
  136. result = my_tcp_connect (server_address, server_port, &sd);
  137. if (result == STATE_OK) { /* we connected */
  138. /* watch for the SMTP connection string and */
  139. /* return a WARNING status if we couldn't read any data */
  140. if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
  141. printf (_("recv() failed\n"));
  142. result = STATE_WARNING;
  143. }
  144. else {
  145. if (verbose)
  146. printf ("%s", buffer);
  147. /* strip the buffer of carriage returns */
  148. strip (buffer);
  149. /* make sure we find the response we are looking for */
  150. if (!strstr (buffer, server_expect)) {
  151. if (server_port == SMTP_PORT)
  152. printf (_("Invalid SMTP response received from host\n"));
  153. else
  154. printf (_("Invalid SMTP response received from host on port %d\n"),
  155. server_port);
  156. result = STATE_WARNING;
  157. }
  158. }
  159. /* send the HELO/EHLO command */
  160. send(sd, helocmd, strlen(helocmd), 0);
  161. /* allow for response to helo command to reach us */
  162. if(read (sd, buffer, MAXBUF - 1) < 0){
  163. printf (_("recv() failed\n"));
  164. return STATE_WARNING;
  165. } else if(use_ehlo){
  166. buffer[MAXBUF-1]='\0';
  167. if(strstr(buffer, "250 STARTTLS") != NULL ||
  168. strstr(buffer, "250-STARTTLS") != NULL){
  169. supports_tls=TRUE;
  170. }
  171. }
  172. if(use_ssl && ! supports_tls){
  173. printf(_("WARNING - TLS not supported by server\n"));
  174. send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
  175. return STATE_WARNING;
  176. }
  177. #ifdef HAVE_SSL
  178. if(use_ssl) {
  179. /* send the STARTTLS command */
  180. send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
  181. recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); /* wait for it */
  182. if (!strstr (buffer, server_expect)) {
  183. printf (_("Server does not support STARTTLS\n"));
  184. send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
  185. return STATE_UNKNOWN;
  186. }
  187. result = np_net_ssl_init(sd);
  188. if(result != STATE_OK) {
  189. printf (_("CRITICAL - Cannot create SSL context.\n"));
  190. np_net_ssl_cleanup();
  191. close(sd);
  192. return STATE_CRITICAL;
  193. } else {
  194. ssl_established = 1;
  195. }
  196. # ifdef USE_OPENSSL
  197. if ( check_cert ) {
  198. result = np_net_ssl_check_cert(days_till_exp);
  199. if(result != STATE_OK){
  200. printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
  201. }
  202. my_close();
  203. return result;
  204. }
  205. # endif /* USE_OPENSSL */
  206. }
  207. #endif
  208. /* sendmail will syslog a "NOQUEUE" error if session does not attempt
  209. * to do something useful. This can be prevented by giving a command
  210. * even if syntax is illegal (MAIL requires a FROM:<...> argument)
  211. *
  212. * According to rfc821 you can include a null reversepath in the from command
  213. * - but a log message is generated on the smtp server.
  214. *
  215. * You can disable sending mail_command with '--nocommand'
  216. * Use the -f option to provide a FROM address
  217. */
  218. if (smtp_use_dummycmd) {
  219. my_send(cmd_str, strlen(cmd_str));
  220. my_recv(buffer, MAX_INPUT_BUFFER-1);
  221. if (verbose)
  222. printf("%s", buffer);
  223. }
  224. while (n < ncommands) {
  225. asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
  226. my_send(cmd_str, strlen(cmd_str));
  227. my_recv(buffer, MAX_INPUT_BUFFER-1);
  228. if (verbose)
  229. printf("%s", buffer);
  230. strip (buffer);
  231. if (n < nresponses) {
  232. #ifdef HAVE_REGEX_H
  233. cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  234. errcode = regcomp (&preg, responses[n], cflags);
  235. if (errcode != 0) {
  236. regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  237. printf (_("Could Not Compile Regular Expression"));
  238. return ERROR;
  239. }
  240. excode = regexec (&preg, buffer, 10, pmatch, eflags);
  241. if (excode == 0) {
  242. result = STATE_OK;
  243. }
  244. else if (excode == REG_NOMATCH) {
  245. result = STATE_WARNING;
  246. printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
  247. }
  248. else {
  249. regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
  250. printf (_("Execute Error: %s\n"), errbuf);
  251. result = STATE_UNKNOWN;
  252. }
  253. #else
  254. if (strstr(buffer, responses[n])!=buffer) {
  255. result = STATE_WARNING;
  256. printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
  257. }
  258. #endif
  259. }
  260. n++;
  261. }
  262. /* tell the server we're done */
  263. my_send (SMTP_QUIT, strlen (SMTP_QUIT));
  264. /* finally close the connection */
  265. close (sd);
  266. }
  267. /* reset the alarm */
  268. alarm (0);
  269. microsec = deltime (tv);
  270. elapsed_time = (double)microsec / 1.0e6;
  271. if (result == STATE_OK) {
  272. if (check_critical_time && elapsed_time > (double) critical_time)
  273. result = STATE_CRITICAL;
  274. else if (check_warning_time && elapsed_time > (double) warning_time)
  275. result = STATE_WARNING;
  276. }
  277. printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
  278. state_text (result), elapsed_time,
  279. verbose?", ":"", verbose?buffer:"",
  280. fperfdata ("time", elapsed_time, "s",
  281. (int)check_warning_time, warning_time,
  282. (int)check_critical_time, critical_time,
  283. TRUE, 0, FALSE, 0));
  284. return result;
  285. }
  286. /* process command-line arguments */
  287. int
  288. process_arguments (int argc, char **argv)
  289. {
  290. int c;
  291. int option = 0;
  292. static struct option longopts[] = {
  293. {"hostname", required_argument, 0, 'H'},
  294. {"expect", required_argument, 0, 'e'},
  295. {"critical", required_argument, 0, 'c'},
  296. {"warning", required_argument, 0, 'w'},
  297. {"timeout", required_argument, 0, 't'},
  298. {"port", required_argument, 0, 'p'},
  299. {"from", required_argument, 0, 'f'},
  300. {"fqdn", required_argument, 0, 'F'},
  301. {"command", required_argument, 0, 'C'},
  302. {"response", required_argument, 0, 'R'},
  303. {"nocommand", required_argument, 0, 'n'},
  304. {"verbose", no_argument, 0, 'v'},
  305. {"version", no_argument, 0, 'V'},
  306. {"use-ipv4", no_argument, 0, '4'},
  307. {"use-ipv6", no_argument, 0, '6'},
  308. {"help", no_argument, 0, 'h'},
  309. {"starttls",no_argument,0,'S'},
  310. {"certificate",required_argument,0,'D'},
  311. {0, 0, 0, 0}
  312. };
  313. if (argc < 2)
  314. return ERROR;
  315. for (c = 1; c < argc; c++) {
  316. if (strcmp ("-to", argv[c]) == 0)
  317. strcpy (argv[c], "-t");
  318. else if (strcmp ("-wt", argv[c]) == 0)
  319. strcpy (argv[c], "-w");
  320. else if (strcmp ("-ct", argv[c]) == 0)
  321. strcpy (argv[c], "-c");
  322. }
  323. while (1) {
  324. c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:",
  325. longopts, &option);
  326. if (c == -1 || c == EOF)
  327. break;
  328. switch (c) {
  329. case 'H': /* hostname */
  330. if (is_host (optarg)) {
  331. server_address = optarg;
  332. }
  333. else {
  334. usage2 (_("Invalid hostname/address"), optarg);
  335. }
  336. break;
  337. case 'p': /* port */
  338. if (is_intpos (optarg))
  339. server_port = atoi (optarg);
  340. else
  341. usage4 (_("Port must be a positive integer"));
  342. break;
  343. case 'F':
  344. /* localhostname */
  345. localhostname = strdup(optarg);
  346. break;
  347. case 'f': /* from argument */
  348. from_arg = optarg;
  349. smtp_use_dummycmd = 1;
  350. break;
  351. case 'e': /* server expect string on 220 */
  352. server_expect = optarg;
  353. break;
  354. case 'C': /* commands */
  355. if (ncommands >= command_size) {
  356. commands = realloc (commands, command_size+8);
  357. if (commands == NULL)
  358. die (STATE_UNKNOWN,
  359. _("Could not realloc() units [%d]\n"), ncommands);
  360. }
  361. commands[ncommands] = optarg;
  362. ncommands++;
  363. break;
  364. case 'R': /* server responses */
  365. if (nresponses >= response_size) {
  366. responses = realloc (responses, response_size+8);
  367. if (responses == NULL)
  368. die (STATE_UNKNOWN,
  369. _("Could not realloc() units [%d]\n"), nresponses);
  370. }
  371. responses[nresponses] = optarg;
  372. nresponses++;
  373. break;
  374. case 'c': /* critical time threshold */
  375. if (is_intnonneg (optarg)) {
  376. critical_time = atoi (optarg);
  377. check_critical_time = TRUE;
  378. }
  379. else {
  380. usage4 (_("Critical time must be a positive integer"));
  381. }
  382. break;
  383. case 'w': /* warning time threshold */
  384. if (is_intnonneg (optarg)) {
  385. warning_time = atoi (optarg);
  386. check_warning_time = TRUE;
  387. }
  388. else {
  389. usage4 (_("Warning time must be a positive integer"));
  390. }
  391. break;
  392. case 'v': /* verbose */
  393. verbose++;
  394. break;
  395. case 't': /* timeout */
  396. if (is_intnonneg (optarg)) {
  397. socket_timeout = atoi (optarg);
  398. }
  399. else {
  400. usage4 (_("Timeout interval must be a positive integer"));
  401. }
  402. break;
  403. case 'S':
  404. /* starttls */
  405. use_ssl = TRUE;
  406. use_ehlo = TRUE;
  407. break;
  408. case 'D':
  409. /* Check SSL cert validity */
  410. #ifdef USE_OPENSSL
  411. if (!is_intnonneg (optarg))
  412. usage2 ("Invalid certificate expiration period",optarg);
  413. days_till_exp = atoi (optarg);
  414. check_cert = TRUE;
  415. #else
  416. usage (_("SSL support not available - install OpenSSL and recompile"));
  417. #endif
  418. break;
  419. case '4':
  420. address_family = AF_INET;
  421. break;
  422. case '6':
  423. #ifdef USE_IPV6
  424. address_family = AF_INET6;
  425. #else
  426. usage4 (_("IPv6 support not available"));
  427. #endif
  428. break;
  429. case 'V': /* version */
  430. print_revision (progname, revision);
  431. exit (STATE_OK);
  432. case 'h': /* help */
  433. print_help ();
  434. exit (STATE_OK);
  435. case '?': /* help */
  436. usage2 (_("Unknown argument"), optarg);
  437. }
  438. }
  439. c = optind;
  440. if (server_address == NULL) {
  441. if (argv[c]) {
  442. if (is_host (argv[c]))
  443. server_address = argv[c];
  444. else
  445. usage2 (_("Invalid hostname/address"), argv[c]);
  446. }
  447. else {
  448. asprintf (&server_address, "127.0.0.1");
  449. }
  450. }
  451. if (server_expect == NULL)
  452. server_expect = strdup (SMTP_EXPECT);
  453. if (mail_command == NULL)
  454. mail_command = strdup("MAIL ");
  455. if (from_arg==NULL)
  456. from_arg = strdup(" ");
  457. return validate_arguments ();
  458. }
  459. int
  460. validate_arguments (void)
  461. {
  462. return OK;
  463. }
  464. void
  465. print_help (void)
  466. {
  467. char *myport;
  468. asprintf (&myport, "%d", SMTP_PORT);
  469. print_revision (progname, revision);
  470. printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
  471. printf (COPYRIGHT, copyright, email);
  472. printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
  473. print_usage ();
  474. printf (_(UT_HELP_VRSN));
  475. printf (_(UT_HOST_PORT), 'p', myport);
  476. printf (_(UT_IPv46));
  477. printf (_("\
  478. -e, --expect=STRING\n\
  479. String to expect in first line of server response (default: '%s')\n\
  480. -n, nocommand\n\
  481. Suppress SMTP command\n\
  482. -C, --command=STRING\n\
  483. SMTP command (may be used repeatedly)\n\
  484. -R, --command=STRING\n\
  485. Expected response to command (may be used repeatedly)\n\
  486. -f, --from=STRING\n\
  487. FROM-address to include in MAIL command, required by Exchange 2000\n"),
  488. SMTP_EXPECT);
  489. #ifdef HAVE_SSL
  490. printf (_("\
  491. -D, --certificate=INTEGER\n\
  492. Minimum number of days a certificate has to be valid.\n\
  493. -S, --starttls\n\
  494. Use STARTTLS for the connection.\n"));
  495. #endif
  496. printf (_(UT_WARN_CRIT));
  497. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  498. printf (_(UT_VERBOSE));
  499. printf(_("\n\
  500. Successul connects return STATE_OK, refusals and timeouts return\n\
  501. STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
  502. connects, but incorrect reponse messages from the host result in\n\
  503. STATE_WARNING return values.\n"));
  504. printf (_(UT_SUPPORT));
  505. }
  506. void
  507. print_usage (void)
  508. {
  509. printf ("\
  510. Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
  511. [-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
  512. }
  513. int
  514. my_close (void)
  515. {
  516. #ifdef HAVE_SSL
  517. np_net_ssl_cleanup();
  518. #endif
  519. return close(sd);
  520. }