cidr.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /* $Id: cidr.c 2053 2008-05-31 02:19:17Z 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. #ifdef DEBUG
  318. char netstr[20];
  319. #endif
  320. /* always return 1 if 0.0.0.0/0 */
  321. if (mycidr->masklen == 0 && mycidr->network == 0)
  322. return 1;
  323. mask = ~0; /* turn on all the bits */
  324. /* shift over by the correct number of bits */
  325. mask = mask << (32 - mycidr->masklen);
  326. /* apply the mask to the network and ip */
  327. ipaddr = ntohl(ip) & mask;
  328. network = htonl(mycidr->network) & mask;
  329. #ifdef DEBUG
  330. /* copy this for debug purposes, since it's not re-entrant */
  331. strlcpy(netstr, get_addr2name4(htonl(mycidr->network), RESOLVE), 20);
  332. #endif
  333. /* if they're the same, then ip is in network */
  334. if (network == ipaddr) {
  335. #ifdef DEBUG
  336. dbgx(1, "The ip %s is inside of %s/%d",
  337. get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen);
  338. #endif
  339. ret = 1;
  340. }
  341. else {
  342. #ifdef DEBUG
  343. dbgx(1, "The ip %s is not inside of %s/%d",
  344. get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen);
  345. #endif
  346. ret = 0;
  347. }
  348. return ret;
  349. }
  350. /**
  351. * iterates over cidrdata to find if a given ip matches
  352. * returns 1 for true, 0 for false
  353. */
  354. int
  355. check_ip_cidr(tcpr_cidr_t * cidrdata, const unsigned long ip)
  356. {
  357. tcpr_cidr_t *mycidr;
  358. /* if we have no cidrdata, of course it isn't in there
  359. * this actually should happen occasionally, so don't put an assert here
  360. */
  361. if (cidrdata == NULL) {
  362. return 1;
  363. }
  364. mycidr = cidrdata;
  365. /* loop through cidr */
  366. while (1) {
  367. /* if match, return 1 */
  368. if (ip_in_cidr(mycidr, ip)) {
  369. dbgx(3, "Found %s in cidr", get_addr2name4(ip, RESOLVE));
  370. return 1;
  371. }
  372. /* check for next record */
  373. if (mycidr->next != NULL) {
  374. mycidr = mycidr->next;
  375. }
  376. else {
  377. break;
  378. }
  379. }
  380. /* if we get here, no match */
  381. dbgx(3, "Didn't find %s in cidr", get_addr2name4(ip, RESOLVE));
  382. return 0;
  383. }
  384. /**
  385. * cidr2ip takes a tcpr_cidr_t and a delimiter
  386. * and returns a string which lists all the IP addresses in the cidr
  387. * deliminated by the given char
  388. */
  389. char *
  390. cidr2iplist(tcpr_cidr_t * cidr, char delim)
  391. {
  392. char *list = NULL;
  393. char ipaddr[16];
  394. u_int32_t size, addr, first, last, numips;
  395. struct in_addr in;
  396. /*
  397. * 16 bytes per IP + delim
  398. * # of IP's = 2^(32-masklen)
  399. */
  400. numips = 2;
  401. for (int i = 2; i <= (32 - cidr->masklen); i++) {
  402. numips *= 2;
  403. }
  404. size = 16 * numips;
  405. list = (char *)safe_malloc(size);
  406. memset(list, 0, size);
  407. /* first and last should not include network or broadcast */
  408. first = ntohl(cidr->network) + 1;
  409. last = first + numips - 3;
  410. dbgx(1, "First: %u\t\tLast: %u", first, last);
  411. /* loop through all but the last one */
  412. for (addr = first; addr < last; addr++) {
  413. in.s_addr = htonl(addr);
  414. snprintf(ipaddr, 17, "%s%c", inet_ntoa(in), delim);
  415. dbgx(2, "%s", ipaddr);
  416. strlcat(list, ipaddr, size);
  417. }
  418. /* last is a special case, end in \0 */
  419. in.s_addr = htonl(addr);
  420. snprintf(ipaddr, 16, "%s", inet_ntoa(in));
  421. strlcat(list, ipaddr, size);
  422. return list;
  423. }
  424. /*
  425. Local Variables:
  426. mode:c
  427. indent-tabs-mode:nil
  428. c-basic-offset:4
  429. End:
  430. */