bpf.c revision 252626
1/*	$OpenBSD: bpf.c,v 1.13 2004/05/05 14:28:58 deraadt Exp $	*/
2
3/* BPF socket interface code, originally contributed by Archie Cobbs. */
4
5/*
6 * Copyright (c) 1995, 1996, 1998, 1999
7 * The Internet Software Consortium.    All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The Internet Software Consortium nor the names
19 *    of its contributors may be used to endorse or promote products derived
20 *    from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
23 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
27 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * This software has been written for the Internet Software Consortium
37 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
38 * Enterprises.  To learn more about the Internet Software Consortium,
39 * see ``http://www.vix.com/isc''.  To learn more about Vixie
40 * Enterprises, see ``http://www.vix.com''.
41 */
42
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: head/sbin/dhclient/bpf.c 252626 2013-07-03 22:12:54Z pjd $");
45
46#include "dhcpd.h"
47#include "privsep.h"
48#include <sys/ioctl.h>
49#include <sys/uio.h>
50
51#include <net/bpf.h>
52#include <netinet/in_systm.h>
53#include <netinet/ip.h>
54#include <netinet/udp.h>
55#include <netinet/if_ether.h>
56
57#define BPF_FORMAT "/dev/bpf%d"
58
59/*
60 * Called by get_interface_list for each interface that's discovered.
61 * Opens a packet filter for each interface and adds it to the select
62 * mask.
63 */
64int
65if_register_bpf(struct interface_info *info, int flags)
66{
67	char filename[50];
68	int sock, b;
69
70	/* Open a BPF device */
71	for (b = 0;; b++) {
72		snprintf(filename, sizeof(filename), BPF_FORMAT, b);
73		sock = open(filename, flags);
74		if (sock < 0) {
75			if (errno == EBUSY)
76				continue;
77			else
78				error("Can't find free bpf: %m");
79		} else
80			break;
81	}
82
83	/* Set the BPF device to point at this interface. */
84	if (ioctl(sock, BIOCSETIF, info->ifp) < 0)
85		error("Can't attach interface %s to bpf device %s: %m",
86		    info->name, filename);
87
88	return (sock);
89}
90
91/*
92 * Packet write filter program:
93 * 'ip and udp and src port bootps and dst port (bootps or bootpc)'
94 */
95struct bpf_insn dhcp_bpf_wfilter[] = {
96	BPF_STMT(BPF_LD + BPF_B + BPF_IND, 14),
97	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, (IPVERSION << 4) + 5, 0, 12),
98
99	/* Make sure this is an IP packet... */
100	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
101	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 10),
102
103	/* Make sure it's a UDP packet... */
104	BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
105	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 8),
106
107	/* Make sure this isn't a fragment... */
108	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
109	BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 6, 0),	/* patched */
110
111	/* Get the IP header length... */
112	BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
113
114	/* Make sure it's from the right port... */
115	BPF_STMT(BPF_LD + BPF_H + BPF_IND, 14),
116	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 68, 0, 3),
117
118	/* Make sure it is to the right ports ... */
119	BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
120	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 67, 0, 1),
121
122	/* If we passed all the tests, ask for the whole packet. */
123	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
124
125	/* Otherwise, drop it. */
126	BPF_STMT(BPF_RET+BPF_K, 0),
127};
128
129int dhcp_bpf_wfilter_len = sizeof(dhcp_bpf_wfilter) / sizeof(struct bpf_insn);
130
131void
132if_register_send(struct interface_info *info)
133{
134	struct bpf_version v;
135	struct bpf_program p;
136	int sock, on = 1;
137
138	/* Open a BPF device and hang it on this interface... */
139	info->wfdesc = if_register_bpf(info, O_WRONLY);
140
141	/* Make sure the BPF version is in range... */
142	if (ioctl(info->wfdesc, BIOCVERSION, &v) < 0)
143		error("Can't get BPF version: %m");
144
145	if (v.bv_major != BPF_MAJOR_VERSION ||
146	    v.bv_minor < BPF_MINOR_VERSION)
147		error("Kernel BPF version out of range - recompile dhcpd!");
148
149	/* Set up the bpf write filter program structure. */
150	p.bf_len = dhcp_bpf_wfilter_len;
151	p.bf_insns = dhcp_bpf_wfilter;
152
153	if (dhcp_bpf_wfilter[7].k == 0x1fff)
154		dhcp_bpf_wfilter[7].k = htons(IP_MF|IP_OFFMASK);
155
156	if (ioctl(info->wfdesc, BIOCSETWF, &p) < 0)
157		error("Can't install write filter program: %m");
158
159	if (ioctl(info->wfdesc, BIOCLOCK, NULL) < 0)
160		error("Cannot lock bpf");
161
162	/*
163	 * Use raw socket for unicast send.
164	 */
165	if ((sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)
166		error("socket(SOCK_RAW): %m");
167	if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on,
168	    sizeof(on)) == -1)
169		error("setsockopt(IP_HDRINCL): %m");
170	info->ufdesc = sock;
171}
172
173/*
174 * Packet filter program...
175 *
176 * XXX: Changes to the filter program may require changes to the
177 * constant offsets used in if_register_send to patch the BPF program!
178 */
179struct bpf_insn dhcp_bpf_filter[] = {
180	/* Make sure this is an IP packet... */
181	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
182	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),
183
184	/* Make sure it's a UDP packet... */
185	BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
186	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),
187
188	/* Make sure this isn't a fragment... */
189	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
190	BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),
191
192	/* Get the IP header length... */
193	BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
194
195	/* Make sure it's to the right port... */
196	BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
197	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 67, 0, 1),		/* patch */
198
199	/* If we passed all the tests, ask for the whole packet. */
200	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
201
202	/* Otherwise, drop it. */
203	BPF_STMT(BPF_RET+BPF_K, 0),
204};
205
206int dhcp_bpf_filter_len = sizeof(dhcp_bpf_filter) / sizeof(struct bpf_insn);
207
208void
209if_register_receive(struct interface_info *info)
210{
211	struct bpf_version v;
212	struct bpf_program p;
213	int flag = 1, sz;
214
215	/* Open a BPF device and hang it on this interface... */
216	info->rfdesc = if_register_bpf(info, O_RDONLY);
217
218	/* Make sure the BPF version is in range... */
219	if (ioctl(info->rfdesc, BIOCVERSION, &v) < 0)
220		error("Can't get BPF version: %m");
221
222	if (v.bv_major != BPF_MAJOR_VERSION ||
223	    v.bv_minor < BPF_MINOR_VERSION)
224		error("Kernel BPF version out of range - recompile dhcpd!");
225
226	/*
227	 * Set immediate mode so that reads return as soon as a packet
228	 * comes in, rather than waiting for the input buffer to fill
229	 * with packets.
230	 */
231	if (ioctl(info->rfdesc, BIOCIMMEDIATE, &flag) < 0)
232		error("Can't set immediate mode on bpf device: %m");
233
234	/* Get the required BPF buffer length from the kernel. */
235	if (ioctl(info->rfdesc, BIOCGBLEN, &sz) < 0)
236		error("Can't get bpf buffer length: %m");
237	info->rbuf_max = sz;
238	info->rbuf = malloc(info->rbuf_max);
239	if (!info->rbuf)
240		error("Can't allocate %lu bytes for bpf input buffer.",
241		    (unsigned long)info->rbuf_max);
242	info->rbuf_offset = 0;
243	info->rbuf_len = 0;
244
245	/* Set up the bpf filter program structure. */
246	p.bf_len = dhcp_bpf_filter_len;
247	p.bf_insns = dhcp_bpf_filter;
248
249	/* Patch the server port into the BPF program...
250	 *
251	 * XXX: changes to filter program may require changes to the
252	 * insn number(s) used below!
253	 */
254	dhcp_bpf_filter[8].k = LOCAL_PORT;
255
256	if (ioctl(info->rfdesc, BIOCSETF, &p) < 0)
257		error("Can't install packet filter program: %m");
258
259	if (ioctl(info->rfdesc, BIOCLOCK, NULL) < 0)
260		error("Cannot lock bpf");
261}
262
263void
264send_packet_unpriv(int privfd, struct dhcp_packet *raw, size_t len,
265    struct in_addr from, struct in_addr to)
266{
267	struct imsg_hdr hdr;
268	struct buf *buf;
269	int errs;
270
271	hdr.code = IMSG_SEND_PACKET;
272	hdr.len = sizeof(hdr) +
273	    sizeof(size_t) + len +
274	    sizeof(from) + sizeof(to);
275
276	if ((buf = buf_open(hdr.len)) == NULL)
277		error("buf_open: %m");
278
279	errs = 0;
280	errs += buf_add(buf, &hdr, sizeof(hdr));
281	errs += buf_add(buf, &len, sizeof(len));
282	errs += buf_add(buf, raw, len);
283	errs += buf_add(buf, &from, sizeof(from));
284	errs += buf_add(buf, &to, sizeof(to));
285	if (errs)
286		error("buf_add: %m");
287
288	if (buf_close(privfd, buf) == -1)
289		error("buf_close: %m");
290}
291
292void
293send_packet_priv(struct interface_info *interface, struct imsg_hdr *hdr, int fd)
294{
295	unsigned char buf[256];
296	struct iovec iov[2];
297	struct msghdr msg;
298	struct dhcp_packet raw;
299	size_t len;
300	struct in_addr from, to;
301	int result, bufp = 0;
302
303	if (hdr->len < sizeof(*hdr) + sizeof(size_t))
304		error("corrupted message received");
305	buf_read(fd, &len, sizeof(len));
306	if (hdr->len != sizeof(*hdr) + sizeof(size_t) + len +
307	    sizeof(from) + sizeof(to)) {
308		error("corrupted message received");
309	}
310	if (len > sizeof(raw))
311		error("corrupted message received");
312	buf_read(fd, &raw, len);
313	buf_read(fd, &from, sizeof(from));
314	buf_read(fd, &to, sizeof(to));
315
316	/* Assemble the headers... */
317	if (to.s_addr == INADDR_BROADCAST)
318		assemble_hw_header(interface, buf, &bufp);
319	assemble_udp_ip_header(buf, &bufp, from.s_addr, to.s_addr,
320	    htons(REMOTE_PORT), (unsigned char *)&raw, len);
321
322	iov[0].iov_base = buf;
323	iov[0].iov_len = bufp;
324	iov[1].iov_base = &raw;
325	iov[1].iov_len = len;
326
327	/* Fire it off */
328	if (to.s_addr == INADDR_BROADCAST)
329		result = writev(interface->wfdesc, iov, 2);
330	else {
331		struct sockaddr_in sato;
332
333		sato.sin_addr = to;
334		sato.sin_port = htons(REMOTE_PORT);
335		sato.sin_family = AF_INET;
336		sato.sin_len = sizeof(sato);
337
338		memset(&msg, 0, sizeof(msg));
339		msg.msg_name = (struct sockaddr *)&sato;
340		msg.msg_namelen = sizeof(sato);
341		msg.msg_iov = iov;
342		msg.msg_iovlen = 2;
343		result = sendmsg(interface->ufdesc, &msg, 0);
344	}
345
346	if (result < 0)
347		warning("send_packet: %m");
348}
349
350ssize_t
351receive_packet(struct interface_info *interface, unsigned char *buf,
352    size_t len, struct sockaddr_in *from, struct hardware *hfrom)
353{
354	int length = 0, offset = 0;
355	struct bpf_hdr hdr;
356
357	/*
358	 * All this complexity is because BPF doesn't guarantee that
359	 * only one packet will be returned at a time.  We're getting
360	 * what we deserve, though - this is a terrible abuse of the BPF
361	 * interface.  Sigh.
362	 */
363
364	/* Process packets until we get one we can return or until we've
365	 * done a read and gotten nothing we can return...
366	 */
367	do {
368		/* If the buffer is empty, fill it. */
369		if (interface->rbuf_offset >= interface->rbuf_len) {
370			length = read(interface->rfdesc, interface->rbuf,
371			    interface->rbuf_max);
372			if (length <= 0)
373				return (length);
374			interface->rbuf_offset = 0;
375			interface->rbuf_len = length;
376		}
377
378		/*
379		 * If there isn't room for a whole bpf header, something
380		 * went wrong, but we'll ignore it and hope it goes
381		 * away... XXX
382		 */
383		if (interface->rbuf_len - interface->rbuf_offset <
384		    sizeof(hdr)) {
385			interface->rbuf_offset = interface->rbuf_len;
386			continue;
387		}
388
389		/* Copy out a bpf header... */
390		memcpy(&hdr, &interface->rbuf[interface->rbuf_offset],
391		    sizeof(hdr));
392
393		/*
394		 * If the bpf header plus data doesn't fit in what's
395		 * left of the buffer, stick head in sand yet again...
396		 */
397		if (interface->rbuf_offset + hdr.bh_hdrlen + hdr.bh_caplen >
398		    interface->rbuf_len) {
399			interface->rbuf_offset = interface->rbuf_len;
400			continue;
401		}
402
403		/* Skip over the BPF header... */
404		interface->rbuf_offset += hdr.bh_hdrlen;
405
406		/*
407		 * If the captured data wasn't the whole packet, or if
408		 * the packet won't fit in the input buffer, all we can
409		 * do is drop it.
410		 */
411		if (hdr.bh_caplen != hdr.bh_datalen) {
412			interface->rbuf_offset =
413			    BPF_WORDALIGN(interface->rbuf_offset +
414			    hdr.bh_caplen);
415			continue;
416		}
417
418		/* Decode the physical header... */
419		offset = decode_hw_header(interface->rbuf,
420		    interface->rbuf_offset, hfrom);
421
422		/*
423		 * If a physical layer checksum failed (dunno of any
424		 * physical layer that supports this, but WTH), skip
425		 * this packet.
426		 */
427		if (offset < 0) {
428			interface->rbuf_offset =
429			    BPF_WORDALIGN(interface->rbuf_offset +
430			    hdr.bh_caplen);
431			continue;
432		}
433		interface->rbuf_offset += offset;
434		hdr.bh_caplen -= offset;
435
436		/* Decode the IP and UDP headers... */
437		offset = decode_udp_ip_header(interface->rbuf,
438		    interface->rbuf_offset, from, NULL, hdr.bh_caplen);
439
440		/* If the IP or UDP checksum was bad, skip the packet... */
441		if (offset < 0) {
442			interface->rbuf_offset =
443			    BPF_WORDALIGN(interface->rbuf_offset +
444			    hdr.bh_caplen);
445			continue;
446		}
447		interface->rbuf_offset += offset;
448		hdr.bh_caplen -= offset;
449
450		/*
451		 * If there's not enough room to stash the packet data,
452		 * we have to skip it (this shouldn't happen in real
453		 * life, though).
454		 */
455		if (hdr.bh_caplen > len) {
456			interface->rbuf_offset =
457			    BPF_WORDALIGN(interface->rbuf_offset +
458			    hdr.bh_caplen);
459			continue;
460		}
461
462		/* Copy out the data in the packet... */
463		memcpy(buf, interface->rbuf + interface->rbuf_offset,
464		    hdr.bh_caplen);
465		interface->rbuf_offset =
466		    BPF_WORDALIGN(interface->rbuf_offset +
467		    hdr.bh_caplen);
468		return (hdr.bh_caplen);
469	} while (!length);
470	return (0);
471}
472