]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - contrib/libpcap/pcap-netfilter-linux.c
MFC: r239663, r239664
[FreeBSD/releng/9.1.git] / contrib / libpcap / pcap-netfilter-linux.c
1 /*
2  * Copyright (c) 2011 Jakub Zawadzki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote 
15  * products derived from this software without specific prior written 
16  * permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include "pcap-int.h"
36
37 #ifdef NEED_STRERROR_H
38 #include "strerror.h"
39 #endif
40
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <unistd.h>
44 #include <string.h>
45 #include <sys/socket.h>
46 #include <arpa/inet.h>
47
48 #include <time.h>
49 #include <sys/time.h>
50 #include <netinet/in.h>
51 #include <linux/types.h>
52
53 #include <linux/netlink.h>
54 #include <linux/netfilter/nfnetlink.h>
55 #include <linux/netfilter/nfnetlink_log.h>
56
57 #include "pcap-netfilter-linux.h"
58
59 #define HDR_LENGTH (NLMSG_LENGTH(NLMSG_ALIGN(sizeof(struct nfgenmsg))))
60
61 #define NFLOG_IFACE "nflog"
62
63 static int
64 nflog_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
65 {
66         const unsigned char *buf;
67         int count = 0;
68         int len;
69
70         /* ignore interrupt system call error */
71         do {
72                 len = recv(handle->fd, handle->buffer, handle->bufsize, 0);
73                 if (handle->break_loop) {
74                         handle->break_loop = 0;
75                         return -2;
76                 }
77         } while ((len == -1) && (errno == EINTR));
78
79         if (len < 0) {
80                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't receive packet %d:%s", errno, pcap_strerror(errno));
81                 return -1;
82         }
83
84         buf = handle->buffer;
85         while (len >= NLMSG_SPACE(0)) {
86                 const struct nlmsghdr *nlh = (const struct nlmsghdr *) buf;
87                 u_int32_t msg_len;
88
89                 if (nlh->nlmsg_len < sizeof(struct nlmsghdr) || len < nlh->nlmsg_len) {
90                         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Message truncated: (got: %d) (nlmsg_len: %u)", len, nlh->nlmsg_len);
91                         return -1;
92                 }
93
94                 if (NFNL_SUBSYS_ID(nlh->nlmsg_type) == NFNL_SUBSYS_ULOG && 
95                         NFNL_MSG_TYPE(nlh->nlmsg_type) == NFULNL_MSG_PACKET) 
96                 {
97                         const unsigned char *payload = NULL;
98                         struct pcap_pkthdr pkth;
99
100                         if (handle->linktype != DLT_NFLOG) {
101                                 const struct nfattr *payload_attr = NULL;
102
103                                 if (nlh->nlmsg_len < HDR_LENGTH) {
104                                         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Malformed message: (nlmsg_len: %u)", nlh->nlmsg_len);
105                                         return -1;
106                                 }
107
108                                 if (nlh->nlmsg_len > HDR_LENGTH) {
109                                         struct nfattr *attr = NFM_NFA(NLMSG_DATA(nlh));
110                                         int attr_len = nlh->nlmsg_len - NLMSG_ALIGN(HDR_LENGTH);
111
112                                         while (NFA_OK(attr, attr_len)) {
113                                                 switch (NFA_TYPE(attr)) {
114                                                         case NFULA_PAYLOAD:
115                                                                 payload_attr = attr;
116                                                                 break;
117                                                 }
118                                                 attr = NFA_NEXT(attr, attr_len);
119                                         }
120                                 }
121
122                                 if (payload_attr) {
123                                         payload = NFA_DATA(payload_attr);
124                                         pkth.len = pkth.caplen = NFA_PAYLOAD(payload_attr);
125                                 }
126
127                         } else {
128                                 payload = NLMSG_DATA(nlh);
129                                 pkth.caplen = pkth.len = nlh->nlmsg_len-NLMSG_ALIGN(sizeof(struct nlmsghdr));
130                         }
131
132                         if (payload) {
133                                 /* pkth.caplen = min (payload_len, handle->snapshot); */
134
135                                 gettimeofday(&pkth.ts, NULL);
136                                 if (handle->fcode.bf_insns == NULL ||
137                                                 bpf_filter(handle->fcode.bf_insns, payload, pkth.len, pkth.caplen)) 
138                                 {
139                                         handle->md.packets_read++;
140                                         callback(user, &pkth, payload);
141                                         count++;
142                                 }
143                         }
144                 }
145
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
156 static int
157 netfilter_set_datalink(pcap_t *handle, int dlt)
158 {
159         handle->linktype = dlt;
160         return 0;
161 }
162
163 static int
164 netfilter_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
172 static int
173 netfilter_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
179 struct my_nfattr {
180         u_int16_t nfa_len;
181         u_int16_t nfa_type;
182         void *data;
183 };
184
185 static int
186 nflog_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
263 static int
264 nflog_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
278 static int 
279 nflog_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
294 static int
295 nflog_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
429 close_fail:
430         pcap_cleanup_live_common(handle);
431         return PCAP_ERROR;
432 }
433
434 pcap_t *
435 nflog_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
447 int 
448 netfilter_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