check_http.c 31 KB

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