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