utils.c 13 KB

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