check_http.c 29 KB

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