4
0

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