tcpdump.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /* $Id: tcpdump.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. /*
  32. * This code allows us to use tcpdump to print packet decodes.
  33. * Basically, we create a local AF_UNIX socketpair, fork a copy
  34. * of ourselves, link 1/2 of the pair to STDIN of the child and
  35. * replace the child with tcpdump. We then send a "pcap" file
  36. * over the socket so that tcpdump can print it's decode to STDOUT.
  37. *
  38. * Idea and a lot of code stolen from Christain Kreibich's
  39. * <christian@whoop.org> libnetdude 0.4 code. Any bugs are mine. :)
  40. *
  41. * This product includes software developed by the University of California,
  42. * Lawrence Berkeley Laboratory and its contributors
  43. */
  44. #include "config.h"
  45. #include "defines.h"
  46. #include "common.h"
  47. #include <sys/types.h>
  48. #include <unistd.h>
  49. #include <sys/socket.h>
  50. #include <sys/wait.h>
  51. #include <errno.h>
  52. #include <string.h>
  53. #ifdef HAVE_SIGNAL_H
  54. #include <signal.h>
  55. #endif
  56. #include "tcpdump.h"
  57. #include "lib/strlcpy.h"
  58. #ifdef DEBUG
  59. extern int debug;
  60. #endif
  61. char *options_vec[OPTIONS_VEC_SIZE];
  62. static int tcpdump_fill_in_options(char *opt);
  63. static int can_exec(const char *filename);
  64. /**
  65. * given a packet, print a decode of via tcpdump
  66. */
  67. int
  68. tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data)
  69. {
  70. struct pollfd poller[1];
  71. int result;
  72. char decode[TCPDUMP_DECODE_LEN];
  73. assert(tcpdump);
  74. assert(pkthdr);
  75. assert(data);
  76. poller[0].fd = tcpdump->infd;
  77. poller[0].events = POLLOUT;
  78. poller[0].revents = 0;
  79. /* wait until we can write to the tcpdump socket */
  80. result = poll(poller, 1, TCPDUMP_POLL_TIMEOUT);
  81. if (result < 0)
  82. errx(1, "Error during poll() to write to tcpdump\n%s", strerror(errno));
  83. if (result == 0)
  84. err(1, "poll() timeout... tcpdump seems to be having a problem keeping up\n"
  85. "Try increasing TCPDUMP_POLL_TIMEOUT");
  86. /* result > 0 if we get here */
  87. if (write(tcpdump->infd, (char *)pkthdr, sizeof(struct pcap_pkthdr))
  88. != sizeof(struct pcap_pkthdr))
  89. errx(1, "Error writing pcap file header to tcpdump\n%s", strerror(errno));
  90. #ifdef DEBUG
  91. if (debug >= 5) {
  92. if (write(tcpdump->debugfd, (char *)pkthdr, sizeof(struct pcap_pkthdr))
  93. != sizeof(struct pcap_pkthdr))
  94. errx(1, "Error writing pcap file header to tcpdump debug\n%s", strerror(errno));
  95. }
  96. #endif
  97. if (write(tcpdump->infd, data, pkthdr->caplen) != (ssize_t)pkthdr->caplen)
  98. errx(1, "Error writing packet data to tcpdump\n%s", strerror(errno));
  99. #ifdef DEBUG
  100. if (debug >= 5) {
  101. if (write(tcpdump->debugfd, data, pkthdr->caplen) != (ssize_t)pkthdr->caplen)
  102. errx(1, "Error writing packet data to tcpdump debug\n%s", strerror(errno));
  103. }
  104. #endif
  105. /* Wait for output from tcpdump */
  106. poller[0].fd = tcpdump->outfd;
  107. poller[0].events = POLLIN;
  108. poller[0].revents = 0;
  109. result = poll(poller, 1, TCPDUMP_POLL_TIMEOUT);
  110. if (result < 0)
  111. errx(1, "Error during poll() to write to tcpdump\n%s", strerror(errno));
  112. if (result == 0)
  113. err(1, "poll() timeout... tcpdump seems to be having a problem keeping up\n"
  114. "Try increasing TCPDUMP_POLL_TIMEOUT");
  115. /* result > 0 if we get here */
  116. if (read(tcpdump->outfd, &decode, TCPDUMP_DECODE_LEN) < 0)
  117. errx(1, "Error reading tcpdump decode: %s", strerror(errno));
  118. printf("%s", decode);
  119. return TRUE;
  120. }
  121. /**
  122. * init our tcpdump handle using the given pcap handle
  123. * Basically, this starts up tcpdump as a child and communicates
  124. * to it via a pair of sockets (stdout/stdin)
  125. */
  126. int
  127. tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap)
  128. {
  129. int infd[2], outfd[2];
  130. FILE *writer;
  131. assert(tcpdump);
  132. assert(pcap);
  133. if (tcpdump->pid != 0) {
  134. warn("tcpdump process already running");
  135. return FALSE;
  136. }
  137. /* is tcpdump executable? */
  138. if (! can_exec(TCPDUMP_BINARY)) {
  139. errx(1, "Unable to execute tcpdump binary: %s", TCPDUMP_BINARY);
  140. }
  141. #ifdef DEBUG
  142. strlcpy(tcpdump->debugfile, TCPDUMP_DEBUG, sizeof(tcpdump->debugfile));
  143. if (debug >= 5) {
  144. dbgx(5, "Opening tcpdump debug file: %s", tcpdump->debugfile);
  145. if ((tcpdump->debugfd = open(tcpdump->debugfile, O_WRONLY|O_CREAT|O_TRUNC,
  146. S_IREAD|S_IWRITE|S_IRGRP|S_IROTH)) == -1) {
  147. errx(1, "Error opening tcpdump debug file: %s\n%s", tcpdump->debugfile, strerror(errno));
  148. }
  149. }
  150. #endif
  151. /* copy over the args */
  152. dbg(2, "Prepping tcpdump options...");
  153. tcpdump_fill_in_options(tcpdump->args);
  154. dbg(2, "Starting tcpdump...");
  155. /* create our socket pair to send packet data to tcpdump via */
  156. if (socketpair(AF_UNIX, SOCK_STREAM, 0, infd) < 0)
  157. errx(1, "Unable to create stdin socket pair: %s", strerror(errno));
  158. /* create our socket pair to read packet decode from tcpdump */
  159. if (socketpair(AF_UNIX, SOCK_STREAM, 0, outfd) < 0)
  160. errx(1, "Unable to create stdout socket pair: %s", strerror(errno));
  161. if ((tcpdump->pid = fork() ) < 0)
  162. errx(1, "Fork failed: %s", strerror(errno));
  163. dbgx(2, "tcpdump pid: %d", tcpdump->pid);
  164. if (tcpdump->pid > 0) {
  165. /* we're still in tcpreplay */
  166. dbgx(2, "[parent] closing input fd %d", infd[1]);
  167. close(infd[1]); /* close the tcpdump side */
  168. dbgx(2, "[parent] closing output fd %d", outfd[1]);
  169. close(outfd[1]);
  170. tcpdump->infd = infd[0];
  171. tcpdump->outfd = outfd[0];
  172. /* send the pcap file header to tcpdump */
  173. writer = fdopen(tcpdump->infd, "w");
  174. if ((tcpdump->dumper = pcap_dump_fopen(pcap, writer)) == NULL) {
  175. warnx("[parent] pcap_dump_fopen(): %s", pcap_geterr(pcap));
  176. return FALSE;
  177. }
  178. pcap_dump_flush(tcpdump->dumper);
  179. if (fcntl(tcpdump->infd, F_SETFL, O_NONBLOCK) < 0)
  180. warnx("[parent] Unable to fcntl tcpreplay socket:\n%s", strerror(errno));
  181. if (fcntl(tcpdump->outfd, F_SETFL, O_NONBLOCK) < 0)
  182. warnx("[parent] Unable to fnctl stdout socket:\n%s", strerror(errno));
  183. }
  184. else {
  185. dbg(2, "[child] started the kid");
  186. /* we're in the child process */
  187. dbgx(2, "[child] closing in fd %d", infd[0]);
  188. dbgx(2, "[child] closing out fd %d", outfd[0]);
  189. close(infd[0]); /* close the tcpreplay side */
  190. close(outfd[0]);
  191. /* copy our side of the socketpair to our stdin */
  192. if (infd[1] != STDIN_FILENO) {
  193. if (dup2(infd[1], STDIN_FILENO) != STDIN_FILENO)
  194. errx(1, "[child] Unable to copy socket to stdin: %s",
  195. strerror(errno));
  196. }
  197. /* copy our side of the socketpair to our stdout */
  198. if (outfd[1] != STDOUT_FILENO) {
  199. if (dup2(outfd[1], STDOUT_FILENO) != STDOUT_FILENO)
  200. errx(1, "[child] Unable to copy socket to stdout: %s",
  201. strerror(errno));
  202. }
  203. /* exec tcpdump */
  204. dbg(2, "[child] Exec'ing tcpdump...");
  205. if (execv(TCPDUMP_BINARY, options_vec) < 0)
  206. errx(1, "Unable to exec tcpdump: %s", strerror(errno));
  207. }
  208. return TRUE;
  209. }
  210. /**
  211. * shutdown tcpdump
  212. */
  213. void
  214. tcpdump_close(tcpdump_t *tcpdump)
  215. {
  216. if (! tcpdump)
  217. return;
  218. if (tcpdump->pid <= 0)
  219. return;
  220. dbgx(2, "[parent] killing tcpdump pid: %d", tcpdump->pid);
  221. kill(tcpdump->pid, SIGKILL);
  222. close(tcpdump->infd);
  223. close(tcpdump->outfd);
  224. if (waitpid(tcpdump->pid, NULL, 0) != tcpdump->pid)
  225. errx(1, "[parent] Error in waitpid: %s", strerror(errno));
  226. tcpdump->pid = 0;
  227. tcpdump->infd = 0;
  228. tcpdump->outfd = 0;
  229. }
  230. /**
  231. * forcefully kill tcpdump
  232. */
  233. void
  234. tcpdump_kill(tcpdump_t *tcpdump)
  235. {
  236. if (tcpdump->pid) {
  237. if (kill(tcpdump->pid, SIGTERM) != 0) {
  238. kill(tcpdump->pid, SIGKILL);
  239. }
  240. }
  241. tcpdump->infd = 0;
  242. tcpdump->outfd = 0;
  243. tcpdump->pid = 0;
  244. }
  245. /**
  246. * copy the string of args (*opt) to the vector (**opt_vec)
  247. * for a max of opt_len. Returns the number of options
  248. * in the vector
  249. */
  250. static int
  251. tcpdump_fill_in_options(char *opt)
  252. {
  253. char options[256];
  254. char *arg, *newarg;
  255. int i = 1, arglen;
  256. char *token = NULL;
  257. /* zero out our options_vec for execv() */
  258. memset(options_vec, '\0', OPTIONS_VEC_SIZE);
  259. /* first arg should be the binary (by convention) */
  260. options_vec[0] = TCPDUMP_BINARY;
  261. /* prep args */
  262. memset(options, '\0', 256);
  263. if (opt != NULL) {
  264. strlcat(options, opt, sizeof(options));
  265. }
  266. strlcat(options, TCPDUMP_ARGS, sizeof(options));
  267. dbgx(2, "[child] Will execute: tcpdump %s", options);
  268. /* process args */
  269. /* process the first argument */
  270. arg = strtok_r(options, OPT_DELIM, &token);
  271. arglen = strlen(arg) + 2; /* -{arg}\0 */
  272. newarg = (char *)safe_malloc(arglen);
  273. strlcat(newarg, "-", arglen);
  274. strlcat(newarg, arg, arglen);
  275. options_vec[i++] = newarg;
  276. /* process the remaining args
  277. note that i < OPTIONS_VEC_SIZE - 1
  278. because: a) we need to add '-' as an option to the end
  279. b) because the array has to be null terminated
  280. */
  281. while (((arg = strtok_r(NULL, OPT_DELIM, &token)) != NULL) &&
  282. (i < OPTIONS_VEC_SIZE - 1)) {
  283. arglen = strlen(arg) + 2;
  284. newarg = (char *)safe_malloc(arglen);
  285. strlcat(newarg, "-", arglen);
  286. strlcat(newarg, arg, arglen);
  287. options_vec[i++] = newarg;
  288. }
  289. /* tell -r to read from stdin */
  290. options_vec[i] = "-";
  291. return(i);
  292. }
  293. /**
  294. * can we exec the given file?
  295. */
  296. static int
  297. can_exec(const char *filename)
  298. {
  299. struct stat st;
  300. if (!filename || filename[0] == '\0')
  301. return FALSE;
  302. /* Stat the file to see if it's executable and
  303. if the user may run it.
  304. */
  305. if (lstat(filename, &st) < 0)
  306. return FALSE;
  307. if ((st.st_mode & S_IXUSR) ||
  308. (st.st_mode & S_IXGRP) ||
  309. (st.st_mode & S_IXOTH))
  310. return TRUE;
  311. return FALSE;
  312. }