Вопрос относится вобщем-то к Linux , но кто знает может и в win одни и теже методы используются. BPF фильтрует трафик приходящий на сетевой адаптер, библиотека libpcap использует BPF для установки фильтров, снифров..и тд ( ) Вобщем, вопрос прост. Каким образом этот BPF ставит перехватчик сетевых пакетов??!!?? В Linux есть свои фильтры (LSF) , я думал что это одно и тоже, что принцип действия один и тотже. Зарегистрировать перехватчик через функцию ядра nf_register_hook. Но когда запускаю одно из приложений использующее libpcap, nf_register_hook не используется а фильтры ставятся и действуют. Так как действуют приложения написанные на libpcap (как действует этот BPF)?? (просьба не посылать изучать исходники libpcap )
featurelles Ни у кого никаких догадок нет? Как-то не верится, что никто с этой библиотекой не сталкивался.
Чё за чушь? я спросил, вдруг кто сталкивался с его работой и знает , как происходит установка фильтров.
Я их просмотрел, там какая-то жопа. Кода уйма, всё на define. Яб сам справился, еслиб знал в какой из тамошних файлов смотреть. например смотрю libpcap-0.8.1/bpf/net/bpf_filter.c логично предполагая, что это то что нужно. Код (Text): /*- * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * This code is derived from the Stanford/CMU enet packet filter, * (net/enet.c) distributed as part of 4.3BSD, and code contributed * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence * Berkeley Laboratory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)bpf.c 7.5 (Berkeley) 7/15/91 */ #if !(defined(lint) || defined(KERNEL) || defined(_KERNEL)) static const char rcsid[] _U_ = "@(#) $Header: /tcpdump/master/libpcap/bpf/net/bpf_filter.c,v 1.43.2.1 2003/11/15 23:26:49 guy Exp $ (LBL)"; #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef WIN32 #include <pcap-stdinc.h> #else /* WIN32 */ #include <sys/param.h> #include <sys/types.h> #include <sys/time.h> #define SOLARIS (defined(sun) && (defined(__SVR4) || defined(__svr4__))) #if defined(__hpux) || SOLARIS # include <sys/sysmacros.h> # include <sys/stream.h> # define mbuf msgb # define m_next b_cont # define MLEN(m) ((m)->b_wptr - (m)->b_rptr) # define mtod(m,t) ((t)(m)->b_rptr) #else # define MLEN(m) ((m)->m_len) #endif #endif /* WIN32 */ #include <pcap-bpf.h> #if !defined(KERNEL) && !defined(_KERNEL) #include <stdlib.h> #endif #define int32 bpf_int32 #define u_int32 bpf_u_int32 #ifndef LBL_ALIGN /* * XXX - IA-64? If not, this probably won't work on Win64 IA-64 * systems, unless LBL_ALIGN is defined elsewhere for them. * XXX - SuperH? If not, this probably won't work on WinCE SuperH * systems, unless LBL_ALIGN is defined elsewhere for them. */ #if defined(sparc) || defined(__sparc__) || defined(mips) || \ defined(ibm032) || defined(__alpha) || defined(__hpux) || \ defined(__arm__) #define LBL_ALIGN #endif #endif #ifndef LBL_ALIGN #ifndef WIN32 #include <netinet/in.h> #endif #define EXTRACT_SHORT(p) ((u_short)ntohs(*(u_short *)p)) #define EXTRACT_LONG(p) (ntohl(*(u_int32 *)p)) #else #define EXTRACT_SHORT(p)\ ((u_short)\ ((u_short)*((u_char *)p+0)<<8|\ (u_short)*((u_char *)p+1)<<0)) #define EXTRACT_LONG(p)\ ((u_int32)*((u_char *)p+0)<<24|\ (u_int32)*((u_char *)p+1)<<16|\ (u_int32)*((u_char *)p+2)<<8|\ (u_int32)*((u_char *)p+3)<<0) #endif #if defined(KERNEL) || defined(_KERNEL) # if !defined(__hpux) && !SOLARIS #include <sys/mbuf.h> # endif #define MINDEX(len, _m, _k) \ { \ len = MLEN(m); \ while ((_k) >= len) { \ (_k) -= len; \ (_m) = (_m)->m_next; \ if ((_m) == 0) \ return 0; \ len = MLEN(m); \ } \ } static int m_xword(m, k, err) register struct mbuf *m; register int k, *err; { register int len; register u_char *cp, *np; register struct mbuf *m0; MINDEX(len, m, k); cp = mtod(m, u_char *) + k; if (len - k >= 4) { *err = 0; return EXTRACT_LONG(cp); } m0 = m->m_next; if (m0 == 0 || MLEN(m0) + len - k < 4) goto bad; *err = 0; np = mtod(m0, u_char *); switch (len - k) { case 1: return (cp[0] << 24) | (np[0] << 16) | (np[1] << 8) | np[2]; case 2: return (cp[0] << 24) | (cp[1] << 16) | (np[0] << 8) | np[1]; default: return (cp[0] << 24) | (cp[1] << 16) | (cp[2] << 8) | np[0]; } bad: *err = 1; return 0; } static int m_xhalf(m, k, err) register struct mbuf *m; register int k, *err; { register int len; register u_char *cp; register struct mbuf *m0; MINDEX(len, m, k); cp = mtod(m, u_char *) + k; if (len - k >= 2) { *err = 0; return EXTRACT_SHORT(cp); } m0 = m->m_next; if (m0 == 0) goto bad; *err = 0; return (cp[0] << 8) | mtod(m0, u_char *)[0]; bad: *err = 1; return 0; } #endif /* * Execute the filter program starting at pc on the packet p * wirelen is the length of the original packet * buflen is the amount of data present * For the kernel, p is assumed to be a pointer to an mbuf if buflen is 0, * in all other cases, p is a pointer to a buffer and buflen is its size. */ u_int bpf_filter(pc, p, wirelen, buflen) register struct bpf_insn *pc; register u_char *p; u_int wirelen; register u_int buflen; { register u_int32 A, X; register int k; int32 mem[BPF_MEMWORDS]; #if defined(KERNEL) || defined(_KERNEL) struct mbuf *m, *n; int merr, len; if (buflen == 0) { m = (struct mbuf *)p; p = mtod(m, u_char *); buflen = MLEN(m); } else m = NULL; #endif if (pc == 0) /* * No filter means accept all. */ return (u_int)-1; A = 0; X = 0; --pc; while (1) { ++pc; switch (pc->code) { default: #if defined(KERNEL) || defined(_KERNEL) return 0; #else abort(); #endif case BPF_RET|BPF_K: return (u_int)pc->k; case BPF_RET|BPF_A: return (u_int)A; case BPF_LD|BPF_W|BPF_ABS: k = pc->k; if (k + sizeof(int32) > buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; A = m_xword(m, k, &merr); if (merr != 0) return 0; continue; #else return 0; #endif } A = EXTRACT_LONG(&p[k]); continue; case BPF_LD|BPF_H|BPF_ABS: k = pc->k; if (k + sizeof(short) > buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; A = m_xhalf(m, k, &merr); if (merr != 0) return 0; continue; #else return 0; #endif } A = EXTRACT_SHORT(&p[k]); continue; case BPF_LD|BPF_B|BPF_ABS: k = pc->k; if (k >= buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; n = m; MINDEX(len, n, k); A = mtod(n, u_char *)[k]; continue; #else return 0; #endif } A = p[k]; continue; case BPF_LD|BPF_W|BPF_LEN: A = wirelen; continue; case BPF_LDX|BPF_W|BPF_LEN: X = wirelen; continue; case BPF_LD|BPF_W|BPF_IND: k = X + pc->k; if (k + sizeof(int32) > buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; A = m_xword(m, k, &merr); if (merr != 0) return 0; continue; #else return 0; #endif } A = EXTRACT_LONG(&p[k]); continue; case BPF_LD|BPF_H|BPF_IND: k = X + pc->k; if (k + sizeof(short) > buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; A = m_xhalf(m, k, &merr); if (merr != 0) return 0; continue; #else return 0; #endif } A = EXTRACT_SHORT(&p[k]); continue; case BPF_LD|BPF_B|BPF_IND: k = X + pc->k; if (k >= buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; n = m; MINDEX(len, n, k); A = mtod(n, u_char *)[k]; continue; #else return 0; #endif } A = p[k]; continue; case BPF_LDX|BPF_MSH|BPF_B: k = pc->k; if (k >= buflen) { #if defined(KERNEL) || defined(_KERNEL) if (m == NULL) return 0; n = m; MINDEX(len, n, k); X = (mtod(n, char *)[k] & 0xf) << 2; continue; #else return 0; #endif } X = (p[pc->k] & 0xf) << 2; continue; case BPF_LD|BPF_IMM: A = pc->k; continue; case BPF_LDX|BPF_IMM: X = pc->k; continue; case BPF_LD|BPF_MEM: A = mem[pc->k]; continue; case BPF_LDX|BPF_MEM: X = mem[pc->k]; continue; case BPF_ST: mem[pc->k] = A; continue; case BPF_STX: mem[pc->k] = X; continue; case BPF_JMP|BPF_JA: pc += pc->k; continue; case BPF_JMP|BPF_JGT|BPF_K: pc += (A > pc->k) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JGE|BPF_K: pc += (A >= pc->k) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JEQ|BPF_K: pc += (A == pc->k) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JSET|BPF_K: pc += (A & pc->k) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JGT|BPF_X: pc += (A > X) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JGE|BPF_X: pc += (A >= X) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JEQ|BPF_X: pc += (A == X) ? pc->jt : pc->jf; continue; case BPF_JMP|BPF_JSET|BPF_X: pc += (A & X) ? pc->jt : pc->jf; continue; case BPF_ALU|BPF_ADD|BPF_X: A += X; continue; case BPF_ALU|BPF_SUB|BPF_X: A -= X; continue; case BPF_ALU|BPF_MUL|BPF_X: A *= X; continue; case BPF_ALU|BPF_DIV|BPF_X: if (X == 0) return 0; A /= X; continue; case BPF_ALU|BPF_AND|BPF_X: A &= X; continue; case BPF_ALU|BPF_OR|BPF_X: A |= X; continue; case BPF_ALU|BPF_LSH|BPF_X: A <<= X; continue; case BPF_ALU|BPF_RSH|BPF_X: A >>= X; continue; case BPF_ALU|BPF_ADD|BPF_K: A += pc->k; continue; case BPF_ALU|BPF_SUB|BPF_K: A -= pc->k; continue; case BPF_ALU|BPF_MUL|BPF_K: A *= pc->k; continue; case BPF_ALU|BPF_DIV|BPF_K: A /= pc->k; continue; case BPF_ALU|BPF_AND|BPF_K: A &= pc->k; continue; case BPF_ALU|BPF_OR|BPF_K: A |= pc->k; continue; case BPF_ALU|BPF_LSH|BPF_K: A <<= pc->k; continue; case BPF_ALU|BPF_RSH|BPF_K: A >>= pc->k; continue; case BPF_ALU|BPF_NEG: A = -A; continue; case BPF_MISC|BPF_TAX: X = A; continue; case BPF_MISC|BPF_TXA: A = X; continue; } } } /* * Return true if the 'fcode' is a valid filter program. * The constraints are that each jump be forward and to a valid * code. The code must terminate with either an accept or reject. * 'valid' is an array for use by the routine (it must be at least * 'len' bytes long). * * The kernel needs to be able to verify an application's filter code. * Otherwise, a bogus program could easily crash the system. */ int bpf_validate(f, len) struct bpf_insn *f; int len; { register int i; register struct bpf_insn *p; for (i = 0; i < len; ++i) { /* * Check that that jumps are forward, and within * the code block. */ p = &f[i]; if (BPF_CLASS(p->code) == BPF_JMP) { register int from = i + 1; if (BPF_OP(p->code) == BPF_JA) { if (from + p->k >= (unsigned)len) return 0; } else if (from + p->jt >= len || from + p->jf >= len) return 0; } /* * Check that memory operations use valid addresses. */ if ((BPF_CLASS(p->code) == BPF_ST || (BPF_CLASS(p->code) == BPF_LD && (p->code & 0xe0) == BPF_MEM)) && (p->k >= BPF_MEMWORDS || p->k < 0)) return 0; /* * Check for constant division by 0. */ if (p->code == (BPF_ALU|BPF_DIV|BPF_K) && p->k == 0) return 0; } return BPF_CLASS(f[len - 1].code) == BPF_RET; } Но почемуто мне кажется это не то (я ничего не понимаю что там понаписано) Уверен что нужный мне код, находится в файле pcap-linux.c так как она подключает "нужные файлы" #include <linux/filter.h> #include <net/if.h> #include <netinet/in.h> #include <linux/if_ether.h> #include <net/if_arp.h> да и функции, "правильные" static void map_arphrd_to_dlt(pcap_t *, int, int); static int live_open_old(pcap_t *, const char *, int, int, char *); static int live_open_new(pcap_t *, const char *, int, int, char *); static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *); static int pcap_read_packet(pcap_t *, pcap_handler, u_char *); static int pcap_stats_linux(pcap_t *, struct pcap_stat *); static int pcap_setfilter_linux(pcap_t *, struct bpf_program *); static void pcap_close_linux(pcap_t *); Вот код функции регистрации фильтра Код (Text): static int pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter) { #ifdef SO_ATTACH_FILTER struct sock_fprog fcode; int can_filter_in_kernel; int err = 0; #endif if (!handle) return -1; if (!filter) { strncpy(handle->errbuf, "setfilter: No filter specified", sizeof(handle->errbuf)); return -1; } /* Make our private copy of the filter */ if (install_bpf_program(handle, filter) < 0) /* install_bpf_program() filled in errbuf */ return -1; /* * Run user level packet filter by default. Will be overriden if * installing a kernel filter succeeds. */ handle->md.use_bpf = 0; /* Install kernel level filter if possible */ #ifdef SO_ATTACH_FILTER #ifdef USHRT_MAX if (handle->fcode.bf_len > USHRT_MAX) { /* * fcode.len is an unsigned short for current kernel. * I have yet to see BPF-Code with that much * instructions but still it is possible. So for the * sake of correctness I added this check. */ fprintf(stderr, "Warning: Filter too complex for kernel\n"); fcode.filter = NULL; can_filter_in_kernel = 0; } else #endif /* USHRT_MAX */ { /* * Oh joy, the Linux kernel uses struct sock_fprog instead * of struct bpf_program and of course the length field is * of different size. Pointed out by Sebastian * * Oh, and we also need to fix it up so that all "ret" * instructions with non-zero operands have 65535 as the * operand, and so that, if we're in cooked mode, all * memory-reference instructions use special magic offsets * in references to the link-layer header and assume that * the link-layer payload begins at 0; "fix_program()" * will do that. */ switch (fix_program(handle, &fcode)) { case -1: default: /* * Fatal error; just quit. * (The "default" case shouldn't happen; we * return -1 for that reason.) */ return -1; case 0: /* * The program performed checks that we can't make * work in the kernel. */ can_filter_in_kernel = 0; break; case 1: /* * We have a filter that'll work in the kernel. */ can_filter_in_kernel = 1; break; } } if (can_filter_in_kernel) { if ((err = set_kernel_filter(handle, &fcode)) == 0) { /* Installation succeded - using kernel filter. */ handle->md.use_bpf = 1; } else if (err == -1) /* Non-fatal error */ { /* * Print a warning if we weren't able to install * the filter for a reason other than "this kernel * isn't configured to support socket filters. */ if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) { fprintf(stderr, "Warning: Kernel filter failed: %s\n", pcap_strerror(errno)); } } } /* * If we're not using the kernel filter, get rid of any kernel * filter that might've been there before, e.g. because the * previous filter could work in the kernel, or because some other * code attached a filter to the socket by some means other than * calling "pcap_setfilter()". Otherwise, the kernel filter may * filter out packets that would pass the new userland filter. */ if (!handle->md.use_bpf) reset_kernel_filter(handle); /* * Free up the copy of the filter that was made by "fix_program()". */ if (fcode.filter != NULL) free(fcode.filter); if (err == -2) /* Fatal error */ return -1; #endif /* SO_ATTACH_FILTER */ return 0; } Из этой функции вызывается set_kernel_filter смотрю эту функцию. И не вижу ничего. Код (Text): static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode) { int total_filter_on = 0; int save_mode; int ret; int save_errno; /* * The socket filter code doesn't discard all packets queued * up on the socket when the filter is changed; this means * that packets that don't match the new filter may show up * after the new filter is put onto the socket, if those * packets haven't yet been read. * * This means, for example, that if you do a tcpdump capture * with a filter, the first few packets in the capture might * be packets that wouldn't have passed the filter. * * We therefore discard all packets queued up on the socket * when setting a kernel filter. (This isn't an issue for * userland filters, as the userland filtering is done after * packets are queued up.) * * To flush those packets, we put the socket in read-only mode, * and read packets from the socket until there are no more to * read. * * In order to keep that from being an infinite loop - i.e., * to keep more packets from arriving while we're draining * the queue - we put the "total filter", which is a filter * that rejects all packets, onto the socket before draining * the queue. * * This code deliberately ignores any errors, so that you may * get bogus packets if an error occurs, rather than having * the filtering done in userland even if it could have been * done in the kernel. */ if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER, &total_fcode, sizeof(total_fcode)) == 0) { char drain[1]; /* * Note that we've put the total filter onto the socket. */ total_filter_on = 1; /* * Save the socket's current mode, and put it in * non-blocking mode; we drain it by reading packets * until we get an error (which is normally a * "nothing more to be read" error). */ save_mode = fcntl(handle->fd, F_GETFL, 0); if (save_mode != -1 && fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) { while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0) ; save_errno = errno; fcntl(handle->fd, F_SETFL, save_mode); if (save_errno != EAGAIN) { /* Fatal error */ reset_kernel_filter(handle); snprintf(handle->errbuf, sizeof(handle->errbuf), "recv: %s", pcap_strerror(save_errno)); return -2; } } } /* * Now attach the new filter. */ ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER, fcode, sizeof(*fcode)); if (ret == -1 && total_filter_on) { /* * Well, we couldn't set that filter on the socket, * but we could set the total filter on the socket. * * This could, for example, mean that the filter was * too big to put into the kernel, so we'll have to * filter in userland; in any case, we'll be doing * filtering in userland, so we need to remove the * total filter so we see packets. */ save_errno = errno; /* * XXX - if this fails, we're really screwed; * we have the total filter on the socket, * and it won't come off. What do we do then? */ reset_kernel_filter(handle); errno = save_errno; } return ret; } просмотрел функцию pcap_read_packet Там есть такой участок if (!handle->md.use_bpf && handle->fcode.bf_insns) { if (bpf_filter(handle->fcode.bf_insns, bp, packet_len, caplen) == 0) { /* rejected by filter */ return 0; } направляюсь к функции bpf_filter она находится в /libpcap-0.8.1/bpf/net/bpf_filter.c И нихрена не понимаю..что происходит дальше???? Никак не могу разобраться как этот bpf действует!
featurelles в приведенном тобой коде - ищи описания struct sock_fprog и setsockopt(... SOL_SOCKET, SO_ATTACH_FILTER...), они должны прояснить ситуацию.
Привет! Я столкнулся с подобной ситуацыей, толко в Packet.dll (из состава WinPcap). Вот что извесно!! A single BPF pseudo-instruction. bpf_insn contains a single instruction for the BPF register-machine. It is used to send a filter program to the driver. ' TYPE bpf_insn code AS WORD '< Instruction Type And addressing mode. jt AS BYTE '< Jump If true jf AS BYTE '< Jump If false k AS LONG '< Generic field used For various purposes. END TYPE A BPF pseudo-assembly program. The program will be injected in the kernel by the PacketSetBPF() function and applied to every incoming packet. TYPE bpf_program bf_len AS DWORD '< Indicates the number of instructions of the program, i.e. the number of struct bpf_insn that will follow. bf_insns AS bpf_insn PTR '< A pointer to the first instruction of the program. END TYPE Но самих команд ненашол! Итересно как у тебя обстоят дела!?