check_http.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. ******************************************************************************/
  14. /* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */
  15. const char *progname = "check_http";
  16. const char *revision = "$Revision$";
  17. const char *copyright = "1999-2001";
  18. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  19. #include "common.h"
  20. #include "netutils.h"
  21. #include "utils.h"
  22. #define HTTP_EXPECT "HTTP/1."
  23. enum {
  24. MAX_IPV4_HOSTLENGTH = 255,
  25. HTTP_PORT = 80,
  26. HTTPS_PORT = 443
  27. };
  28. #ifdef HAVE_SSL_H
  29. #include <rsa.h>
  30. #include <crypto.h>
  31. #include <x509.h>
  32. #include <pem.h>
  33. #include <ssl.h>
  34. #include <err.h>
  35. #include <rand.h>
  36. #else
  37. # ifdef HAVE_OPENSSL_SSL_H
  38. # include <openssl/rsa.h>
  39. # include <openssl/crypto.h>
  40. # include <openssl/x509.h>
  41. # include <openssl/pem.h>
  42. # include <openssl/ssl.h>
  43. # include <openssl/err.h>
  44. # include <openssl/rand.h>
  45. # endif
  46. #endif
  47. #ifdef HAVE_SSL
  48. int check_cert = FALSE;
  49. int days_till_exp;
  50. char *randbuff;
  51. SSL_CTX *ctx;
  52. SSL *ssl;
  53. X509 *server_cert;
  54. int connect_SSL (void);
  55. int check_certificate (X509 **);
  56. #endif
  57. #ifdef HAVE_REGEX_H
  58. enum {
  59. REGS = 2,
  60. MAX_RE_SIZE = 256
  61. };
  62. #include <regex.h>
  63. regex_t preg;
  64. regmatch_t pmatch[REGS];
  65. char regexp[MAX_RE_SIZE];
  66. char errbuf[MAX_INPUT_BUFFER];
  67. int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
  68. int errcode;
  69. #endif
  70. struct timeval tv;
  71. #define HTTP_URL "/"
  72. #define CRLF "\r\n"
  73. char timestamp[17] = "";
  74. int specify_port = FALSE;
  75. int server_port = HTTP_PORT;
  76. char server_port_text[6] = "";
  77. char server_type[6] = "http";
  78. char *server_address;
  79. char *host_name;
  80. char *server_url;
  81. char *user_agent;
  82. int server_url_length;
  83. int server_expect_yn = 0;
  84. char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
  85. char string_expect[MAX_INPUT_BUFFER] = "";
  86. double warning_time = 0;
  87. int check_warning_time = FALSE;
  88. double critical_time = 0;
  89. int check_critical_time = FALSE;
  90. char user_auth[MAX_INPUT_BUFFER] = "";
  91. int display_html = FALSE;
  92. int onredirect = STATE_OK;
  93. int use_ssl = FALSE;
  94. int verbose = FALSE;
  95. int sd;
  96. int min_page_len = 0;
  97. int redir_depth = 0;
  98. int max_depth = 15;
  99. char *http_method;
  100. char *http_post_data;
  101. char buffer[MAX_INPUT_BUFFER];
  102. int process_arguments (int, char **);
  103. static char *base64 (const char *bin, size_t len);
  104. int check_http (void);
  105. void redir (char *pos, char *status_line);
  106. int server_type_check(const char *type);
  107. int server_port_check(int ssl_flag);
  108. char *perfd_time (long microsec);
  109. int my_recv (void);
  110. int my_close (void);
  111. void print_help (void);
  112. void print_usage (void);
  113. int
  114. main (int argc, char **argv)
  115. {
  116. int result = STATE_UNKNOWN;
  117. /* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */
  118. server_url = strdup(HTTP_URL);
  119. server_url_length = strlen(server_url);
  120. asprintf (&user_agent, "User-Agent: check_http/%s (nagios-plugins %s)",
  121. clean_revstring (revision), VERSION);
  122. if (process_arguments (argc, argv) == ERROR)
  123. usage (_("check_http: could not parse arguments\n"));
  124. if (strstr (timestamp, ":")) {
  125. if (strstr (server_url, "?"))
  126. asprintf (&server_url, "%s&%s", server_url, timestamp);
  127. else
  128. asprintf (&server_url, "%s?%s", server_url, timestamp);
  129. }
  130. if (display_html == TRUE)
  131. printf ("<A HREF=\"http://%s:%d%s\" target=\"_blank\">",
  132. host_name, server_port, server_url);
  133. /* initialize alarm signal handling, set socket timeout, start timer */
  134. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  135. (void) alarm (socket_timeout);
  136. gettimeofday (&tv, NULL);
  137. #ifdef HAVE_SSL
  138. if (use_ssl && check_cert == TRUE) {
  139. if (connect_SSL () != OK)
  140. die (STATE_CRITICAL, _("HTTP CRITICAL - Could not make SSL connection\n"));
  141. if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
  142. result = check_certificate (&server_cert);
  143. X509_free (server_cert);
  144. }
  145. else {
  146. printf (_("ERROR: Cannot retrieve server certificate.\n"));
  147. result = STATE_CRITICAL;
  148. }
  149. SSL_shutdown (ssl);
  150. SSL_free (ssl);
  151. SSL_CTX_free (ctx);
  152. close (sd);
  153. }
  154. else {
  155. result = check_http ();
  156. }
  157. #else
  158. result = check_http ();
  159. #endif
  160. return result;
  161. }
  162. /* process command-line arguments */
  163. int
  164. process_arguments (int argc, char **argv)
  165. {
  166. int c = 1;
  167. int option = 0;
  168. static struct option longopts[] = {
  169. STD_LONG_OPTS,
  170. {"file",required_argument,0,'F'},
  171. {"link", no_argument, 0, 'L'},
  172. {"nohtml", no_argument, 0, 'n'},
  173. {"ssl", no_argument, 0, 'S'},
  174. {"verbose", no_argument, 0, 'v'},
  175. {"post", required_argument, 0, 'P'},
  176. {"IP-address", required_argument, 0, 'I'},
  177. {"string", required_argument, 0, 's'},
  178. {"regex", required_argument, 0, 'r'},
  179. {"ereg", required_argument, 0, 'r'},
  180. {"eregi", required_argument, 0, 'R'},
  181. {"linespan", no_argument, 0, 'l'},
  182. {"onredirect", required_argument, 0, 'f'},
  183. {"certificate", required_argument, 0, 'C'},
  184. {"min", required_argument, 0, 'm'},
  185. {"use-ipv4", no_argument, 0, '4'},
  186. {"use-ipv6", no_argument, 0, '6'},
  187. {0, 0, 0, 0}
  188. };
  189. if (argc < 2)
  190. return ERROR;
  191. for (c = 1; c < argc; c++) {
  192. if (strcmp ("-to", argv[c]) == 0)
  193. strcpy (argv[c], "-t");
  194. if (strcmp ("-hn", argv[c]) == 0)
  195. strcpy (argv[c], "-H");
  196. if (strcmp ("-wt", argv[c]) == 0)
  197. strcpy (argv[c], "-w");
  198. if (strcmp ("-ct", argv[c]) == 0)
  199. strcpy (argv[c], "-c");
  200. if (strcmp ("-nohtml", argv[c]) == 0)
  201. strcpy (argv[c], "-n");
  202. }
  203. while (1) {
  204. c = getopt_long (argc, argv, "Vvh46t:c:w:H:P:I:a:e:p:s:R:r:u:f:C:nlLSm:", longopts, &option);
  205. if (c == -1 || c == EOF)
  206. break;
  207. switch (c) {
  208. case '?': /* usage */
  209. usage3 (_("unknown argument"), optopt);
  210. break;
  211. case 'h': /* help */
  212. print_help ();
  213. exit (STATE_OK);
  214. break;
  215. case 'V': /* version */
  216. print_revision (progname, revision);
  217. exit (STATE_OK);
  218. break;
  219. case 't': /* timeout period */
  220. if (!is_intnonneg (optarg))
  221. usage2 (_("timeout interval must be a non-negative integer"), optarg);
  222. else
  223. socket_timeout = atoi (optarg);
  224. break;
  225. case 'c': /* critical time threshold */
  226. if (!is_intnonneg (optarg))
  227. usage2 (_("invalid critical threshold"), optarg);
  228. else {
  229. critical_time = strtod (optarg, NULL);
  230. check_critical_time = TRUE;
  231. }
  232. break;
  233. case 'w': /* warning time threshold */
  234. if (!is_intnonneg (optarg))
  235. usage2 (_("invalid warning threshold"), optarg);
  236. else {
  237. warning_time = strtod (optarg, NULL);
  238. check_warning_time = TRUE;
  239. }
  240. break;
  241. case 'L': /* show html link */
  242. display_html = TRUE;
  243. break;
  244. case 'n': /* do not show html link */
  245. display_html = FALSE;
  246. break;
  247. case 'S': /* use SSL */
  248. #ifndef HAVE_SSL
  249. usage (_("check_http: invalid option - SSL is not available\n"));
  250. #endif
  251. use_ssl = TRUE;
  252. if (specify_port == FALSE)
  253. server_port = HTTPS_PORT;
  254. break;
  255. case 'C': /* Check SSL cert validity */
  256. #ifdef HAVE_SSL
  257. if (!is_intnonneg (optarg))
  258. usage2 (_("invalid certificate expiration period"), optarg);
  259. else {
  260. days_till_exp = atoi (optarg);
  261. check_cert = TRUE;
  262. }
  263. #else
  264. usage (_("check_http: invalid option - SSL is not available\n"));
  265. #endif
  266. break;
  267. case 'f': /* onredirect */
  268. if (!strcmp (optarg, "follow"))
  269. onredirect = STATE_DEPENDENT;
  270. if (!strcmp (optarg, "unknown"))
  271. onredirect = STATE_UNKNOWN;
  272. if (!strcmp (optarg, "ok"))
  273. onredirect = STATE_OK;
  274. if (!strcmp (optarg, "warning"))
  275. onredirect = STATE_WARNING;
  276. if (!strcmp (optarg, "critical"))
  277. onredirect = STATE_CRITICAL;
  278. if (verbose)
  279. printf(_("option f:%d \n"), onredirect);
  280. break;
  281. /* Note: H, I, and u must be malloc'd or will fail on redirects */
  282. case 'H': /* Host Name (virtual host) */
  283. host_name = strdup (optarg);
  284. break;
  285. case 'I': /* Server IP-address */
  286. server_address = strdup (optarg);
  287. break;
  288. case 'u': /* URL path */
  289. server_url = strdup (optarg);
  290. server_url_length = strlen (server_url);
  291. break;
  292. case 'p': /* Server port */
  293. if (!is_intnonneg (optarg))
  294. usage2 (_("invalid port number"), optarg);
  295. else {
  296. server_port = atoi (optarg);
  297. specify_port = TRUE;
  298. }
  299. break;
  300. case 'a': /* authorization info */
  301. strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
  302. user_auth[MAX_INPUT_BUFFER - 1] = 0;
  303. break;
  304. case 'P': /* HTTP POST data in URL encoded format */
  305. if (http_method || http_post_data) break;
  306. http_method = strdup("POST");
  307. http_post_data = strdup (optarg);
  308. break;
  309. case 's': /* string or substring */
  310. strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
  311. string_expect[MAX_INPUT_BUFFER - 1] = 0;
  312. break;
  313. case 'e': /* string or substring */
  314. strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
  315. server_expect[MAX_INPUT_BUFFER - 1] = 0;
  316. server_expect_yn = 1;
  317. break;
  318. #ifndef HAVE_REGEX_H
  319. case 'l': /* linespan */
  320. case 'r': /* linespan */
  321. case 'R': /* linespan */
  322. usage (_("check_http: call for regex which was not a compiled option\n"));
  323. break;
  324. #else
  325. case 'l': /* linespan */
  326. cflags &= ~REG_NEWLINE;
  327. break;
  328. case 'R': /* regex */
  329. cflags |= REG_ICASE;
  330. case 'r': /* regex */
  331. strncpy (regexp, optarg, MAX_RE_SIZE - 1);
  332. regexp[MAX_RE_SIZE - 1] = 0;
  333. errcode = regcomp (&preg, regexp, cflags);
  334. if (errcode != 0) {
  335. (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  336. printf (_("Could Not Compile Regular Expression: %s"), errbuf);
  337. return ERROR;
  338. }
  339. break;
  340. #endif
  341. case '4':
  342. address_family = AF_INET;
  343. break;
  344. case '6':
  345. #ifdef USE_IPV6
  346. address_family = AF_INET6;
  347. #else
  348. usage (_("IPv6 support not available\n"));
  349. #endif
  350. break;
  351. case 'v': /* verbose */
  352. verbose = TRUE;
  353. break;
  354. case 'm': /* min_page_length */
  355. min_page_len = atoi (optarg);
  356. break;
  357. }
  358. }
  359. c = optind;
  360. if (server_address == NULL && c < argc)
  361. server_address = strdup (argv[c++]);
  362. if (host_name == NULL && c < argc)
  363. host_name = strdup (argv[c++]);
  364. if (server_address == NULL) {
  365. if (host_name == NULL)
  366. usage (_("check_http: you must specify a server address or host name\n"));
  367. else
  368. server_address = strdup (host_name);
  369. }
  370. if (check_critical_time && critical_time>(double)socket_timeout)
  371. socket_timeout = (int)critical_time + 1;
  372. if (http_method == NULL)
  373. http_method = strdup ("GET");
  374. return TRUE;
  375. }
  376. /* written by lauri alanko */
  377. static char *
  378. base64 (const char *bin, size_t len)
  379. {
  380. char *buf = (char *) malloc ((len + 2) / 3 * 4 + 1);
  381. size_t i = 0, j = 0;
  382. char BASE64_END = '=';
  383. char base64_table[64];
  384. strncpy (base64_table, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 64);
  385. while (j < len - 2) {
  386. buf[i++] = base64_table[bin[j] >> 2];
  387. buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
  388. buf[i++] = base64_table[((bin[j + 1] & 15) << 2) | (bin[j + 2] >> 6)];
  389. buf[i++] = base64_table[bin[j + 2] & 63];
  390. j += 3;
  391. }
  392. switch (len - j) {
  393. case 1:
  394. buf[i++] = base64_table[bin[j] >> 2];
  395. buf[i++] = base64_table[(bin[j] & 3) << 4];
  396. buf[i++] = BASE64_END;
  397. buf[i++] = BASE64_END;
  398. break;
  399. case 2:
  400. buf[i++] = base64_table[bin[j] >> 2];
  401. buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
  402. buf[i++] = base64_table[(bin[j + 1] & 15) << 2];
  403. buf[i++] = BASE64_END;
  404. break;
  405. case 0:
  406. break;
  407. }
  408. buf[i] = '\0';
  409. return buf;
  410. }
  411. int
  412. check_http (void)
  413. {
  414. char *msg;
  415. char *status_line;
  416. char *header;
  417. char *page;
  418. char *auth;
  419. int i = 0;
  420. size_t pagesize = 0;
  421. char *full_page;
  422. char *buf;
  423. char *pos;
  424. long microsec;
  425. double elapsed_time;
  426. int page_len = 0;
  427. #ifdef HAVE_SSL
  428. int sslerr;
  429. #endif
  430. /* try to connect to the host at the given port number */
  431. #ifdef HAVE_SSL
  432. if (use_ssl == TRUE) {
  433. if (connect_SSL () != OK) {
  434. die (STATE_CRITICAL, _("Unable to open TCP socket\n"));
  435. }
  436. if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
  437. X509_free (server_cert);
  438. }
  439. else {
  440. printf (_("ERROR: Cannot retrieve server certificate.\n"));
  441. return STATE_CRITICAL;
  442. }
  443. }
  444. else {
  445. #endif
  446. if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
  447. die (STATE_CRITICAL, _("Unable to open TCP socket\n"));
  448. #ifdef HAVE_SSL
  449. }
  450. #endif
  451. asprintf (&buf, "%s %s HTTP/1.0\r\n%s\r\n", http_method, server_url, user_agent);
  452. /* optionally send the host header info */
  453. if (host_name)
  454. asprintf (&buf, "%sHost: %s\r\n", buf, host_name);
  455. /* optionally send the authentication info */
  456. if (strlen(user_auth)) {
  457. auth = base64 (user_auth, strlen (user_auth));
  458. asprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth);
  459. }
  460. /* either send http POST data */
  461. if (http_post_data) {
  462. asprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf);
  463. asprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, strlen (http_post_data));
  464. asprintf (&buf, "%s%s%s", buf, http_post_data, CRLF);
  465. }
  466. else {
  467. /* or just a newline so the server knows we're done with the request */
  468. asprintf (&buf, "%s%s", buf, CRLF);
  469. }
  470. if (verbose)
  471. printf ("%s\n", buf);
  472. #ifdef HAVE_SSL
  473. if (use_ssl == TRUE) {
  474. if (SSL_write (ssl, buf, (int)strlen(buf)) == -1) {
  475. ERR_print_errors_fp (stderr);
  476. return STATE_CRITICAL;
  477. }
  478. }
  479. else {
  480. #endif
  481. send (sd, buf, strlen (buf), 0);
  482. #ifdef HAVE_SSL
  483. }
  484. #endif
  485. /* fetch the page */
  486. full_page = strdup("");
  487. while ((i = my_recv ()) > 0) {
  488. buffer[i] = '\0';
  489. asprintf (&full_page, "%s%s", full_page, buffer);
  490. pagesize += i;
  491. }
  492. if (i < 0 && errno != ECONNRESET) {
  493. #ifdef HAVE_SSL
  494. if (use_ssl) {
  495. sslerr=SSL_get_error(ssl, i);
  496. if ( sslerr == SSL_ERROR_SSL ) {
  497. die (STATE_WARNING, _("Client Certificate Required\n"));
  498. } else {
  499. die (STATE_CRITICAL, _("Error in recv()\n"));
  500. }
  501. }
  502. else {
  503. #endif
  504. die (STATE_CRITICAL, _("Error in recv()\n"));
  505. #ifdef HAVE_SSL
  506. }
  507. #endif
  508. }
  509. /* return a CRITICAL status if we couldn't read any data */
  510. if (pagesize == (size_t) 0)
  511. die (STATE_CRITICAL, _("No data received %s\n"), timestamp);
  512. /* close the connection */
  513. my_close ();
  514. /* reset the alarm */
  515. alarm (0);
  516. /* leave full_page untouched so we can free it later */
  517. page = full_page;
  518. if (verbose)
  519. printf ("%s://%s:%d%s is %d characters\n", server_type, server_address, server_port, server_url, pagesize);
  520. /* find status line and null-terminate it */
  521. status_line = page;
  522. page += (size_t) strcspn (page, "\r\n");
  523. pos = page;
  524. page += (size_t) strspn (page, "\r\n");
  525. status_line[strcspn(status_line, "\r\n")] = 0;
  526. strip (status_line);
  527. if (verbose)
  528. printf ("STATUS: %s\n", status_line);
  529. /* find header info and null-terminate it */
  530. header = page;
  531. while (strcspn (page, "\r\n") > 0) {
  532. page += (size_t) strcspn (page, "\r\n");
  533. pos = page;
  534. if ((strspn (page, "\r") == 1 && strspn (page, "\r\n") >= 2) ||
  535. (strspn (page, "\n") == 1 && strspn (page, "\r\n") >= 2))
  536. page += (size_t) 2;
  537. else
  538. page += (size_t) 1;
  539. }
  540. page += (size_t) strspn (page, "\r\n");
  541. header[pos - header] = 0;
  542. if (verbose)
  543. printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, page);
  544. /* make sure the status line matches the response we are looking for */
  545. if (!strstr (status_line, server_expect)) {
  546. if (server_port == HTTP_PORT)
  547. asprintf (&msg, _("Invalid HTTP response received from host\n"));
  548. else
  549. asprintf (&msg,
  550. _("Invalid HTTP response received from host on port %d\n"),
  551. server_port);
  552. die (STATE_CRITICAL, "%s", msg);
  553. }
  554. /* Exit here if server_expect was set by user and not default */
  555. if ( server_expect_yn ) {
  556. asprintf (&msg, _("HTTP OK: Status line output matched \"%s\"\n"),
  557. server_expect);
  558. if (verbose)
  559. printf ("%s\n",msg);
  560. }
  561. else {
  562. /* check the return code */
  563. /* server errors result in a critical state */
  564. if (strstr (status_line, "500") || strstr (status_line, "501") ||
  565. strstr (status_line, "502") || strstr (status_line, "503") ||
  566. strstr (status_line, "504") || strstr (status_line, "505")) {
  567. die (STATE_CRITICAL, _("HTTP CRITICAL: %s\n"), status_line);
  568. }
  569. /* client errors result in a warning state */
  570. if (strstr (status_line, "400") || strstr (status_line, "401") ||
  571. strstr (status_line, "402") || strstr (status_line, "403") ||
  572. strstr (status_line, "404") || strstr (status_line, "405") ||
  573. strstr (status_line, "406") || strstr (status_line, "407") ||
  574. strstr (status_line, "408") || strstr (status_line, "409") ||
  575. strstr (status_line, "410") || strstr (status_line, "411") ||
  576. strstr (status_line, "412") || strstr (status_line, "413") ||
  577. strstr (status_line, "414") || strstr (status_line, "415") ||
  578. strstr (status_line, "416") || strstr (status_line, "417")) {
  579. die (STATE_WARNING, _("HTTP WARNING: %s\n"), status_line);
  580. }
  581. /* check redirected page if specified */
  582. if (strstr (status_line, "300") || strstr (status_line, "301") ||
  583. strstr (status_line, "302") || strstr (status_line, "303") ||
  584. strstr (status_line, "304") || strstr (status_line, "305") ||
  585. strstr (status_line, "306")) {
  586. if (onredirect == STATE_DEPENDENT)
  587. redir (header, status_line);
  588. else if (onredirect == STATE_UNKNOWN)
  589. printf (_("UNKNOWN"));
  590. else if (onredirect == STATE_OK)
  591. printf (_("OK"));
  592. else if (onredirect == STATE_WARNING)
  593. printf (_("WARNING"));
  594. else if (onredirect == STATE_CRITICAL)
  595. printf (_("CRITICAL"));
  596. microsec = deltime (tv);
  597. elapsed_time = (double)microsec / 1.0e6;
  598. die (onredirect,
  599. _(" - %s - %.3f second response time %s%s|%s size=%dB\n"),
  600. status_line, elapsed_time, timestamp,
  601. (display_html ? "</A>" : ""),
  602. perfd_time (microsec), pagesize);
  603. } /* end if (strstr (status_line, "30[0-4]") */
  604. } /* end else (server_expect_yn) */
  605. /* check elapsed time */
  606. microsec = deltime (tv);
  607. elapsed_time = (double)microsec / 1.0e6;
  608. asprintf (&msg,
  609. _("HTTP problem: %s - %.3f second response time %s%s|%s size=%dB\n"),
  610. status_line, elapsed_time, timestamp,
  611. (display_html ? "</A>" : ""),
  612. perfd_time (microsec), pagesize);
  613. if (check_critical_time == TRUE && elapsed_time > critical_time)
  614. die (STATE_CRITICAL, "%s", msg);
  615. if (check_warning_time == TRUE && elapsed_time > warning_time)
  616. die (STATE_WARNING, "%s", msg);
  617. /* Page and Header content checks go here */
  618. /* these checks should be last */
  619. if (strlen (string_expect)) {
  620. if (strstr (page, string_expect)) {
  621. printf (_("HTTP OK %s - %.3f second response time %s%s|%s size=%dB\n"),
  622. status_line, elapsed_time,
  623. timestamp, (display_html ? "</A>" : ""),
  624. perfd_time (microsec), pagesize);
  625. exit (STATE_OK);
  626. }
  627. else {
  628. printf (_("CRITICAL - string not found%s|%s size=%dB\n"),
  629. (display_html ? "</A>" : ""),
  630. perfd_time (microsec), pagesize);
  631. exit (STATE_CRITICAL);
  632. }
  633. }
  634. #ifdef HAVE_REGEX_H
  635. if (strlen (regexp)) {
  636. errcode = regexec (&preg, page, REGS, pmatch, 0);
  637. if (errcode == 0) {
  638. printf (_("HTTP OK %s - %.3f second response time %s%s|%s size=%dB\n"),
  639. status_line, elapsed_time,
  640. timestamp, (display_html ? "</A>" : ""),
  641. perfd_time (microsec), pagesize);
  642. exit (STATE_OK);
  643. }
  644. else {
  645. if (errcode == REG_NOMATCH) {
  646. printf (_("CRITICAL - pattern not found%s|%s size=%dB\n"),
  647. (display_html ? "</A>" : ""),
  648. perfd_time (microsec), pagesize);
  649. exit (STATE_CRITICAL);
  650. }
  651. else {
  652. regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  653. printf (_("CRITICAL - Execute Error: %s\n"), errbuf);
  654. exit (STATE_CRITICAL);
  655. }
  656. }
  657. }
  658. #endif
  659. /* make sure the page is of an appropriate size */
  660. page_len = strlen (page);
  661. if ((min_page_len > 0) && (page_len < min_page_len)) {
  662. printf (_("HTTP WARNING: page size too small%s|size=%i\n"),
  663. (display_html ? "</A>" : ""), page_len );
  664. exit (STATE_WARNING);
  665. }
  666. /* We only get here if all tests have been passed */
  667. asprintf (&msg, _("HTTP OK %s - %.3f second response time %s%s|%s size=%dB\n"),
  668. status_line, elapsed_time,
  669. timestamp, (display_html ? "</A>" : ""),
  670. perfd_time (microsec), pagesize);
  671. die (STATE_OK, "%s", msg);
  672. return STATE_UNKNOWN;
  673. }
  674. /* per RFC 2396 */
  675. #define HDR_LOCATION "%*[Ll]%*[Oo]%*[Cc]%*[Aa]%*[Tt]%*[Ii]%*[Oo]%*[Nn]: "
  676. #define URI_HTTP "%[HTPShtps]://"
  677. #define URI_HOST "%[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  678. #define URI_PORT ":%[0123456789]"
  679. #define URI_PATH "%[-_.!~*'();/?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  680. #define HD1 URI_HTTP URI_HOST URI_PORT URI_PATH
  681. #define HD2 URI_HTTP URI_HOST URI_PATH
  682. #define HD3 URI_HTTP URI_HOST URI_PORT
  683. #define HD4 URI_HTTP URI_HOST
  684. #define HD5 URI_PATH
  685. void
  686. redir (char *pos, char *status_line)
  687. {
  688. int i = 0;
  689. char *x;
  690. char xx[2];
  691. char type[6];
  692. char *addr;
  693. char port[6];
  694. char *url;
  695. addr = malloc (MAX_IPV4_HOSTLENGTH + 1);
  696. if (addr == NULL)
  697. die (STATE_UNKNOWN, _("ERROR: could not allocate addr\n"));
  698. url = malloc (strcspn (pos, "\r\n"));
  699. if (url == NULL)
  700. die (STATE_UNKNOWN, _("ERROR: could not allocate url\n"));
  701. while (pos) {
  702. if (sscanf (pos, "%[Ll]%*[Oo]%*[Cc]%*[Aa]%*[Tt]%*[Ii]%*[Oo]%*[Nn]:%n", xx, &i) < 1) {
  703. pos += (size_t) strcspn (pos, "\r\n");
  704. pos += (size_t) strspn (pos, "\r\n");
  705. if (strlen(pos) == 0)
  706. die (STATE_UNKNOWN,
  707. _("UNKNOWN - Could not find redirect location - %s%s\n"),
  708. status_line, (display_html ? "</A>" : ""));
  709. continue;
  710. }
  711. pos += i;
  712. pos += strspn (pos, " \t\r\n");
  713. url = realloc (url, strcspn (pos, "\r\n"));
  714. if (url == NULL)
  715. die (STATE_UNKNOWN, _("ERROR: could not allocate url\n"));
  716. /* URI_HTTP, URI_HOST, URI_PORT, URI_PATH */
  717. if (sscanf (pos, HD1, type, addr, port, url) == 4) {
  718. use_ssl = server_type_check (type);
  719. i = atoi (port);
  720. }
  721. /* URI_HTTP URI_HOST URI_PATH */
  722. else if (sscanf (pos, HD2, type, addr, url) == 3 ) {
  723. use_ssl = server_type_check (type);
  724. i = server_port_check (use_ssl);
  725. }
  726. /* URI_HTTP URI_HOST URI_PORT */
  727. else if(sscanf (pos, HD3, type, addr, port) == 3) {
  728. strcpy (url, HTTP_URL);
  729. use_ssl = server_type_check (type);
  730. i = atoi (port);
  731. }
  732. /* URI_HTTP URI_HOST */
  733. else if(sscanf (pos, HD4, type, addr) == 2) {
  734. strcpy (url, HTTP_URL);
  735. use_ssl = server_type_check (type);
  736. i = server_port_check (use_ssl);
  737. }
  738. /* URI_PATH */
  739. else if (sscanf (pos, HD5, url) == 1) {
  740. /* relative url */
  741. if ((url[0] != '/')) {
  742. if ((x = strrchr(url, '/')))
  743. *x = '\0';
  744. asprintf (&server_url, "%s/%s", server_url, url);
  745. }
  746. i = server_port;
  747. strcpy (type, server_type);
  748. strcpy (addr, host_name);
  749. }
  750. else {
  751. die (STATE_UNKNOWN,
  752. _("UNKNOWN - Could not parse redirect location - %s%s\n"),
  753. pos, (display_html ? "</A>" : ""));
  754. }
  755. break;
  756. } /* end while (pos) */
  757. if (++redir_depth > max_depth)
  758. die (STATE_WARNING,
  759. _("WARNING - maximum redirection depth %d exceeded - %s://%s:%d%s%s\n"),
  760. max_depth, type, addr, i, url, (display_html ? "</A>" : ""));
  761. if (server_port==i &&
  762. !strcmp(server_address, addr) &&
  763. (host_name && !strcmp(host_name, addr)) &&
  764. !strcmp(server_url, url))
  765. die (STATE_WARNING,
  766. _("WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
  767. type, addr, i, url, (display_html ? "</A>" : ""));
  768. server_port = i;
  769. strcpy (server_type, type);
  770. free (host_name);
  771. host_name = strdup (addr);
  772. free (server_address);
  773. server_address = strdup (addr);
  774. free (server_url);
  775. server_url = strdup (url);
  776. check_http ();
  777. }
  778. int
  779. server_type_check (const char *type)
  780. {
  781. if (strcmp (type, "https"))
  782. return FALSE;
  783. else
  784. return TRUE;
  785. }
  786. int
  787. server_port_check (int ssl_flag)
  788. {
  789. if (ssl_flag)
  790. return HTTPS_PORT;
  791. else
  792. return HTTP_PORT;
  793. }
  794. #ifdef HAVE_SSL
  795. int connect_SSL (void)
  796. {
  797. SSL_METHOD *meth;
  798. asprintf (&randbuff, "%s", "qwertyuiopasdfghjklqwertyuiopasdfghjkl");
  799. RAND_seed (randbuff, (int)strlen(randbuff));
  800. if (verbose)
  801. printf(_("SSL seeding: %s\n"), (RAND_status()==1 ? _("OK") : _("Failed")) );
  802. /* Initialize SSL context */
  803. SSLeay_add_ssl_algorithms ();
  804. meth = SSLv23_client_method ();
  805. SSL_load_error_strings ();
  806. if ((ctx = SSL_CTX_new (meth)) == NULL) {
  807. printf (_("CRITICAL - Cannot create SSL context.\n"));
  808. return STATE_CRITICAL;
  809. }
  810. /* Initialize alarm signal handling */
  811. signal (SIGALRM, socket_timeout_alarm_handler);
  812. /* Set socket timeout */
  813. alarm (socket_timeout);
  814. /* Save start time */
  815. gettimeofday (&tv, NULL);
  816. /* Make TCP connection */
  817. if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK) {
  818. /* Do the SSL handshake */
  819. if ((ssl = SSL_new (ctx)) != NULL) {
  820. SSL_set_cipher_list(ssl, "ALL");
  821. SSL_set_fd (ssl, sd);
  822. if (SSL_connect (ssl) != -1)
  823. return OK;
  824. ERR_print_errors_fp (stderr);
  825. }
  826. else {
  827. printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
  828. }
  829. SSL_free (ssl);
  830. }
  831. SSL_CTX_free (ctx);
  832. close (sd);
  833. return STATE_CRITICAL;
  834. }
  835. #endif
  836. #ifdef HAVE_SSL
  837. int
  838. check_certificate (X509 ** certificate)
  839. {
  840. ASN1_STRING *tm;
  841. int offset;
  842. struct tm stamp;
  843. int days_left;
  844. /* Retrieve timestamp of certificate */
  845. tm = X509_get_notAfter (*certificate);
  846. /* Generate tm structure to process timestamp */
  847. if (tm->type == V_ASN1_UTCTIME) {
  848. if (tm->length < 10) {
  849. printf (_("CRITICAL - Wrong time format in certificate.\n"));
  850. return STATE_CRITICAL;
  851. }
  852. else {
  853. stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
  854. if (stamp.tm_year < 50)
  855. stamp.tm_year += 100;
  856. offset = 0;
  857. }
  858. }
  859. else {
  860. if (tm->length < 12) {
  861. printf (_("CRITICAL - Wrong time format in certificate.\n"));
  862. return STATE_CRITICAL;
  863. }
  864. else {
  865. stamp.tm_year =
  866. (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
  867. (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
  868. stamp.tm_year -= 1900;
  869. offset = 2;
  870. }
  871. }
  872. stamp.tm_mon =
  873. (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
  874. stamp.tm_mday =
  875. (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
  876. stamp.tm_hour =
  877. (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
  878. stamp.tm_min =
  879. (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
  880. stamp.tm_sec = 0;
  881. stamp.tm_isdst = -1;
  882. days_left = (mktime (&stamp) - time (NULL)) / 86400;
  883. snprintf
  884. (timestamp, 17, "%02d/%02d/%04d %02d:%02d",
  885. stamp.tm_mon + 1,
  886. stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
  887. if (days_left > 0 && days_left <= days_till_exp) {
  888. printf (_("WARNING - Certificate expires in %d day(s) (%s).\n"), days_left, timestamp);
  889. return STATE_WARNING;
  890. }
  891. if (days_left < 0) {
  892. printf (_("CRITICAL - Certificate expired on %s.\n"), timestamp);
  893. return STATE_CRITICAL;
  894. }
  895. if (days_left == 0) {
  896. printf (_("WARNING - Certificate expires today (%s).\n"), timestamp);
  897. return STATE_WARNING;
  898. }
  899. printf (_("OK - Certificate will expire on %s.\n"), timestamp);
  900. return STATE_OK;
  901. }
  902. #endif
  903. char *perfd_time (long microsec)
  904. {
  905. perfdata ("time", microsec, "us",
  906. check_warning_time, (int)(1e6*warning_time),
  907. check_critical_time, (int)(1e6*critical_time),
  908. TRUE, 0, FALSE, 0);
  909. }
  910. int
  911. my_recv (void)
  912. {
  913. int i;
  914. #ifdef HAVE_SSL
  915. if (use_ssl) {
  916. i = SSL_read (ssl, buffer, MAX_INPUT_BUFFER - 1);
  917. }
  918. else {
  919. i = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
  920. }
  921. #else
  922. i = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
  923. #endif
  924. return i;
  925. }
  926. int
  927. my_close (void)
  928. {
  929. #ifdef HAVE_SSL
  930. if (use_ssl == TRUE) {
  931. SSL_shutdown (ssl);
  932. SSL_free (ssl);
  933. SSL_CTX_free (ctx);
  934. return 0;
  935. }
  936. else {
  937. #endif
  938. return close (sd);
  939. #ifdef HAVE_SSL
  940. }
  941. #endif
  942. }
  943. void
  944. print_help (void)
  945. {
  946. print_revision (progname, revision);
  947. printf (_("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"));
  948. printf (_(COPYRIGHT), copyright, email);
  949. printf (_("\
  950. This plugin tests the HTTP service on the specified host. It can test\n\
  951. normal (http) and secure (https) servers, follow redirects, search for\n\
  952. strings and regular expressions, check connection times, and report on\n\
  953. certificate expiration times.\n"));
  954. print_usage ();
  955. printf (_("NOTE: One or both of -H and -I must be specified\n"));
  956. printf (_(UT_HELP_VRSN));
  957. printf (_("\
  958. -H, --hostname=ADDRESS\n\
  959. Host name argument for servers using host headers (virtual host)\n\
  960. -I, --IP-address=ADDRESS\n\
  961. IP address or name (use numeric address if possible to bypass DNS lookup).\n\
  962. -p, --port=INTEGER\n\
  963. Port number (default: %d)\n"), HTTP_PORT);
  964. printf (_(UT_IPv46));
  965. #ifdef HAVE_SSL
  966. printf (_("\
  967. -S, --ssl\n\
  968. Connect via SSL\n\
  969. -C, --certificate=INTEGER\n\
  970. Minimum number of days a certificate has to be valid.\n\
  971. (when this option is used the url is not checked.)\n"));
  972. #endif
  973. printf (_("\
  974. -e, --expect=STRING\n\
  975. String to expect in first (status) line of server response (default: %s)\n\
  976. If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)\n\
  977. -s, --string=STRING\n\
  978. String to expect in the content\n\
  979. -u, --url=PATH\n\
  980. URL to GET or POST (default: /)\n\
  981. -P, --post=STRING\n\
  982. URL encoded http POST data\n"), HTTP_EXPECT);
  983. #ifdef HAVE_REGEX_H
  984. printf (_("\
  985. -l, --linespan\n\
  986. Allow regex to span newlines (must precede -r or -R)\n\
  987. -r, --regex, --ereg=STRING\n\
  988. Search page for regex STRING\n\
  989. -R, --eregi=STRING\n\
  990. Search page for case-insensitive regex STRING\n"));
  991. #endif
  992. printf (_("\
  993. -a, --authorization=AUTH_PAIR\n\
  994. Username:password on sites with basic authentication\n\
  995. -L, --link=URL\n\
  996. Wrap output in HTML link (obsoleted by urlize)\n\
  997. -f, --onredirect=<ok|warning|critical|follow>\n\
  998. How to handle redirected pages\n\
  999. -m, --min=INTEGER\n\
  1000. Minimum page size required (bytes)\n"));
  1001. printf (_(UT_WARN_CRIT));
  1002. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  1003. printf (_(UT_VERBOSE));
  1004. printf (_("\
  1005. This plugin will attempt to open an HTTP connection with the host. Successful\n\
  1006. connects return STATE_OK, refusals and timeouts return STATE_CRITICAL, other\n\
  1007. errors return STATE_UNKNOWN. Successful connects, but incorrect reponse\n\
  1008. messages from the host result in STATE_WARNING return values. If you are\n\
  1009. checking a virtual server that uses 'host headers' you must supply the FQDN\n\
  1010. (fully qualified domain name) as the [host_name] argument.\n"));
  1011. #ifdef HAVE_SSL
  1012. printf (_("\n\
  1013. This plugin can also check whether an SSL enabled web server is able to\n\
  1014. serve content (optionally within a specified time) or whether the X509 \n\
  1015. certificate is still valid for the specified number of days.\n"));
  1016. printf (_("\n\
  1017. CHECK CONTENT: check_http -w 5 -c 10 --ssl www.verisign.com\n\n\
  1018. When the 'www.verisign.com' server returns its content within 5 seconds, a\n\
  1019. STATE_OK will be returned. When the server returns its content but exceeds\n\
  1020. the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,\n\
  1021. a STATE_CRITICAL will be returned.\n\n"));
  1022. printf (_("\
  1023. CHECK CERTIFICATE: check_http www.verisign.com -C 14\n\n\
  1024. When the certificate of 'www.verisign.com' is valid for more than 14 days, a\n\
  1025. STATE_OK is returned. When the certificate is still valid, but for less than\n\
  1026. 14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when\n\
  1027. the certificate is expired.\n"));
  1028. #endif
  1029. printf (_(UT_SUPPORT));
  1030. }
  1031. void
  1032. print_usage (void)
  1033. {
  1034. printf (_("\
  1035. Usage: %s (-H <vhost> | -I <IP-address>) [-u <uri>] [-p <port>]\n\
  1036. [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L]\n\
  1037. [-a auth] [-f <ok | warn | critcal | follow>] [-e <expect>]\n\
  1038. [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n\
  1039. [-P string] [-m min_pg_size] [-4|-6]\n"), progname);
  1040. printf (_(UT_HLP_VRS), progname, progname);
  1041. }