check_http.c 30 KB

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