tcpprep.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /* $Id: tcpprep.c 1383 2005-07-03 19:21:06Z aturner $ */
  2. /*
  3. * Copyright (c) 2001-2005 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. /*
  32. * Purpose:
  33. * 1) Remove the performance bottleneck in tcpreplay for choosing an NIC
  34. * 2) Seperate code to make it more manageable
  35. * 3) Add addtional features which require multiple passes of a pcap
  36. *
  37. * Support:
  38. * Right now we support matching source IP based upon on of the following:
  39. * - Regular expression
  40. * - IP address is contained in one of a list of CIDR blocks
  41. * - Auto learning of CIDR block for servers (clients all other)
  42. */
  43. #include "config.h"
  44. #include "defines.h"
  45. #include "common.h"
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <regex.h>
  50. #include <string.h>
  51. #include <unistd.h>
  52. #include "tcpprep.h"
  53. #include "portmap.h"
  54. #include "tcpprep_opts.h"
  55. #include "lib/tree.h"
  56. #include "tree.h"
  57. #include "lib/sll.h"
  58. #include "lib/strlcpy.h"
  59. #include "dlt.h"
  60. /*
  61. * global variables
  62. */
  63. #ifdef DEBUG
  64. int debug = 0;
  65. #endif
  66. #ifdef HAVE_TCPDUMP
  67. tcpdump_t tcpdump;
  68. #endif
  69. tcpprep_opt_t options;
  70. int info = 0;
  71. char *ourregex = NULL;
  72. char *cidr = NULL;
  73. data_tree_t treeroot;
  74. static void init(void);
  75. static void post_args(int, char *[]);
  76. static void print_comment(const char *);
  77. static void print_info(const char *);
  78. static int check_ip_regex(const unsigned long ip);
  79. static COUNTER process_raw_packets(pcap_t * pcap);
  80. static int check_dst_port(ip_hdr_t *ip_hdr, int len);
  81. /*
  82. * main()
  83. */
  84. int
  85. main(int argc, char *argv[])
  86. {
  87. int out_file;
  88. COUNTER totpackets = 0;
  89. char errbuf[PCAP_ERRBUF_SIZE];
  90. int optct = 0;
  91. init(); /* init our globals */
  92. optct = optionProcess(&tcpprepOptions, argc, argv);
  93. post_args(argc, argv);
  94. argc -= optct;
  95. argv += optct;
  96. /* open the cache file */
  97. if ((out_file = open(OPT_ARG(CACHEFILE), O_WRONLY | O_CREAT | O_TRUNC,
  98. S_IREAD | S_IWRITE | S_IRGRP | S_IWGRP | S_IROTH)) == -1)
  99. errx(1, "Unable to open cache file %s for writing: %s",
  100. OPT_ARG(CACHEFILE), strerror(errno));
  101. readpcap:
  102. /* open the pcap file */
  103. if ((options.pcap = pcap_open_offline(OPT_ARG(PCAP), errbuf)) == NULL)
  104. errx(1, "Error opening file: %s", errbuf);
  105. if ((pcap_datalink(options.pcap) != DLT_EN10MB) &&
  106. (pcap_datalink(options.pcap) != DLT_LINUX_SLL) &&
  107. (pcap_datalink(options.pcap) != DLT_RAW) &&
  108. (pcap_datalink(options.pcap) != DLT_C_HDLC)) {
  109. errx(1, "Unsupported pcap DLT type: 0x%x", pcap_datalink(options.pcap));
  110. }
  111. #ifdef HAVE_TCPDUMP
  112. if (HAVE_OPT(VERBOSE)) {
  113. tcpdump.filename = safe_strdup(OPT_ARG(PCAP));
  114. tcpdump_open(&tcpdump);
  115. }
  116. #endif
  117. /* do we apply a bpf filter? */
  118. if (options.bpf.filter != NULL) {
  119. if (pcap_compile(options.pcap, &options.bpf.program, options.bpf.filter,
  120. options.bpf.optimize, 0) != 0) {
  121. errx(1, "Error compiling BPF filter: %s", pcap_geterr(options.pcap));
  122. }
  123. pcap_setfilter(options.pcap, &options.bpf.program);
  124. }
  125. if ((totpackets = process_raw_packets(options.pcap)) == 0) {
  126. pcap_close(options.pcap);
  127. err(1, "No packets were processed. Filter too limiting?");
  128. }
  129. pcap_close(options.pcap);
  130. #ifdef HAVE_TCPDUMP
  131. tcpdump_close(&tcpdump);
  132. #endif
  133. /* we need to process the pcap file twice in HASH/AUTO mode */
  134. if (options.mode == AUTO_MODE) {
  135. options.mode = options.automode;
  136. if (options.mode == ROUTER_MODE) { /* do we need to convert TREE->CIDR? */
  137. if (info)
  138. fprintf(stderr, "Building network list from pre-cache...\n");
  139. if (!process_tree()) {
  140. err(1, "Error: unable to build a valid list of servers. Aborting.");
  141. }
  142. }
  143. else {
  144. /*
  145. * in bridge mode we need to calculate client/sever
  146. * manually since this is done automatically in
  147. * process_tree()
  148. */
  149. tree_calculate(&treeroot);
  150. }
  151. if (info)
  152. fprintf(stderr, "Buliding cache file...\n");
  153. /*
  154. * re-process files, but this time generate
  155. * cache
  156. */
  157. goto readpcap;
  158. }
  159. #ifdef DEBUG
  160. if (debug && (options.cidrdata != NULL))
  161. print_cidr(options.cidrdata);
  162. #endif
  163. /* write cache data */
  164. totpackets = write_cache(options.cachedata, out_file, totpackets,
  165. options.comment);
  166. if (info)
  167. notice("Done.\nCached " COUNTER_SPEC " packets.\n", totpackets);
  168. /* close cache file */
  169. close(out_file);
  170. return 0;
  171. }
  172. /*
  173. * checks the dst port to see if this is destined for a server port.
  174. * returns 1 for true, 0 for false
  175. */
  176. static int
  177. check_dst_port(ip_hdr_t *ip_hdr, int len)
  178. {
  179. tcp_hdr_t *tcp_hdr = NULL;
  180. udp_hdr_t *udp_hdr = NULL;
  181. dbg(3, "Checking the destination port...");
  182. if (ip_hdr->ip_p == IPPROTO_TCP) {
  183. tcp_hdr = (tcp_hdr_t *)get_layer4(ip_hdr);
  184. /* is a service? */
  185. if (options.services.tcp[ntohs(tcp_hdr->th_dport)]) {
  186. dbg(1, "TCP packet is destined for a server port: %d", ntohs(tcp_hdr->th_dport));
  187. return 1;
  188. }
  189. /* nope */
  190. dbg(1, "TCP packet is NOT destined for a server port: %d", ntohs(tcp_hdr->th_dport));
  191. return 0;
  192. } else if (ip_hdr->ip_p == IPPROTO_UDP) {
  193. udp_hdr = (udp_hdr_t *)get_layer4(ip_hdr);
  194. /* is a service? */
  195. if (options.services.udp[ntohs(udp_hdr->uh_dport)]) {
  196. dbg(1, "UDP packet is destined for a server port: %d", ntohs(udp_hdr->uh_dport));
  197. return 1;
  198. }
  199. /* nope */
  200. dbg(1, "UDP packet is NOT destined for a server port: %d", ntohs(udp_hdr->uh_dport));
  201. return 0;
  202. }
  203. /* not a TCP or UDP packet... return as non_ip */
  204. dbg(1, "Packet isn't a UDP or TCP packet... no port to process.");
  205. return options.nonip;
  206. }
  207. /*
  208. * checks to see if an ip address matches a regex. Returns 1 for true
  209. * 0 for false
  210. */
  211. static int
  212. check_ip_regex(const unsigned long ip)
  213. {
  214. int eflags = 0;
  215. u_char src_ip[16];
  216. size_t nmatch = 0;
  217. regmatch_t *pmatch = NULL;
  218. memset(src_ip, '\0', 16);
  219. strlcpy((char *)src_ip, (char *)libnet_addr2name4(ip, LIBNET_DONT_RESOLVE),
  220. sizeof(src_ip));
  221. if (regexec(&options.preg, (char *)src_ip, nmatch, pmatch, eflags) == 0) {
  222. return (1);
  223. }
  224. else {
  225. return (0);
  226. }
  227. }
  228. /*
  229. * uses libpcap library to parse the packets and build
  230. * the cache file.
  231. */
  232. static COUNTER
  233. process_raw_packets(pcap_t * pcap)
  234. {
  235. ip_hdr_t *ip_hdr = NULL;
  236. struct pcap_pkthdr pkthdr;
  237. const u_char *pktdata = NULL;
  238. COUNTER packetnum = 0;
  239. int l2len, cache_result = 0;
  240. u_char ipbuff[MAXPACKET], *buffptr;
  241. #ifdef HAVE_TCPDUMP
  242. struct pollfd poller[1];
  243. poller[0].fd = tcpdump.outfd;
  244. poller[0].events = POLLIN;
  245. poller[0].revents = 0;
  246. #endif
  247. while ((pktdata = pcap_next(pcap, &pkthdr)) != NULL) {
  248. packetnum++;
  249. dbg(1, "Packet " COUNTER_SPEC, packetnum);
  250. /* look for include or exclude LIST match */
  251. if (options.xX.list != NULL) {
  252. if (options.xX.mode < xXExclude) {
  253. if (!check_list(options.xX.list, packetnum)) {
  254. add_cache(&options.cachedata, DONT_SEND, 0);
  255. continue;
  256. }
  257. }
  258. else if (check_list(options.xX.list, packetnum)) {
  259. add_cache(&options.cachedata, DONT_SEND, 0);
  260. continue;
  261. }
  262. }
  263. /* get the IP header (if any) */
  264. buffptr = ipbuff;
  265. ip_hdr = (ip_hdr_t *)get_ipv4(pktdata, pkthdr.caplen,
  266. pcap_datalink(pcap), &buffptr);
  267. if (ip_hdr == NULL) {
  268. dbg(2, "Packet isn't IP");
  269. /* we don't want to cache these packets twice */
  270. if (options.mode != AUTO_MODE) {
  271. dbg(3, "Adding to cache using options for Non-IP packets");
  272. add_cache(&options.cachedata, SEND, options.nonip);
  273. }
  274. continue;
  275. }
  276. l2len = get_l2len(pktdata, pkthdr.caplen, pcap_datalink(pcap));
  277. /* look for include or exclude CIDR match */
  278. if (options.xX.cidr != NULL) {
  279. if (!process_xX_by_cidr(options.xX.mode, options.xX.cidr, ip_hdr)) {
  280. add_cache(&options.cachedata, DONT_SEND, 0);
  281. continue;
  282. }
  283. }
  284. switch (options.mode) {
  285. case REGEX_MODE:
  286. dbg(2, "processing regex mode...");
  287. cache_result = add_cache(&options.cachedata, SEND,
  288. check_ip_regex(ip_hdr->ip_src.s_addr));
  289. break;
  290. case CIDR_MODE:
  291. dbg(2, "processing cidr mode...");
  292. cache_result = add_cache(&options.cachedata, SEND,
  293. check_ip_cidr(options.cidrdata, ip_hdr->ip_src.s_addr));
  294. break;
  295. case AUTO_MODE:
  296. dbg(2, "processing first pass of auto mode...");
  297. /* first run through in auto mode: create tree */
  298. add_tree(ip_hdr->ip_src.s_addr, pktdata);
  299. break;
  300. case ROUTER_MODE:
  301. /*
  302. * second run through in auto mode: create route
  303. * based cache
  304. */
  305. dbg(2, "processing second pass of auto: router mode...");
  306. cache_result = add_cache(&options.cachedata, SEND,
  307. check_ip_cidr(options.cidrdata, ip_hdr->ip_src.s_addr));
  308. break;
  309. case BRIDGE_MODE:
  310. /*
  311. * second run through in auto mode: create bridge
  312. * based cache
  313. */
  314. dbg(2, "processing second pass of auto: bridge mode...");
  315. cache_result = add_cache(&options.cachedata, SEND,
  316. check_ip_tree(UNKNOWN, ip_hdr->ip_src.s_addr));
  317. break;
  318. case SERVER_MODE:
  319. /*
  320. * second run through in auto mode: create bridge
  321. * where unknowns are servers
  322. */
  323. dbg(2, "processing second pass of auto: server mode...");
  324. cache_result = add_cache(&options.cachedata, SEND,
  325. check_ip_tree(SERVER, ip_hdr->ip_src.s_addr));
  326. break;
  327. case CLIENT_MODE:
  328. /*
  329. * second run through in auto mode: create bridge
  330. * where unknowns are clients
  331. */
  332. dbg(2, "processing second pass of auto: client mode...");
  333. cache_result = add_cache(&options.cachedata, SEND,
  334. check_ip_tree(CLIENT, ip_hdr->ip_src.s_addr));
  335. break;
  336. case PORT_MODE:
  337. /*
  338. * process ports based on their destination port
  339. */
  340. dbg(2, "processing port mode...");
  341. cache_result = add_cache(&options.cachedata, SEND,
  342. check_dst_port(ip_hdr, (pkthdr.caplen - l2len)));
  343. break;
  344. }
  345. #ifdef HAVE_TCPDUMP
  346. if (options.verbose)
  347. tcpdump_print(&tcpdump, &pkthdr, pktdata);
  348. #endif
  349. }
  350. return packetnum;
  351. }
  352. /*
  353. * init our options
  354. */
  355. void
  356. init(void)
  357. {
  358. int i;
  359. memset(&options, '\0', sizeof(options));
  360. options.bpf.optimize = BPF_OPTIMIZE;
  361. for (i = DEFAULT_LOW_SERVER_PORT; i <= DEFAULT_HIGH_SERVER_PORT; i++) {
  362. options.services.tcp[i] = 1;
  363. options.services.udp[i] = 1;
  364. }
  365. options.max_mask = DEF_MAX_MASK;
  366. options.min_mask = DEF_MIN_MASK;
  367. options.ratio = DEF_RATIO;
  368. }
  369. /*
  370. * post process args
  371. */
  372. static void
  373. post_args(int argc, char *argv[])
  374. {
  375. char myargs[MYARGS_LEN];
  376. int i, bufsize;
  377. char *tempstr;
  378. memset(myargs, 0, MYARGS_LEN);
  379. /* print_comment and print_info don't return */
  380. if (HAVE_OPT(PRINT_COMMENT))
  381. print_comment(OPT_ARG(PRINT_COMMENT));
  382. if (HAVE_OPT(PRINT_INFO))
  383. print_info(OPT_ARG(PRINT_INFO));
  384. if (! HAVE_OPT(CACHEFILE) && ! HAVE_OPT(PCAP))
  385. err(1, "Must specify an output cachefile (-o) and input pcap (-i)");
  386. if (! options.mode)
  387. err(1, "Must specify a processing mode: -a, -c, -r, -p");
  388. #ifdef DEBUG
  389. if (HAVE_OPT(DBUG))
  390. debug = OPT_VALUE_DBUG;
  391. #endif
  392. #ifdef HAVE_TCPDUMP
  393. if (HAVE_OPT(VERBOSE)) {
  394. options.verbose = 1;
  395. }
  396. if (HAVE_OPT(DECODE))
  397. tcpdump.args = safe_strdup(OPT_ARG(DECODE));
  398. /*
  399. * put the open after decode options so they are passed to tcpdump
  400. */
  401. #endif
  402. /*
  403. * if we are to include the cli args, then prep it for the
  404. * cache file header
  405. */
  406. if (! options.nocomment) {
  407. /* copy all of our args to myargs */
  408. for (i = 1; i < argc; i ++) {
  409. /* skip the -C <comment> */
  410. if (strcmp(argv[i], "-C") == 0) {
  411. i += 2;
  412. continue;
  413. }
  414. strlcat(myargs, argv[i], MYARGS_LEN);
  415. strlcat(myargs, " ", MYARGS_LEN);
  416. }
  417. /* remove trailing space */
  418. myargs[strlen(myargs) - 1] = 0;
  419. dbg(1, "Comment args length: %d", strlen(myargs));
  420. }
  421. /* setup or options.comment buffer so that that we get args\ncomment */
  422. if (options.comment != NULL) {
  423. strlcat(myargs, "\n", MYARGS_LEN);
  424. bufsize = strlen(options.comment) + strlen(myargs) + 1;
  425. options.comment = (char *)safe_realloc(options.comment,
  426. bufsize);
  427. tempstr = strdup(options.comment);
  428. strlcpy(options.comment, myargs, bufsize);
  429. strlcat(options.comment, tempstr, bufsize);
  430. } else {
  431. bufsize = strlen(myargs) + 1;
  432. options.comment = (char *)safe_malloc(bufsize);
  433. strlcpy(options.comment, myargs, bufsize);
  434. }
  435. dbg(1, "Final comment length: %d", strlen(options.comment));
  436. /* copy over our min/max mask */
  437. if (HAVE_OPT(MINMASK))
  438. options.min_mask = OPT_VALUE_MINMASK;
  439. if (HAVE_OPT(MAXMASK))
  440. options.max_mask = OPT_VALUE_MAXMASK;
  441. if (! options.min_mask > options.max_mask)
  442. errx(1, "Min network mask len (%d) must be less then max network mask len (%d)",
  443. options.min_mask, options.max_mask);
  444. if (options.ratio < 0)
  445. err(1, "Ratio must be a non-negative number.");
  446. }
  447. /*
  448. * print the tcpprep cache file comment
  449. */
  450. static void
  451. print_comment(const char *file)
  452. {
  453. char *cachedata = NULL;
  454. char *comment = NULL;
  455. COUNTER count = 0;
  456. count = read_cache(&cachedata, file, &comment);
  457. printf("tcpprep args: %s\n", comment);
  458. printf("Cache contains data for " COUNTER_SPEC " packets\n", count);
  459. exit(0);
  460. }
  461. /*
  462. * prints out the cache file details
  463. */
  464. static void
  465. print_info(const char *file)
  466. {
  467. char *cachedata = NULL;
  468. char *comment = NULL;
  469. COUNTER count = 0, i;
  470. count = read_cache(&cachedata, file, &comment);
  471. for (i = 1; i <= count; i ++) {
  472. switch (check_cache(cachedata, i)) {
  473. case CACHE_PRIMARY:
  474. printf("Packet " COUNTER_SPEC " -> Primary\n", i);
  475. break;
  476. case CACHE_SECONDARY:
  477. printf("Packet " COUNTER_SPEC " -> Secondary\n", i);
  478. break;
  479. case CACHE_NOSEND:
  480. printf("Packet " COUNTER_SPEC " -> Don't Send\n", i);
  481. break;
  482. default:
  483. err(1, "Invalid cachedata value!");
  484. break;
  485. }
  486. }
  487. exit(0);
  488. }
  489. /*
  490. Local Variables:
  491. mode:c
  492. indent-tabs-mode:nil
  493. c-basic-offset:4
  494. End:
  495. */