cidr.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /* $Id: cidr.c 1897 2007-08-25 04:57:38Z aturner $ */
  2. /*
  3. * Copyright (c) 2001-2004 Aaron Turner.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the names of the copyright owners nor the names of its
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  20. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  23. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  25. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  27. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  28. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  29. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include "config.h"
  32. #include "defines.h"
  33. #include "common.h"
  34. #include "lib/strlcpy.h"
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. /* required for inet_aton() */
  39. #include <sys/socket.h>
  40. #include <netinet/in.h>
  41. #include <arpa/inet.h>
  42. #ifdef DEBUG
  43. extern int debug;
  44. #endif
  45. static tcpr_cidr_t *cidr2cidr(char *);
  46. /**
  47. * prints to the given fd all the entries in mycidr
  48. */
  49. void
  50. print_cidr(tcpr_cidr_t * mycidr)
  51. {
  52. tcpr_cidr_t *cidr_ptr;
  53. fprintf(stderr, "Cidr List: ");
  54. cidr_ptr = mycidr;
  55. while (cidr_ptr != NULL) {
  56. /* print it */
  57. fprintf(stderr, "%s/%d, ",
  58. get_addr2name4(cidr_ptr->network, RESOLVE),
  59. cidr_ptr->masklen);
  60. /* go to the next */
  61. if (cidr_ptr->next != NULL) {
  62. cidr_ptr = cidr_ptr->next;
  63. }
  64. else {
  65. break;
  66. }
  67. }
  68. fprintf(stderr, "\n");
  69. }
  70. /**
  71. * deletes all entries in a cidr and destroys the datastructure
  72. */
  73. void
  74. destroy_cidr(tcpr_cidr_t * cidr)
  75. {
  76. if (cidr != NULL)
  77. if (cidr->next != NULL)
  78. destroy_cidr(cidr->next);
  79. safe_free(cidr);
  80. return;
  81. }
  82. /**
  83. * adds a new tcpr_cidr_t entry to cidrdata
  84. */
  85. void
  86. add_cidr(tcpr_cidr_t ** cidrdata, tcpr_cidr_t ** newcidr)
  87. {
  88. tcpr_cidr_t *cidr_ptr;
  89. dbg(1, "Running new_cidr()");
  90. if (*cidrdata == NULL) {
  91. *cidrdata = *newcidr;
  92. }
  93. else {
  94. cidr_ptr = *cidrdata;
  95. while (cidr_ptr->next != NULL) {
  96. cidr_ptr = cidr_ptr->next;
  97. }
  98. cidr_ptr->next = *newcidr;
  99. }
  100. }
  101. /**
  102. * takes in an IP and masklen, and returns a string in
  103. * cidr format: x.x.x.x/y. This malloc's memory.
  104. */
  105. u_char *
  106. ip2cidr(const unsigned long ip, const int masklen)
  107. {
  108. u_char *network;
  109. char mask[3];
  110. network = (u_char *)safe_malloc(20);
  111. strlcpy((char *)network, (char *)get_addr2name4(ip, RESOLVE),
  112. sizeof(network));
  113. strcat((char *)network, "/");
  114. if (masklen < 10) {
  115. snprintf(mask, 1, "%d", masklen);
  116. strncat((char *)network, mask, 1);
  117. }
  118. else {
  119. snprintf(mask, 2, "%d", masklen);
  120. strncat((char *)network, mask, 2);
  121. }
  122. return (network);
  123. }
  124. /**
  125. * Mallocs and sets to sane defaults a tcpr_cidr_t structure
  126. */
  127. tcpr_cidr_t *
  128. new_cidr(void)
  129. {
  130. tcpr_cidr_t *newcidr;
  131. newcidr = (tcpr_cidr_t *)safe_malloc(sizeof(tcpr_cidr_t));
  132. memset(newcidr, '\0', sizeof(tcpr_cidr_t));
  133. newcidr->masklen = 99;
  134. newcidr->next = NULL;
  135. return (newcidr);
  136. }
  137. /**
  138. * Creates a new tcpr_cidrmap_t structure. Malloc's memory
  139. */
  140. tcpr_cidrmap_t *
  141. new_cidr_map(void)
  142. {
  143. tcpr_cidrmap_t *new;
  144. new = (tcpr_cidrmap_t *)safe_malloc(sizeof(tcpr_cidrmap_t));
  145. memset(new, '\0', sizeof(tcpr_cidrmap_t));
  146. new->next = NULL;
  147. return (new);
  148. }
  149. /**
  150. * Converts a single cidr (string) in the form of x.x.x.x/y into a
  151. * tcpr_cidr_t structure. Will malloc the tcpr_cidr_t structure.
  152. */
  153. static tcpr_cidr_t *
  154. cidr2cidr(char *cidr)
  155. {
  156. int count = 0;
  157. unsigned int octets[4]; /* used in sscanf */
  158. tcpr_cidr_t *newcidr;
  159. char networkip[16], tempoctet[4], ebuf[EBUF_SIZE];
  160. assert(cidr);
  161. assert(strlen(cidr) <= EBUF_SIZE);
  162. newcidr = new_cidr();
  163. /*
  164. * scan it, and make sure it scanned correctly, also copy over the
  165. * masklen
  166. */
  167. count = sscanf(cidr, "%u.%u.%u.%u/%d", &octets[0], &octets[1],
  168. &octets[2], &octets[3], &newcidr->masklen);
  169. if (count == 4) {
  170. newcidr->masklen = 32;
  171. } else if (count != 5) {
  172. goto error;
  173. }
  174. /* masklen better be 0 =< masklen <= 32 */
  175. if (newcidr->masklen > 32)
  176. goto error;
  177. /* copy in the ip address */
  178. memset(networkip, '\0', 16);
  179. for (count = 0; count < 4; count++) {
  180. if (octets[count] > 255)
  181. goto error;
  182. snprintf(tempoctet, sizeof(octets[count]), "%d", octets[count]);
  183. strcat(networkip, tempoctet);
  184. /* we don't want a '.' at the end of the last octet */
  185. if (count < 3)
  186. strcat(networkip, ".");
  187. }
  188. /* copy over the network address and return */
  189. #ifdef HAVE_INET_ATON
  190. inet_aton(networkip, (struct in_addr *)&newcidr->network);
  191. #elif HAVE_INET_ADDR
  192. newcidr->network = inet_addr(networkip);
  193. #endif
  194. return (newcidr);
  195. /* we only get here on error parsing input */
  196. error:
  197. memset(ebuf, '\0', EBUF_SIZE);
  198. strcpy(ebuf, "Unable to parse as a vaild CIDR: ");
  199. strlcat(ebuf, cidr, EBUF_SIZE);
  200. errx(1, "%s", ebuf);
  201. return NULL;
  202. }
  203. /**
  204. * parses a list of tcpr_cidr_t's input from the user which should be in the form
  205. * of x.x.x.x/y,x.x.x.x/y...
  206. * returns 1 for success, or fails to return on failure (exit 1)
  207. * since we use strtok to process cidr, it gets zeroed out.
  208. */
  209. int
  210. parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim)
  211. {
  212. tcpr_cidr_t *cidr_ptr; /* ptr to current cidr record */
  213. char *network = NULL;
  214. char *token = NULL;
  215. /* first itteration of input using strtok */
  216. network = strtok_r(cidrin, delim, &token);
  217. *cidrdata = cidr2cidr(network);
  218. cidr_ptr = *cidrdata;
  219. /* do the same with the rest of the input */
  220. while (1) {
  221. network = strtok_r(NULL, delim, &token);
  222. /* if that was the last CIDR, then kickout */
  223. if (network == NULL)
  224. break;
  225. /* next record */
  226. cidr_ptr->next = cidr2cidr(network);
  227. cidr_ptr = cidr_ptr->next;
  228. }
  229. return 1;
  230. }
  231. /**
  232. * parses a pair of IP addresses: <IP1>:<IP2> and processes it like:
  233. * -N 0.0.0.0/0:<IP1> -N 0.0.0.0/0:<IP2>
  234. * returns 1 for success or returns 0 on failure
  235. * since we use strtok to process optarg, it gets zeroed out
  236. */
  237. int
  238. parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const char *optarg)
  239. {
  240. #define NEWMAP_LEN 32
  241. char *map = NULL, newmap[NEWMAP_LEN];
  242. char *token = NULL;
  243. char *string;
  244. string = safe_strdup(optarg);
  245. memset(newmap, '\0', NEWMAP_LEN);
  246. map = strtok_r(string, ":", &token);
  247. strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN);
  248. strlcat(newmap, map, NEWMAP_LEN);
  249. if (! parse_cidr_map(cidrmap1, newmap))
  250. return 0;
  251. /* do again with the second IP */
  252. memset(newmap, '\0', NEWMAP_LEN);
  253. map = strtok_r(NULL, ":", &token);
  254. strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN);
  255. strlcat(newmap, map, NEWMAP_LEN);
  256. if (! parse_cidr_map(cidrmap2, newmap))
  257. return 0;
  258. safe_free(string);
  259. return 1; /* success */
  260. }
  261. /**
  262. * parses a list of tcpr_cidrmap_t's input from the user which should be in the form
  263. * of x.x.x.x/y:x.x.x.x/y,...
  264. * returns 1 for success, or returns 0 on failure
  265. * since we use strtok to process optarg, it gets zeroed out.
  266. */
  267. int
  268. parse_cidr_map(tcpr_cidrmap_t **cidrmap, const char *optarg)
  269. {
  270. tcpr_cidr_t *cidr = NULL;
  271. char *map = NULL;
  272. char *token = NULL, *string = NULL;
  273. tcpr_cidrmap_t *ptr;
  274. string = safe_strdup(optarg);
  275. /* first iteration */
  276. map = strtok_r(string, ",", &token);
  277. if (! parse_cidr(&cidr, map, ":"))
  278. return 0;
  279. /* must return a linked list of two */
  280. if (cidr->next == NULL)
  281. return 0;
  282. /* copy over */
  283. *cidrmap = new_cidr_map();
  284. ptr = *cidrmap;
  285. ptr->from = cidr;
  286. ptr->to = cidr->next;
  287. ptr->from->next = NULL;
  288. /* do the same with the reset of the input */
  289. while(1) {
  290. map = strtok_r(NULL, ",", &token);
  291. if (map == NULL)
  292. break;
  293. if (! parse_cidr(&cidr, map, ":"))
  294. return 0;
  295. /* must return a linked list of two */
  296. if (cidr->next == NULL)
  297. return 0;
  298. /* copy over */
  299. ptr->next = new_cidr_map();
  300. ptr = ptr->next;
  301. ptr->from = cidr;
  302. ptr->to = cidr->next;
  303. ptr->from->next = NULL;
  304. }
  305. safe_free(string);
  306. return 1; /* success */
  307. }
  308. /**
  309. * checks to see if the ip address is in the cidr
  310. * returns 1 for true, 0 for false
  311. */
  312. int
  313. ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip)
  314. {
  315. unsigned long ipaddr = 0, network = 0, mask = 0;
  316. int ret = 0;
  317. /* always return 1 if 0.0.0.0/0 */
  318. if (mycidr->masklen == 0 && mycidr->network == 0)
  319. return 1;
  320. mask = ~0; /* turn on all the bits */
  321. /* shift over by the correct number of bits */
  322. mask = mask << (32 - mycidr->masklen);
  323. /* apply the mask to the network and ip */
  324. ipaddr = ntohl(ip) & mask;
  325. network = htonl(mycidr->network) & mask;
  326. /* if they're the same, then ip is in network */
  327. if (network == ipaddr) {
  328. dbgx(1, "The ip %s is inside of %s/%d",
  329. get_addr2name4(ip, RESOLVE),
  330. get_addr2name4(htonl(network), RESOLVE), mycidr->masklen);
  331. ret = 1;
  332. }
  333. else {
  334. dbgx(1, "The ip %s is not inside of %s/%d",
  335. get_addr2name4(ip, RESOLVE),
  336. get_addr2name4(htonl(network), RESOLVE), mycidr->masklen);
  337. ret = 0;
  338. }
  339. return ret;
  340. }
  341. /**
  342. * iterates over cidrdata to find if a given ip matches
  343. * returns 1 for true, 0 for false
  344. */
  345. int
  346. check_ip_cidr(tcpr_cidr_t * cidrdata, const unsigned long ip)
  347. {
  348. tcpr_cidr_t *mycidr;
  349. /* if we have no cidrdata, of course it isn't in there
  350. * this actually should happen occasionally, so don't put an assert here
  351. */
  352. if (cidrdata == NULL) {
  353. return 1;
  354. }
  355. mycidr = cidrdata;
  356. /* loop through cidr */
  357. while (1) {
  358. /* if match, return 1 */
  359. if (ip_in_cidr(mycidr, ip)) {
  360. dbgx(3, "Found %s in cidr", get_addr2name4(ip, RESOLVE));
  361. return 1;
  362. }
  363. /* check for next record */
  364. if (mycidr->next != NULL) {
  365. mycidr = mycidr->next;
  366. }
  367. else {
  368. break;
  369. }
  370. }
  371. /* if we get here, no match */
  372. dbgx(3, "Didn't find %s in cidr", get_addr2name4(ip, RESOLVE));
  373. return 0;
  374. }
  375. /**
  376. * cidr2ip takes a tcpr_cidr_t and a delimiter
  377. * and returns a string which lists all the IP addresses in the cidr
  378. * deliminated by the given char
  379. */
  380. char *
  381. cidr2iplist(tcpr_cidr_t * cidr, char delim)
  382. {
  383. char *list = NULL;
  384. char ipaddr[16];
  385. u_int32_t size, addr, first, last, numips;
  386. struct in_addr in;
  387. /*
  388. * 16 bytes per IP + delim
  389. * # of IP's = 2^(32-masklen)
  390. */
  391. numips = 2;
  392. for (int i = 2; i <= (32 - cidr->masklen); i++) {
  393. numips *= 2;
  394. }
  395. size = 16 * numips;
  396. list = (char *)safe_malloc(size);
  397. memset(list, 0, size);
  398. /* first and last should not include network or broadcast */
  399. first = ntohl(cidr->network) + 1;
  400. last = first + numips - 3;
  401. dbgx(1, "First: %u\t\tLast: %u", first, last);
  402. /* loop through all but the last one */
  403. for (addr = first; addr < last; addr++) {
  404. in.s_addr = htonl(addr);
  405. snprintf(ipaddr, 17, "%s%c", inet_ntoa(in), delim);
  406. dbgx(2, "%s", ipaddr);
  407. strlcat(list, ipaddr, size);
  408. }
  409. /* last is a special case, end in \0 */
  410. in.s_addr = htonl(addr);
  411. snprintf(ipaddr, 16, "%s", inet_ntoa(in));
  412. strlcat(list, ipaddr, size);
  413. return list;
  414. }
  415. /*
  416. Local Variables:
  417. mode:c
  418. indent-tabs-mode:nil
  419. c-basic-offset:4
  420. End:
  421. */