check_http.c 31 KB

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