utils.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /****************************************************************************
  2. *
  3. * utils.c - NRPE Utility Functions
  4. *
  5. * License: GPLv2
  6. * Copyright (c) 2009-2017 Nagios Enterprises
  7. * 1999-2008 Ethan Galstad (nagios@nagios.org)
  8. *
  9. * Description:
  10. *
  11. * This file contains common network functions used in nrpe and check_nrpe.
  12. *
  13. * License Notice:
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 2 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program; if not, write to the Free Software
  27. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  28. *
  29. ****************************************************************************/
  30. #include "../include/common.h"
  31. #include "../include/utils.h"
  32. #include <stdarg.h>
  33. #ifdef HAVE_PATHS_H
  34. #include <paths.h>
  35. #endif
  36. #ifndef HAVE_ASPRINTF
  37. extern int asprintf(char **ptr, const char *format, ...);
  38. #endif
  39. #ifndef HAVE_VASPRINTF
  40. extern int vasprintf(char **ptr, const char *format, va_list ap);
  41. #endif
  42. #ifndef NI_MAXSERV
  43. # define NI_MAXSERV 32
  44. #endif
  45. #ifndef NI_MAXHOST
  46. # define NI_MAXHOST 1025
  47. #endif
  48. extern char **environ;
  49. static unsigned long crc32_table[256];
  50. char *log_file = NULL;
  51. FILE *log_fp = NULL;
  52. static int my_create_socket(struct addrinfo *ai, const char *bind_address, int redirect_stderr);
  53. /* build the crc table - must be called before calculating the crc value */
  54. void generate_crc32_table(void)
  55. {
  56. unsigned long crc, poly;
  57. int i, j;
  58. poly = 0xEDB88320L;
  59. for (i = 0; i < 256; i++) {
  60. crc = i;
  61. for (j = 8; j > 0; j--) {
  62. if (crc & 1)
  63. crc = (crc >> 1) ^ poly;
  64. else
  65. crc >>= 1;
  66. }
  67. crc32_table[i] = crc;
  68. }
  69. return;
  70. }
  71. /* calculates the CRC 32 value for a buffer */
  72. unsigned long calculate_crc32(char *buffer, int buffer_size)
  73. {
  74. register unsigned long crc = 0xFFFFFFFF;
  75. int this_char;
  76. int current_index;
  77. for (current_index = 0; current_index < buffer_size; current_index++) {
  78. this_char = (int)buffer[current_index];
  79. crc = ((crc >> 8) & 0x00FFFFFF) ^ crc32_table[(crc ^ this_char) & 0xFF];
  80. }
  81. return (crc ^ 0xFFFFFFFF);
  82. }
  83. /* fill a buffer with semi-random data */
  84. void randomize_buffer(char *buffer, int buffer_size)
  85. {
  86. FILE *fp;
  87. int x;
  88. int seed;
  89. /**** FILL BUFFER WITH RANDOM ALPHA-NUMERIC CHARACTERS ****/
  90. /***************************************************************
  91. Only use alpha-numeric characters because plugins usually
  92. only generate numbers and letters in their output. We
  93. want the buffer to contain the same set of characters as
  94. plugins, so its harder to distinguish where the real output
  95. ends and the rest of the buffer (padded randomly) starts.
  96. ***************************************************************/
  97. /* try to get seed value from /dev/urandom, as its a better source of entropy */
  98. fp = fopen("/dev/urandom", "r");
  99. if (fp != NULL) {
  100. seed = fgetc(fp);
  101. fclose(fp);
  102. }
  103. /* else fallback to using the current time as the seed */
  104. else
  105. seed = (int)time(NULL);
  106. srand(seed);
  107. for (x = 0; x < buffer_size; x++)
  108. buffer[x] = (int)'0' + (int)(72.0 * rand() / (RAND_MAX + 1.0));
  109. return;
  110. }
  111. /* opens a connection to a remote host */
  112. #ifdef HAVE_STRUCT_SOCKADDR_STORAGE
  113. int my_connect(const char *host, struct sockaddr_storage *hostaddr, u_short port,
  114. int address_family, const char *bind_address, int redirect_stderr)
  115. #else
  116. int my_connect(const char *host, struct sockaddr *hostaddr, u_short port,
  117. int address_family, const char *bind_address, int redirect_stderr)
  118. #endif
  119. {
  120. struct addrinfo hints, *ai, *aitop;
  121. char ntop[NI_MAXHOST], strport[NI_MAXSERV];
  122. int gaierr;
  123. int sock = -1;
  124. FILE *output = stderr;
  125. if (redirect_stderr)
  126. output = stdout;
  127. memset(&hints, 0, sizeof(hints));
  128. hints.ai_family = address_family;
  129. hints.ai_socktype = SOCK_STREAM;
  130. snprintf(strport, sizeof strport, "%u", port);
  131. if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
  132. fprintf(output, "Could not resolve hostname %.100s: %s\n", host, gai_strerror(gaierr));
  133. exit(1);
  134. }
  135. /*
  136. * Loop through addresses for this host, and try each one in
  137. * sequence until the connection succeeds.
  138. */
  139. for (ai = aitop; ai; ai = ai->ai_next) {
  140. if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
  141. continue;
  142. if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
  143. strport, sizeof(strport), NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
  144. fprintf(output, "my_connect: getnameinfo failed\n");
  145. continue;
  146. }
  147. /* Create a socket for connecting. */
  148. sock = my_create_socket(ai, bind_address, redirect_stderr);
  149. if (sock < 0)
  150. continue; /* Any error is already output */
  151. if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
  152. /* Successful connection. */
  153. memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
  154. break;
  155. } else {
  156. fprintf(output, "connect to address %s port %s: %s\n", ntop, strport,
  157. strerror(errno));
  158. close(sock);
  159. sock = -1;
  160. }
  161. }
  162. freeaddrinfo(aitop);
  163. /* Return failure if we didn't get a successful connection. */
  164. if (sock == -1) {
  165. fprintf(output, "connect to host %s port %s: %s\n", host, strport, strerror(errno));
  166. return -1;
  167. }
  168. return sock;
  169. }
  170. /* Creates a socket for the connection. */
  171. int my_create_socket(struct addrinfo *ai, const char *bind_address, int redirect_stderr)
  172. {
  173. int sock, gaierr;
  174. struct addrinfo hints, *res;
  175. FILE *output = stderr;
  176. if (redirect_stderr)
  177. output = stdout;
  178. sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  179. if (sock < 0)
  180. fprintf(output, "socket: %.100s\n", strerror(errno));
  181. /* Bind the socket to an alternative local IP address */
  182. if (bind_address == NULL)
  183. return sock;
  184. memset(&hints, 0, sizeof(hints));
  185. hints.ai_family = ai->ai_family;
  186. hints.ai_socktype = ai->ai_socktype;
  187. hints.ai_protocol = ai->ai_protocol;
  188. hints.ai_flags = AI_PASSIVE;
  189. gaierr = getaddrinfo(bind_address, NULL, &hints, &res);
  190. if (gaierr) {
  191. fprintf(output, "getaddrinfo: %s: %s\n", bind_address, gai_strerror(gaierr));
  192. close(sock);
  193. return -1;
  194. }
  195. if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
  196. fprintf(output, "bind: %s: %s\n", bind_address, strerror(errno));
  197. close(sock);
  198. freeaddrinfo(res);
  199. return -1;
  200. }
  201. freeaddrinfo(res);
  202. return sock;
  203. }
  204. void add_listen_addr(struct addrinfo **listen_addrs, int address_family, char *addr, int port)
  205. {
  206. struct addrinfo hints, *ai, *aitop;
  207. char strport[NI_MAXSERV];
  208. int gaierr;
  209. memset(&hints, 0, sizeof(hints));
  210. hints.ai_family = address_family;
  211. hints.ai_socktype = SOCK_STREAM;
  212. hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
  213. snprintf(strport, sizeof strport, "%d", port);
  214. if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
  215. logit(LOG_ERR, "bad addr or host: %s (%s)\n", addr ? addr : "<NULL>",
  216. gai_strerror(gaierr));
  217. exit(1);
  218. }
  219. for (ai = aitop; ai->ai_next; ai = ai->ai_next) ;
  220. ai->ai_next = *listen_addrs;
  221. *listen_addrs = aitop;
  222. }
  223. int clean_environ(const char *keep_env_vars, const char *nrpe_user)
  224. {
  225. #if defined(HAVE_PATHS_H) && defined(_PATH_STDPATH)
  226. static char *path = _PATH_STDPATH;
  227. #else
  228. static char *path = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
  229. #endif
  230. struct passwd *pw;
  231. size_t len, var_sz = 0;
  232. char **kept = NULL, *value, *var, *keep = NULL;
  233. int i, j, keepcnt = 0;
  234. if (keep_env_vars && *keep_env_vars)
  235. asprintf(&keep, "%s,NRPE_MULTILINESUPPORT,NRPE_PROGRAMVERSION", keep_env_vars);
  236. else
  237. asprintf(&keep, "NRPE_MULTILINESUPPORT,NRPE_PROGRAMVERSION");
  238. if (keep == NULL) {
  239. logit(LOG_ERR, "Could not sanitize the environment. Aborting!");
  240. return ERROR;
  241. }
  242. ++keepcnt;
  243. i = strlen(keep);
  244. while (i--) {
  245. if (keep[i] == ',')
  246. ++keepcnt;
  247. }
  248. if ((kept = calloc(keepcnt + 1, sizeof(char *))) == NULL) {
  249. logit(LOG_ERR, "Could not sanitize the environment. Aborting!");
  250. return ERROR;
  251. }
  252. for (i = 0, var = my_strsep(&keep, ","); var != NULL; var = my_strsep(&keep, ","))
  253. kept[i++] = strip(var);
  254. var = NULL;
  255. i = 0;
  256. while (environ[i]) {
  257. value = environ[i];
  258. if ((len = strcspn(value, "=")) == 0) {
  259. free(keep);
  260. free(kept);
  261. free(var);
  262. logit(LOG_ERR, "Could not sanitize the environment. Aborting!");
  263. return ERROR;
  264. }
  265. if (len >= var_sz) {
  266. var_sz = len + 1;
  267. var = realloc(var, var_sz);
  268. }
  269. strncpy(var, environ[i], var_sz);
  270. var[len] = 0;
  271. for (j = 0; kept[j]; ++j) {
  272. if (!strncmp(var, kept[j], strlen(kept[j])))
  273. break;
  274. }
  275. if (kept[j]) {
  276. ++i;
  277. continue;
  278. }
  279. unsetenv(var);
  280. }
  281. free(var);
  282. free(keep);
  283. free(kept);
  284. char * user = NULL;
  285. if (nrpe_user != NULL) {
  286. user = strdup(nrpe_user);
  287. pw = (struct passwd *)getpwnam(nrpe_user);
  288. }
  289. if (nrpe_user == NULL || pw == NULL) {
  290. pw = (struct passwd *)getpwuid(getuid());
  291. if (pw != NULL) {
  292. user = strdup(pw->pw_name);
  293. }
  294. }
  295. if (pw == NULL) {
  296. free(user);
  297. return OK;
  298. }
  299. setenv("PATH", path, 1);
  300. setenv("IFS", " \t\n", 1);
  301. setenv("LOGNAME", user, 0);
  302. setenv("USER", user, 0);
  303. setenv("HOME", pw->pw_dir, 0);
  304. setenv("SHELL", pw->pw_shell, 0);
  305. free(user);
  306. return OK;
  307. }
  308. char *strip(char *buffer)
  309. {
  310. int x;
  311. int index;
  312. char *buf = buffer;
  313. for (x = strlen(buffer); x >= 1; x--) {
  314. index = x - 1;
  315. if (buffer[index] == ' ' || buffer[index] == '\r' || buffer[index] == '\n'
  316. || buffer[index] == '\t')
  317. buffer[index] = '\x0';
  318. else
  319. break;
  320. }
  321. while (*buf == ' ' || *buf == '\r' || *buf == '\n' || *buf == '\t') {
  322. ++buf;
  323. --x;
  324. }
  325. if (buf != buffer) {
  326. memmove(buffer, buf, x);
  327. buffer[x] = '\x0';
  328. }
  329. return buffer;
  330. }
  331. /* sends all data - thanks to Beej's Guide to Network Programming */
  332. int sendall(int s, char *buf, int *len)
  333. {
  334. int total = 0;
  335. int bytesleft = *len;
  336. int n = 0;
  337. /* send all the data */
  338. while (total < *len) {
  339. n = send(s, buf + total, bytesleft, 0); /* send some data */
  340. if (n == -1) /* break on error */
  341. break;
  342. /* apply bytes we sent */
  343. total += n;
  344. bytesleft -= n;
  345. }
  346. *len = total; /* return number of bytes actually sent here */
  347. return n == -1 ? -1 : 0; /* return -1 on failure, 0 on success */
  348. }
  349. /* receives all data - modelled after sendall() */
  350. int recvall(int s, char *buf, int *len, int timeout)
  351. {
  352. time_t start_time;
  353. time_t current_time;
  354. int total = 0;
  355. int bytesleft = *len;
  356. int n = 0;
  357. bzero(buf, *len); /* clear the receive buffer */
  358. time(&start_time);
  359. /* receive all data */
  360. while (total < *len) {
  361. n = recv(s, buf + total, bytesleft, 0); /* receive some data */
  362. if (n == -1 && errno == EAGAIN) {
  363. /* no data has arrived yet (non-blocking socket) */
  364. time(&current_time);
  365. if (current_time - start_time > timeout)
  366. break;
  367. sleep(1);
  368. continue;
  369. } else if (n <= 0)
  370. break; /* receive error or client disconnect */
  371. /* apply bytes we received */
  372. total += n;
  373. bytesleft -= n;
  374. }
  375. /* return number of bytes actually received here */
  376. *len = total;
  377. /* return <=0 on failure, bytes received on success */
  378. return (n <= 0) ? n : total;
  379. }
  380. /* fixes compiler problems under Solaris, since strsep() isn't included */
  381. /* this code is taken from the glibc source */
  382. char *my_strsep(char **stringp, const char *delim)
  383. {
  384. char *begin, *end;
  385. begin = *stringp;
  386. if (begin == NULL)
  387. return NULL;
  388. /* A frequent case is when the delimiter string contains only one
  389. character. Here we don't need to call the expensive `strpbrk'
  390. function and instead work using `strchr'. */
  391. if (delim[0] == '\0' || delim[1] == '\0') {
  392. char ch = delim[0];
  393. if (ch == '\0')
  394. end = NULL;
  395. else {
  396. if (*begin == ch)
  397. end = begin;
  398. else
  399. end = strchr(begin + 1, ch);
  400. }
  401. } else
  402. end = strpbrk(begin, delim); /* Find the end of the token. */
  403. if (end) {
  404. /* Terminate the token and set *STRINGP past NUL character. */
  405. *end++ = '\0';
  406. *stringp = end;
  407. } else
  408. /* No more delimiters; this is the last token. */
  409. *stringp = NULL;
  410. return begin;
  411. }
  412. void open_log_file()
  413. {
  414. int fh;
  415. int flags = O_RDWR|O_APPEND|O_CREAT;
  416. struct stat st;
  417. close_log_file();
  418. if (!log_file)
  419. return;
  420. #ifdef O_NOFOLLOW
  421. flags |= O_NOFOLLOW;
  422. #endif
  423. if ((fh = open(log_file, flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1) {
  424. printf("Warning: Cannot open log file '%s' for writing\n", log_file);
  425. logit(LOG_WARNING, "Warning: Cannot open log file '%s' for writing", log_file);
  426. return;
  427. }
  428. log_fp = fdopen(fh, "a+");
  429. if(log_fp == NULL) {
  430. printf("Warning: Cannot open log file '%s' for writing\n", log_file);
  431. logit(LOG_WARNING, "Warning: Cannot open log file '%s' for writing", log_file);
  432. return;
  433. }
  434. if ((fstat(fh, &st)) == -1) {
  435. log_fp = NULL;
  436. close(fh);
  437. printf("Warning: Cannot fstat log file '%s'\n", log_file);
  438. logit(LOG_WARNING, "Warning: Cannot fstat log file '%s'", log_file);
  439. return;
  440. }
  441. if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) {
  442. log_fp = NULL;
  443. close(fh);
  444. printf("Warning: log file '%s' has an invalid mode\n", log_file);
  445. logit(LOG_WARNING, "Warning: log file '%s' has an invalid mode", log_file);
  446. return;
  447. }
  448. (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC);
  449. }
  450. void logit(int priority, const char *format, ...)
  451. {
  452. time_t log_time = 0L;
  453. va_list ap;
  454. char *buffer = NULL;
  455. if (!format || !*format)
  456. return;
  457. va_start(ap, format);
  458. if(vasprintf(&buffer, format, ap) > 0) {
  459. if (log_fp) {
  460. time(&log_time);
  461. /* strip any newlines from the end of the buffer */
  462. strip(buffer);
  463. /* write the buffer to the log file */
  464. fprintf(log_fp, "[%llu] %s\n", (unsigned long long)log_time, buffer);
  465. fflush(log_fp);
  466. } else if (!disable_syslog) {
  467. syslog(priority, "%s", buffer);
  468. }
  469. free(buffer);
  470. }
  471. va_end(ap);
  472. }
  473. void close_log_file()
  474. {
  475. if(!log_fp)
  476. return;
  477. fflush(log_fp);
  478. fclose(log_fp);
  479. log_fp = NULL;
  480. return;
  481. }
  482. /* show license */
  483. void display_license(void)
  484. {
  485. printf("This program is released under the GPL (see below) with the additional\n");
  486. printf("exemption that compiling, linking, and/or using OpenSSL is allowed.\n\n");
  487. printf("This program is free software; you can redistribute it and/or modify\n");
  488. printf("it under the terms of the GNU General Public License as published by\n");
  489. printf("the Free Software Foundation; either version 2 of the License, or\n");
  490. printf("(at your option) any later version.\n\n");
  491. printf("This program is distributed in the hope that it will be useful,\n");
  492. printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
  493. printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
  494. printf("GNU General Public License for more details.\n\n");
  495. printf("You should have received a copy of the GNU General Public License\n");
  496. printf("along with this program; if not, write to the Free Software\n");
  497. printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
  498. return;
  499. }