pcap-netfilter-linux.c revision 235426
1218887Sdim/*
2218887Sdim * Copyright (c) 2011 Jakub Zawadzki
3353358Sdim * All rights reserved.
4353358Sdim *
5353358Sdim * Redistribution and use in source and binary forms, with or without
6218887Sdim * modification, are permitted provided that the following conditions
7218887Sdim * are met:
8218887Sdim *
9218887Sdim * 1. Redistributions of source code must retain the above copyright
10344779Sdim * notice, this list of conditions and the following disclaimer.
11249423Sdim * 2. Redistributions in binary form must reproduce the above copyright
12249423Sdim * notice, this list of conditions and the following disclaimer in the
13249423Sdim * documentation and/or other materials provided with the distribution.
14221345Sdim * 3. The name of the author may not be used to endorse or promote
15221345Sdim * products derived from this software without specific prior written
16218887Sdim * permission.
17221345Sdim *
18218887Sdim * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19234353Sdim * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20234353Sdim * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21249423Sdim * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22218887Sdim * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23218887Sdim * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24218887Sdim * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25218887Sdim * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26276479Sdim * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27276479Sdim * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28234353Sdim * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29234353Sdim */
30234353Sdim
31234353Sdim#ifdef HAVE_CONFIG_H
32234353Sdim#include "config.h"
33218887Sdim#endif
34221345Sdim
35218887Sdim#include "pcap-int.h"
36221345Sdim
37218887Sdim#ifdef NEED_STRERROR_H
38218887Sdim#include "strerror.h"
39218887Sdim#endif
40221345Sdim
41218887Sdim#include <errno.h>
42221345Sdim#include <stdlib.h>
43276479Sdim#include <unistd.h>
44218887Sdim#include <string.h>
45309124Sdim#include <sys/socket.h>
46218887Sdim#include <arpa/inet.h>
47234353Sdim
48234353Sdim#include <time.h>
49234353Sdim#include <sys/time.h>
50234353Sdim#include <netinet/in.h>
51234353Sdim#include <linux/types.h>
52234353Sdim
53234353Sdim#include <linux/netlink.h>
54218887Sdim#include <linux/netfilter/nfnetlink.h>
55218887Sdim#include <linux/netfilter/nfnetlink_log.h>
56218887Sdim
57218887Sdim#include "pcap-netfilter-linux.h"
58234353Sdim
59234353Sdim#define HDR_LENGTH (NLMSG_LENGTH(NLMSG_ALIGN(sizeof(struct nfgenmsg))))
60234353Sdim
61234353Sdim#define NFLOG_IFACE "nflog"
62249423Sdim
63218887Sdimstatic int
64218887Sdimnflog_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
65218887Sdim{
66218887Sdim	const unsigned char *buf;
67218887Sdim	int count = 0;
68234353Sdim	int len;
69218887Sdim
70218887Sdim	/* ignore interrupt system call error */
71218887Sdim	do {
72218887Sdim		len = recv(handle->fd, handle->buffer, handle->bufsize, 0);
73218887Sdim		if (handle->break_loop) {
74218887Sdim			handle->break_loop = 0;
75218887Sdim			return -2;
76218887Sdim		}
77218887Sdim	} while ((len == -1) && (errno == EINTR));
78218887Sdim
79218887Sdim	if (len < 0) {
80218887Sdim		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't receive packet %d:%s", errno, pcap_strerror(errno));
81218887Sdim		return -1;
82218887Sdim	}
83218887Sdim
84218887Sdim	buf = handle->buffer;
85234353Sdim	while (len >= NLMSG_SPACE(0)) {
86234353Sdim		const struct nlmsghdr *nlh = (const struct nlmsghdr *) buf;
87234353Sdim		u_int32_t msg_len;
88218887Sdim
89218887Sdim		if (nlh->nlmsg_len < sizeof(struct nlmsghdr) || len < nlh->nlmsg_len) {
90234353Sdim			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Message truncated: (got: %d) (nlmsg_len: %u)", len, nlh->nlmsg_len);
91218887Sdim			return -1;
92218887Sdim		}
93234353Sdim
94234353Sdim		if (NFNL_SUBSYS_ID(nlh->nlmsg_type) == NFNL_SUBSYS_ULOG &&
95218887Sdim			NFNL_MSG_TYPE(nlh->nlmsg_type) == NFULNL_MSG_PACKET)
96234353Sdim		{
97234353Sdim			const unsigned char *payload = NULL;
98234353Sdim			struct pcap_pkthdr pkth;
99218887Sdim
100234353Sdim			if (handle->linktype != DLT_NFLOG) {
101234353Sdim				const struct nfattr *payload_attr = NULL;
102234353Sdim
103296417Sdim				if (nlh->nlmsg_len < HDR_LENGTH) {
104234353Sdim					snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Malformed message: (nlmsg_len: %u)", nlh->nlmsg_len);
105234353Sdim					return -1;
106234353Sdim				}
107234353Sdim
108218887Sdim				if (nlh->nlmsg_len > HDR_LENGTH) {
109221345Sdim					struct nfattr *attr = NFM_NFA(NLMSG_DATA(nlh));
110221345Sdim					int attr_len = nlh->nlmsg_len - NLMSG_ALIGN(HDR_LENGTH);
111218887Sdim
112218887Sdim					while (NFA_OK(attr, attr_len)) {
113218887Sdim						switch (NFA_TYPE(attr)) {
114276479Sdim							case NFULA_PAYLOAD:
115234353Sdim								payload_attr = attr;
116218887Sdim								break;
117234353Sdim						}
118221345Sdim						attr = NFA_NEXT(attr, attr_len);
119218887Sdim					}
120221345Sdim				}
121221345Sdim
122218887Sdim				if (payload_attr) {
123218887Sdim					payload = NFA_DATA(payload_attr);
124341825Sdim					pkth.len = pkth.caplen = NFA_PAYLOAD(payload_attr);
125341825Sdim				}
126218887Sdim
127249423Sdim			} else {
128234353Sdim				payload = NLMSG_DATA(nlh);
129234353Sdim				pkth.caplen = pkth.len = nlh->nlmsg_len-NLMSG_ALIGN(sizeof(struct nlmsghdr));
130234353Sdim			}
131234353Sdim
132249423Sdim			if (payload) {
133276479Sdim				/* pkth.caplen = min (payload_len, handle->snapshot); */
134249423Sdim
135234353Sdim				gettimeofday(&pkth.ts, NULL);
136218887Sdim				if (handle->fcode.bf_insns == NULL ||
137218887Sdim						bpf_filter(handle->fcode.bf_insns, payload, pkth.len, pkth.caplen))
138221345Sdim				{
139221345Sdim					handle->md.packets_read++;
140221345Sdim					callback(user, &pkth, payload);
141221345Sdim					count++;
142353358Sdim				}
143353358Sdim			}
144353358Sdim		}
145353358Sdim
146		msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
147		if (msg_len > len)
148			msg_len = len;
149
150		len -= msg_len;
151		buf += msg_len;
152	}
153	return count;
154}
155
156static int
157netfilter_set_datalink(pcap_t *handle, int dlt)
158{
159	handle->linktype = dlt;
160	return 0;
161}
162
163static int
164netfilter_stats_linux(pcap_t *handle, struct pcap_stat *stats)
165{
166	stats->ps_recv = handle->md.packets_read;
167	stats->ps_drop = 0;
168	stats->ps_ifdrop = 0;
169	return 0;
170}
171
172static int
173netfilter_inject_linux(pcap_t *handle, const void *buf, size_t size)
174{
175	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on netfilter devices");
176	return (-1);
177}
178
179struct my_nfattr {
180	u_int16_t nfa_len;
181	u_int16_t nfa_type;
182	void *data;
183};
184
185static int
186nflog_send_config_msg(const pcap_t *handle, u_int8_t family, u_int16_t res_id, const struct my_nfattr *mynfa)
187{
188	char buf[1024] __attribute__ ((aligned));
189
190	struct nlmsghdr *nlh = (struct nlmsghdr *) buf;
191	struct nfgenmsg *nfg = (struct nfgenmsg *) (buf + sizeof(struct nlmsghdr));
192
193	struct sockaddr_nl snl;
194	static unsigned int seq_id;
195
196	if (!seq_id)
197		seq_id = time(NULL);
198	++seq_id;
199
200	nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nfgenmsg));
201	nlh->nlmsg_type = (NFNL_SUBSYS_ULOG << 8) | NFULNL_MSG_CONFIG;
202	nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
203	nlh->nlmsg_pid = 0;	/* to kernel */
204	nlh->nlmsg_seq = seq_id;
205
206	nfg->nfgen_family = family;
207	nfg->version = NFNETLINK_V0;
208	nfg->res_id = htons(res_id);
209
210	if (mynfa) {
211		struct nfattr *nfa = (struct nfattr *) (buf + NLMSG_ALIGN(nlh->nlmsg_len));
212
213		nfa->nfa_type = mynfa->nfa_type;
214		nfa->nfa_len = NFA_LENGTH(mynfa->nfa_len);
215		memcpy(NFA_DATA(nfa), mynfa->data, mynfa->nfa_len);
216		nlh->nlmsg_len = NLMSG_ALIGN(nlh->nlmsg_len) + NFA_ALIGN(nfa->nfa_len);
217	}
218
219	memset(&snl, 0, sizeof(snl));
220	snl.nl_family = AF_NETLINK;
221
222	if (sendto(handle->fd, nlh, nlh->nlmsg_len, 0, (struct sockaddr *) &snl, sizeof(snl)) == -1)
223		return -1;
224
225	/* waiting for reply loop */
226	do {
227		socklen_t addrlen = sizeof(snl);
228		int len;
229
230		/* ignore interrupt system call error */
231		do {
232			len = recvfrom(handle->fd, buf, sizeof(buf), 0, (struct sockaddr *) &snl, &addrlen);
233		} while ((len == -1) && (errno == EINTR));
234
235		if (len <= 0)
236			return len;
237
238		if (addrlen != sizeof(snl) || snl.nl_family != AF_NETLINK) {
239			errno = EINVAL;
240			return -1;
241		}
242
243		nlh = (struct nlmsghdr *) buf;
244		if (snl.nl_pid != 0 || seq_id != nlh->nlmsg_seq)	/* if not from kernel or wrong sequence skip */
245			continue;
246
247		while (len >= NLMSG_SPACE(0) && NLMSG_OK(nlh, len)) {
248			if (nlh->nlmsg_type == NLMSG_ERROR || (nlh->nlmsg_type == NLMSG_DONE && nlh->nlmsg_flags & NLM_F_MULTI)) {
249				if (nlh->nlmsg_len < NLMSG_ALIGN(sizeof(struct nlmsgerr))) {
250					errno = EBADMSG;
251					return -1;
252				}
253				errno = -(*((int *)NLMSG_DATA(nlh)));
254				return (errno == 0) ? 0 : -1;
255			}
256			nlh = NLMSG_NEXT(nlh, len);
257		}
258	} while (1);
259
260	return -1; /* never here */
261}
262
263static int
264nflog_send_config_cmd(const pcap_t *handle, u_int16_t group_id, u_int8_t cmd, u_int8_t family)
265{
266	struct nfulnl_msg_config_cmd msg;
267	struct my_nfattr nfa;
268
269	msg.command = cmd;
270
271	nfa.data = &msg;
272	nfa.nfa_type = NFULA_CFG_CMD;
273	nfa.nfa_len = sizeof(msg);
274
275	return nflog_send_config_msg(handle, family, group_id, &nfa);
276}
277
278static int
279nflog_send_config_mode(const pcap_t *handle, u_int16_t group_id, u_int8_t copy_mode, u_int32_t copy_range)
280{
281	struct nfulnl_msg_config_mode msg;
282	struct my_nfattr nfa;
283
284	msg.copy_range = htonl(copy_range);
285	msg.copy_mode = copy_mode;
286
287	nfa.data = &msg;
288	nfa.nfa_type = NFULA_CFG_MODE;
289	nfa.nfa_len = sizeof(msg);
290
291	return nflog_send_config_msg(handle, AF_UNSPEC, group_id, &nfa);
292}
293
294static int
295nflog_activate(pcap_t* handle)
296{
297	const char *dev = handle->opt.source;
298	unsigned short groups[32];
299	int group_count = 0;
300	int i;
301
302	if (strncmp(dev, NFLOG_IFACE, strlen(NFLOG_IFACE)) == 0) {
303		dev += strlen(NFLOG_IFACE);
304
305		/* nflog:30,33,42 looks nice, allow it */
306		if (*dev == ':')
307			dev++;
308
309		while (*dev) {
310			long int group_id;
311			char *end_dev;
312
313			if (group_count == 32) {
314				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
315						"Maximum 32 netfilter groups! dev: %s",
316						handle->opt.source);
317				return PCAP_ERROR;
318			}
319
320			group_id = strtol(dev, &end_dev, 0);
321			if (end_dev != dev) {
322				if (group_id < 0 || group_id > 65535) {
323					snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
324							"Netfilter group range from 0 to 65535 (got %ld)",
325							group_id);
326					return PCAP_ERROR;
327				}
328
329				groups[group_count++] = (unsigned short) group_id;
330				dev = end_dev;
331			}
332			if (*dev != ',')
333				break;
334			dev++;
335		}
336	}
337
338	if (*dev) {
339		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
340				"Can't get netfilter group(s) index from %s",
341				handle->opt.source);
342		return PCAP_ERROR;
343	}
344
345	/* if no groups, add default: 0 */
346	if (!group_count) {
347		groups[0] = 0;
348		group_count = 1;
349	}
350
351	/* Initialize some components of the pcap structure. */
352	handle->bufsize = 128 + handle->snapshot;
353	handle->offset = 0;
354	handle->linktype = DLT_NFLOG;
355	handle->read_op = nflog_read_linux;
356	handle->inject_op = netfilter_inject_linux;
357	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
358	handle->setdirection_op = NULL;
359	handle->set_datalink_op = NULL;
360	handle->set_datalink_op = netfilter_set_datalink;
361	handle->getnonblock_op = pcap_getnonblock_fd;
362	handle->setnonblock_op = pcap_setnonblock_fd;
363	handle->stats_op = netfilter_stats_linux;
364
365	/* Create netlink socket */
366	handle->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER);
367	if (handle->fd < 0) {
368		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't create raw socket %d:%s", errno, pcap_strerror(errno));
369		return PCAP_ERROR;
370	}
371
372	handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
373	if (handle->dlt_list != NULL) {
374		handle->dlt_list[0] = DLT_NFLOG;
375		handle->dlt_list[1] = DLT_IPV4;
376		handle->dlt_count = 2;
377	}
378
379	handle->buffer = malloc(handle->bufsize);
380	if (!handle->buffer) {
381		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't allocate dump buffer: %s", pcap_strerror(errno));
382		goto close_fail;
383	}
384
385	if (nflog_send_config_cmd(handle, 0, NFULNL_CFG_CMD_PF_UNBIND, AF_INET) < 0) {
386		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "NFULNL_CFG_CMD_PF_UNBIND: %s", pcap_strerror(errno));
387		goto close_fail;
388	}
389
390	if (nflog_send_config_cmd(handle, 0, NFULNL_CFG_CMD_PF_BIND, AF_INET) < 0) {
391		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "NFULNL_CFG_CMD_PF_BIND: %s", pcap_strerror(errno));
392		goto close_fail;
393	}
394
395	/* Bind socket to the nflog groups */
396	for (i = 0; i < group_count; i++) {
397		if (nflog_send_config_cmd(handle, groups[i], NFULNL_CFG_CMD_BIND, AF_UNSPEC) < 0) {
398			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't listen on group group index: %s", pcap_strerror(errno));
399			goto close_fail;
400		}
401
402		if (nflog_send_config_mode(handle, groups[i], NFULNL_COPY_PACKET, handle->snapshot) < 0) {
403			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "NFULNL_COPY_PACKET: %s", pcap_strerror(errno));
404			goto close_fail;
405		}
406	}
407
408	if (handle->opt.rfmon) {
409		/*
410		 * Monitor mode doesn't apply to netfilter devices.
411		 */
412		pcap_cleanup_live_common(handle);
413		return PCAP_ERROR_RFMON_NOTSUP;
414	}
415
416	if (handle->opt.buffer_size != 0) {
417		/*
418		 * Set the socket buffer size to the specified value.
419		 */
420		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF, &handle->opt.buffer_size, sizeof(handle->opt.buffer_size)) == -1) {
421			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "SO_RCVBUF: %s", pcap_strerror(errno));
422			goto close_fail;
423		}
424	}
425
426	handle->selectable_fd = handle->fd;
427	return 0;
428
429close_fail:
430	pcap_cleanup_live_common(handle);
431	return PCAP_ERROR;
432}
433
434pcap_t *
435nflog_create(const char *device, char *ebuf)
436{
437	pcap_t *p;
438
439	p = pcap_create_common(device, ebuf);
440	if (p == NULL)
441		return (NULL);
442
443	p->activate_op = nflog_activate;
444	return (p);
445}
446
447int
448netfilter_platform_finddevs(pcap_if_t **alldevsp, char *err_str)
449{
450	pcap_if_t *found_dev = *alldevsp;
451	int sock;
452
453	sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER);
454	if (sock < 0) {
455		/* if netlink is not supported this this is not fatal */
456		if (errno == EAFNOSUPPORT)
457			return 0;
458		snprintf(err_str, PCAP_ERRBUF_SIZE, "Can't open netlink socket %d:%s",
459			errno, pcap_strerror(errno));
460		return -1;
461	}
462	close(sock);
463
464	if (pcap_add_if(&found_dev, NFLOG_IFACE, 0, "Linux netfilter log (NFLOG) interface", err_str) < 0)
465		return -1;
466	return 0;
467}
468
469