check_http.c 31 KB

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