AF_PACKET으로 이더넷 패킷 캡처
다음 C 코드는 리눅스에서 패킷을 캡처해 Ethernet 헤더와 페이로드를 콘솔에 출력한다.
ethernet.c
#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <stddef.h>#include <stdint.h>#include <string.h>#include <ctype.h>#include <limits.h>#include <unistd.h>#include <errno.h>#include <poll.h>#include <signal.h>#include <time.h>#include <net/if.h>#include <sys/socket.h>#include <asm/byteorder.h>#include <linux/types.h>#include <linux/if_arp.h>#include <linux/if_ether.h>#include <linux/if_packet.h>#include <linux/sock_diag.h>#define FRAME_BUFFER_SIZE 65536U#define ETH_PAYLOAD_MAX (FRAME_BUFFER_SIZE - ETH_HLEN)#define SOCKET_RCVBUF_SIZE (2 * 1024 * 1024)#define PROG_NAME_MAX 256U#define WIDTH_TEXT_MAX 8U#define NSEC_PER_SEC 1000000000L#define HEXDUMP_DEFAULT_WIDTH 8U#define HEXDUMP_MAX_WIDTH 256U#define HEXDUMP_PREFIX_MAX (sizeof(" 0x:") - 1 + 2 * sizeof(size_t))#define HEXDUMP_LINE_SIZE (HEXDUMP_PREFIX_MAX + 3 * HEXDUMP_MAX_WIDTH + sizeof("\n"))#define VLAN_HLEN 4U#define VLAN_PRIO_MASK 0xe000U#define VLAN_PRIO_SHIFT 13U#define VLAN_VID_MASK 0x0fffUunion eth_frame { struct { struct ethhdr hdr; __u8 payload[ETH_PAYLOAD_MAX]; }; __u8 raw[FRAME_BUFFER_SIZE];};struct frame_info { struct timespec ts; size_t len; size_t caplen; struct sockaddr_ll sll; struct tpacket_auxdata aux;};static volatile sig_atomic_t stop_signal;static void request_stop(int signo){ if (signo == SIGINT || signo == SIGTERM) { stop_signal = signo; }}static int install_signal_handlers(void){ struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = request_stop; if (sigemptyset(&sa.sa_mask) < 0) { perror("sigemptyset"); return -1; } if (sigaction(SIGINT, &sa, NULL) < 0 || sigaction(SIGTERM, &sa, NULL) < 0) { perror("sigaction"); return -1; } return 0;}static const char *display_name(const char *name){ size_t len; size_t i; if (name == NULL) { return "ethernet"; } len = strnlen(name, PROG_NAME_MAX); if (len == 0 || len >= PROG_NAME_MAX) { return "ethernet"; } for (i = 0; i < len; ++i) { if (!isprint((unsigned char)name[i])) { return "ethernet"; } } return name;}static int parse_width(const char *text, size_t *width){ unsigned long value; char *end; size_t len; size_t i; if (text == NULL || width == NULL) { return -1; } len = strnlen(text, WIDTH_TEXT_MAX + 1); if (len == 0 || len > WIDTH_TEXT_MAX) { return -1; } for (i = 0; i < len; ++i) { if (!isdigit((unsigned char)text[i])) { return -1; } } errno = 0; value = strtoul(text, &end, 10); if (errno != 0 || end != text + len || value == 0 || value > HEXDUMP_MAX_WIDTH) { return -1; } *width = value; return 0;}static int valid_ifname(const char *name){ size_t len; size_t i; if (name == NULL) { return 0; } len = strnlen(name, IF_NAMESIZE); if (len == 0 || len >= IF_NAMESIZE || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { return 0; } for (i = 0; i < len; ++i) { unsigned char c = (unsigned char)name[i]; if (!isgraph(c) || c == '/' || c == ':') { return 0; } } return 1;}static int create_socket(const char *ifname){ struct sockaddr_ll sll; struct packet_mreq mreq; unsigned int ifindex = 0; int rcvbuf = SOCKET_RCVBUF_SIZE; int one = 1; int fd; if (ifname != NULL && !valid_ifname(ifname)) { fprintf(stderr, "invalid interface name\n"); return -1; } fd = socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); if (fd < 0) { perror("socket"); return -1; } if (ifname != NULL) { ifindex = if_nametoindex(ifname); if (ifindex == 0) { perror("if_nametoindex"); close(fd); return -1; } if (ifindex > INT_MAX) { fprintf(stderr, "interface index out of range\n"); close(fd); return -1; } } if (setsockopt(fd, SOL_PACKET, PACKET_AUXDATA, &one, sizeof(one)) < 0) { perror("setsockopt(PACKET_AUXDATA)"); close(fd); return -1; } if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPNS, &one, sizeof(one)) < 0) { perror("setsockopt(SO_TIMESTAMPNS)"); close(fd); return -1; } if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &rcvbuf, sizeof(rcvbuf)) < 0 && setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) < 0) { perror("setsockopt(SO_RCVBUF)"); close(fd); return -1; } memset(&sll, 0, sizeof(sll)); sll.sll_family = AF_PACKET; sll.sll_protocol = __cpu_to_be16(ETH_P_ALL); sll.sll_ifindex = (int)ifindex; if (bind(fd, (struct sockaddr *)&sll, sizeof(sll)) < 0) { perror("bind"); close(fd); return -1; } if (ifname == NULL) { return fd; } memset(&mreq, 0, sizeof(mreq)); mreq.mr_ifindex = (int)ifindex; mreq.mr_type = PACKET_MR_PROMISC; if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { perror("setsockopt(PACKET_MR_PROMISC)"); close(fd); return -1; } return fd;}static int wait_for_frame(int fd){ struct pollfd pfd; sigset_t stop_signals; sigset_t wait_mask; int ret = 0; if (fd < 0) { errno = EBADF; perror("ppoll"); return -1; } if (sigemptyset(&stop_signals) < 0 || sigaddset(&stop_signals, SIGINT) < 0 || sigaddset(&stop_signals, SIGTERM) < 0) { perror("sigaddset"); return -1; } if (sigprocmask(SIG_BLOCK, &stop_signals, &wait_mask) < 0) { perror("sigprocmask"); return -1; } pfd.fd = fd; pfd.events = POLLIN; pfd.revents = 0; if (stop_signal == 0 && ppoll(&pfd, 1, NULL, &wait_mask) < 0 && errno != EINTR) { perror("ppoll"); ret = -1; } if (sigprocmask(SIG_SETMASK, &wait_mask, NULL) < 0) { perror("sigprocmask"); ret = -1; } if (ret == 0 && (pfd.revents & POLLNVAL)) { errno = EBADF; perror("ppoll"); ret = -1; } return ret;}static int receive_frame(int fd, union eth_frame *frame, struct frame_info *info){ union { char buf[CMSG_SPACE(sizeof(struct timespec)) + CMSG_SPACE(sizeof(struct tpacket_auxdata))]; struct cmsghdr align_noused; } control; struct cmsghdr *cmsg; struct msghdr msg; struct iovec iov; ssize_t n; if (fd < 0 || frame == NULL || info == NULL) { errno = EINVAL; return -1; } memset(info, 0, sizeof(*info)); info->ts.tv_nsec = -1; iov.iov_base = frame->raw; iov.iov_len = sizeof(frame->raw); memset(&msg, 0, sizeof(msg)); msg.msg_name = &info->sll; msg.msg_namelen = sizeof(info->sll); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control.buf; msg.msg_controllen = sizeof(control.buf); n = recvmsg(fd, &msg, MSG_TRUNC); if (n < 0) { return -1; } if (msg.msg_namelen < offsetof(struct sockaddr_ll, sll_addr) || info->sll.sll_family != AF_PACKET || info->sll.sll_ifindex <= 0) { return 0; } if (!(msg.msg_flags & MSG_CTRUNC)) { for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMPNS && cmsg->cmsg_len >= CMSG_LEN(sizeof(info->ts))) { memcpy(&info->ts, CMSG_DATA(cmsg), sizeof(info->ts)); } else if (cmsg->cmsg_level == SOL_PACKET && cmsg->cmsg_type == PACKET_AUXDATA && cmsg->cmsg_len >= CMSG_LEN(sizeof(info->aux))) { memcpy(&info->aux, CMSG_DATA(cmsg), sizeof(info->aux)); } } } info->len = (size_t)n; info->caplen = info->len; if (info->caplen > sizeof(frame->raw)) { info->caplen = sizeof(frame->raw); } return 1;}static int is_ethernet_frame(const struct frame_info *info){ if (info == NULL) { return 0; } return (info->sll.sll_hatype == ARPHRD_ETHER || info->sll.sll_hatype == ARPHRD_LOOPBACK) && info->caplen >= ETH_HLEN && info->caplen <= info->len;}static void restore_vlan_tag(union eth_frame *frame, struct frame_info *info){ size_t tag_offset = offsetof(struct ethhdr, h_proto); __u16 tpid = ETH_P_8021Q; size_t moved; __be16 tag[2]; if (frame == NULL || !is_ethernet_frame(info) || !(info->aux.tp_status & TP_STATUS_VLAN_VALID)) { return; } if (info->caplen > sizeof(frame->raw) || info->len > SIZE_MAX - VLAN_HLEN) { return; } if (info->aux.tp_status & TP_STATUS_VLAN_TPID_VALID) { tpid = info->aux.tp_vlan_tpid; } if (tpid != ETH_P_8021Q && tpid != ETH_P_8021AD) { return; } tag[0] = __cpu_to_be16(tpid); tag[1] = __cpu_to_be16(info->aux.tp_vlan_tci); moved = info->caplen - tag_offset; if (moved > sizeof(frame->raw) - tag_offset - VLAN_HLEN) { moved = sizeof(frame->raw) - tag_offset - VLAN_HLEN; } memmove(frame->raw + tag_offset + VLAN_HLEN, frame->raw + tag_offset, moved); memcpy(frame->raw + tag_offset, tag, sizeof(tag)); info->caplen = tag_offset + VLAN_HLEN + moved; info->len += VLAN_HLEN;}static const char *packet_type_name(unsigned char pkttype){ switch (pkttype) { case PACKET_HOST: return "host"; case PACKET_BROADCAST: return "broadcast"; case PACKET_MULTICAST: return "multicast"; case PACKET_OTHERHOST: return "otherhost"; case PACKET_OUTGOING: return "outgoing"; default: return "unknown"; }}static void print_timestamp(const struct timespec *ts){ struct tm tm; if (ts == NULL || ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC) { printf("--:--:--.---------"); return; } if (localtime_r(&ts->tv_sec, &tm) == NULL) { printf("%lld.%09ld", (long long)ts->tv_sec, ts->tv_nsec); return; } printf("%02d:%02d:%02d.%09ld", tm.tm_hour, tm.tm_min, tm.tm_sec, ts->tv_nsec);}static void print_mac(const unsigned char *mac, size_t len){ if (mac == NULL || len != ETH_ALEN) { printf("??:??:??:??:??:??"); return; } printf("%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);}static int read_be16(const __u8 *buf, size_t len, size_t offset, __u16 *value){ __be16 raw; if (buf == NULL || value == NULL || offset > len || len - offset < sizeof(raw)) { return -1; } memcpy(&raw, buf + offset, sizeof(raw)); *value = __be16_to_cpu(raw); return 0;}static void print_vlan_tag(__u16 tpid, __u16 tci){ printf(" tpid=0x%04x pcp=%u vid=%u", tpid, (tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT, tci & VLAN_VID_MASK);}static int print_hexdump(const __u8 *data, size_t len, size_t width){ static const char digits[] = "0123456789abcdef"; char line[HEXDUMP_LINE_SIZE]; size_t offset; size_t pos; size_t i; int n; if (data == NULL || width == 0 || width > HEXDUMP_MAX_WIDTH) { return -1; } for (offset = 0; offset < len; offset += width) { n = snprintf(line, sizeof(line), " 0x%04zx:", offset); if (n < 0 || (size_t)n > HEXDUMP_PREFIX_MAX) { return -1; } pos = (size_t)n; for (i = offset; i < len && i - offset < width; ++i) { line[pos] = ' '; ++pos; line[pos] = digits[data[i] >> 4]; ++pos; line[pos] = digits[data[i] & 0x0f]; ++pos; } line[pos] = '\n'; ++pos; if (fwrite(line, 1, pos, stdout) != pos) { return -1; } } return 0;}static void inspect_payload(size_t payload_len, __u16 proto){ printf(" [payload] proto=0x%04x payload_len=%zu\n", proto, payload_len);}static void inspect_ethernet(const union eth_frame *frame, const struct frame_info *info){ size_t offset = offsetof(struct ethhdr, h_proto); __u16 type; __u16 tci; __u16 next; if (frame == NULL || !is_ethernet_frame(info) || info->caplen > sizeof(frame->raw)) { printf("\n"); return; } printf(" dst="); print_mac(frame->hdr.h_dest, sizeof(frame->hdr.h_dest)); printf(" src="); print_mac(frame->hdr.h_source, sizeof(frame->hdr.h_source)); if (read_be16(frame->raw, info->caplen, offset, &type) < 0) { printf("\n"); return; } offset += sizeof(__be16); while ((type == ETH_P_8021Q || type == ETH_P_8021AD) && read_be16(frame->raw, info->caplen, offset, &tci) == 0 && read_be16(frame->raw, info->caplen, offset + sizeof(__be16), &next) == 0) { print_vlan_tag(type, tci); type = next; offset += VLAN_HLEN; } if (type < ETH_P_802_3_MIN) { printf(" length=%u\n", type); type = __be16_to_cpu(info->sll.sll_protocol); } else { printf(" ethertype=0x%04x\n", type); } inspect_payload(info->len - offset, type);}static int print_frame(const union eth_frame *frame, const struct frame_info *info, const char *ifname, size_t width){ char name[IF_NAMESIZE]; int n; if (frame == NULL || info == NULL || width == 0 || width > HEXDUMP_MAX_WIDTH || info->caplen > sizeof(frame->raw) || info->caplen > info->len) { return -1; } if (ifname != NULL && !valid_ifname(ifname)) { return -1; } if (ifname == NULL) { if (info->sll.sll_ifindex > 0 && if_indextoname((unsigned int)info->sll.sll_ifindex, name) != NULL && valid_ifname(name)) { ifname = name; } else { n = snprintf(name, sizeof(name), "if%d", info->sll.sll_ifindex); if (n < 0 || (size_t)n >= sizeof(name)) { return -1; } ifname = name; } } print_timestamp(&info->ts); printf(" %s %s total_len=%zu", ifname, packet_type_name(info->sll.sll_pkttype), info->len); if (info->caplen < info->len) { printf(" caplen=%zu", info->caplen); } if (is_ethernet_frame(info)) { inspect_ethernet(frame, info); } else { printf(" hatype=%u\n", info->sll.sll_hatype); inspect_payload(info->len, __be16_to_cpu(info->sll.sll_protocol)); } return print_hexdump(frame->raw, info->caplen, width);}static void print_statistics(int fd, unsigned long long captured, unsigned long long received){ __u32 meminfo[SK_MEMINFO_VARS]; socklen_t len = sizeof(meminfo); unsigned long long total; if (fd < 0) { return; } memset(meminfo, 0, sizeof(meminfo)); if (getsockopt(fd, SOL_SOCKET, SO_MEMINFO, meminfo, &len) < 0) { perror("getsockopt(SO_MEMINFO)"); return; } if (len < sizeof(meminfo[0]) * (SK_MEMINFO_DROPS + 1)) { fprintf(stderr, "getsockopt(SO_MEMINFO): drop count unavailable\n"); return; } total = received; if (total > ULLONG_MAX - meminfo[SK_MEMINFO_DROPS]) { total = ULLONG_MAX; } else { total += meminfo[SK_MEMINFO_DROPS]; } fprintf(stderr, "%llu packets captured\n", captured); fprintf(stderr, "%llu packets received by socket\n", total); fprintf(stderr, "%u packets dropped by kernel\n", meminfo[SK_MEMINFO_DROPS]);}static void usage(const char *prog){ fprintf(stderr, "usage: %s [-c bytes_per_line] [ifname]\n", display_name(prog));}int main(int argc, char *argv[]){ static union eth_frame frame; unsigned long long captured = 0; unsigned long long received = 0; size_t width = HEXDUMP_DEFAULT_WIDTH; const char *prog; const char *ifname = NULL; int status = EXIT_SUCCESS; int ret; int opt; int fd; if (argc < 1 || argv == NULL || argv[0] == NULL) { fprintf(stderr, "ethernet: empty argument vector\n"); return EXIT_FAILURE; } prog = display_name(argv[0]); while ((opt = getopt(argc, argv, "c:")) != -1) { if (opt != 'c') { usage(prog); return EXIT_FAILURE; } if (parse_width(optarg, &width) < 0) { fprintf(stderr, "%s: bytes per line must be an integer from 1 to %u\n", prog, HEXDUMP_MAX_WIDTH); return EXIT_FAILURE; } } if (optind < 0 || optind > argc || argc - optind > 1) { usage(prog); return EXIT_FAILURE; } if (optind < argc) { ifname = argv[optind]; if (!valid_ifname(ifname)) { fprintf(stderr, "%s: invalid interface name\n", prog); return EXIT_FAILURE; } } tzset(); if (install_signal_handlers() < 0) { return EXIT_FAILURE; } fd = create_socket(ifname); if (fd < 0) { return EXIT_FAILURE; } if (ifname != NULL) { fprintf(stderr, "Capturing on %s (promiscuous mode enabled)\n", ifname); } else { fprintf(stderr, "Capturing on all interfaces\n"); } while (stop_signal == 0) { struct frame_info info; ret = receive_frame(fd, &frame, &info); if (ret < 0) { if (ifname != NULL && errno == ENETDOWN) { fprintf(stderr, "%s: interface is down\n", ifname); break; } if (errno != EAGAIN) { perror("recvmsg"); status = EXIT_FAILURE; break; } if (wait_for_frame(fd) < 0) { status = EXIT_FAILURE; break; } continue; } if (received < ULLONG_MAX) { ++received; } if (ret == 0) { continue; } if (info.sll.sll_hatype == ARPHRD_LOOPBACK && info.sll.sll_pkttype == PACKET_OUTGOING) { continue; } restore_vlan_tag(&frame, &info); if (print_frame(&frame, &info, ifname, width) < 0 || ferror(stdout)) { fprintf(stderr, "%s: failed to write frame to standard output\n", prog); status = EXIT_FAILURE; break; } if (captured < ULLONG_MAX) { ++captured; } } if (stop_signal == SIGINT && isatty(STDERR_FILENO)) { fputc('\n', stderr); } if (fflush(stdout) == EOF) { perror("fflush"); status = EXIT_FAILURE; } print_statistics(fd, captured, received); if (close(fd) < 0) { perror("close"); status = EXIT_FAILURE; } return status;}