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