Created
January 3, 2021 19:30
-
-
Save BobBurns/be670bb345c8ef73a60f3a84b1b84481 to your computer and use it in GitHub Desktop.
BPF filter machine 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/time.h> | |
#include <net/bpf.h> | |
#include <net/if.h> | |
#include <sys/ioctl.h> | |
#include <sys/socket.h> | |
#include <net/ethernet.h> // ETHERTYPE_IP | |
#include <netinet/in.h> // IPPROTO_TCP | |
#include <unistd.h> | |
#include <time.h> | |
int | |
main (int argc, char *argv[]) | |
{ | |
char buf[11] = "/dev/bpf0"; | |
int bpf = 0; | |
bpf = open (buf, O_RDWR); | |
if (bpf < 0) | |
{ | |
perror("open"); | |
exit(EXIT_FAILURE); | |
} | |
const char * interface = "em0"; | |
struct ifreq net_if; | |
bcopy (interface, net_if.ifr_name, sizeof(interface)); | |
if (ioctl (bpf, BIOCSETIF, &net_if) == -1 ) | |
{ | |
perror("ioctl"); | |
exit(EXIT_FAILURE); | |
} | |
if (ioctl (bpf, BIOCPROMISC) < 0 ) | |
{ | |
perror("promisc"); | |
exit(EXIT_FAILURE); | |
} | |
struct bpf_insn bf_insns[] = { | |
BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12), | |
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETHERTYPE_IP, 0, 3), | |
BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 26), | |
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x0a000076, 0, 1), | |
BPF_STMT(BPF_RET+BPF_K, (u_int)-1), | |
BPF_STMT(BPF_RET+BPF_K, 0) | |
}; | |
struct bpf_program bprog = { | |
sizeof(bf_insns) / sizeof(struct bpf_insn), | |
bf_insns | |
}; | |
if (ioctl (bpf, BIOCSETFNR, &bprog) < 0 ) | |
{ | |
perror("BIOCSETFNR"); | |
exit(EXIT_FAILURE); | |
} | |
int buf_len = 1; | |
// activate immediate mode (therefore, buf_len is initially set to "1") | |
if( ioctl( bpf, BIOCIMMEDIATE, &buf_len ) == -1 ) { | |
perror("BIOCIMMEDIATE"); | |
exit(EXIT_FAILURE); | |
} | |
// request buffer length | |
if( ioctl( bpf, BIOCGBLEN, &buf_len ) == -1 ) { | |
perror("BIOCGBLEN"); | |
exit(EXIT_FAILURE); | |
} | |
int read_bytes = 0; | |
// struct bpf_hdr* bpf_buf = calloc(buf_len, sizeof(struct bpf_hdr)); | |
int i; | |
struct bpf_hdr* bhdr; | |
unsigned char* bpf_buf = malloc(buf_len); | |
struct timeval tsmp; | |
char *t; | |
for (;;) { | |
if (( read_bytes = read (bpf, bpf_buf, buf_len)) > 0) | |
{ | |
bhdr = (struct bpf_hdr *)bpf_buf; | |
tsmp = bhdr->bh_tstamp; | |
t = ctime(&tsmp.tv_sec); | |
printf("time of packet:%s\n", t); | |
bpf_buf += bhdr->bh_hdrlen; | |
for (i = 0; i < bhdr->bh_caplen; i++) { | |
printf("%02X ", bpf_buf[i]); | |
} | |
for (i = 0; i < bhdr->bh_caplen; i++) { | |
printf("%c ", bpf_buf[i]); | |
} | |
printf("\nend\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment