xref: /openbsd-src/usr.sbin/dhcrelay/bpf.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: bpf.c,v 1.6 2008/09/15 20:39:21 claudio 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 "dhcpd.h"
44 #include <sys/ioctl.h>
45 #include <sys/uio.h>
46 
47 #include <net/bpf.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <netinet/udp.h>
51 #include <netinet/if_ether.h>
52 
53 #define BPF_FORMAT "/dev/bpf%d"
54 
55 /*
56  * Called by get_interface_list for each interface that's discovered.
57  * Opens a packet filter for each interface and adds it to the select
58  * mask.
59  */
60 int
61 if_register_bpf(struct interface_info *info)
62 {
63 	char filename[50];
64 	int sock, b;
65 
66 	/* Open a BPF device */
67 	for (b = 0; 1; b++) {
68 		snprintf(filename, sizeof(filename), BPF_FORMAT, b);
69 		sock = open(filename, O_RDWR, 0);
70 		if (sock == -1) {
71 			if (errno == EBUSY)
72 				continue;
73 			else
74 				error("Can't find free bpf: %m");
75 		} else
76 			break;
77 	}
78 
79 	/* Set the BPF device to point at this interface. */
80 	if (ioctl(sock, BIOCSETIF, info->ifp) == -1)
81 		error("Can't attach interface %s to bpf device %s: %m",
82 		    info->name, filename);
83 
84 	return (sock);
85 }
86 
87 void
88 if_register_send(struct interface_info *info)
89 {
90 	/*
91 	 * If we're using the bpf API for sending and receiving, we
92 	 * don't need to register this interface twice.
93 	 */
94 	info->wfdesc = info->rfdesc;
95 }
96 
97 /*
98  * Packet filter program: 'ip and udp and dst port SERVER_PORT'
99  */
100 struct bpf_insn dhcp_bpf_filter[] = {
101 	/* Make sure this is an IP packet... */
102 	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
103 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),
104 
105 	/* Make sure it's a UDP packet... */
106 	BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
107 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),
108 
109 	/* Make sure this isn't a fragment... */
110 	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
111 	BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),
112 
113 	/* Get the IP header length... */
114 	BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
115 
116 	/* Make sure it's to the right port... */
117 	BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
118 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, SERVER_PORT, 0, 1),
119 
120 	/* If we passed all the tests, ask for the whole packet. */
121 	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
122 
123 	/* Otherwise, drop it. */
124 	BPF_STMT(BPF_RET+BPF_K, 0),
125 };
126 
127 int dhcp_bpf_filter_len = sizeof(dhcp_bpf_filter) / sizeof(struct bpf_insn);
128 
129 
130 /*
131  * Packet write filter program: 'ip and udp and src port SERVER_PORT'
132  */
133 struct bpf_insn dhcp_bpf_wfilter[] = {
134 	/* Make sure this is an IP packet... */
135 	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
136 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),
137 
138 	/* Make sure it's a UDP packet... */
139 	BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
140 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),
141 
142 	/* Make sure this isn't a fragment... */
143 	BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
144 	BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),
145 
146 	/* Get the IP header length... */
147 	BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
148 
149 	/* Make sure it's from the right port... */
150 	BPF_STMT(BPF_LD + BPF_H + BPF_IND, 14),
151 	BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, SERVER_PORT, 0, 1),
152 
153 	/* If we passed all the tests, ask for the whole packet. */
154 	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
155 
156 	/* Otherwise, drop it. */
157 	BPF_STMT(BPF_RET+BPF_K, 0),
158 };
159 
160 int dhcp_bpf_wfilter_len = sizeof(dhcp_bpf_wfilter) / sizeof(struct bpf_insn);
161 
162 void
163 if_register_receive(struct interface_info *info)
164 {
165 	struct bpf_version v;
166 	struct bpf_program p;
167 	int flag = 1, sz, cmplt = 0;
168 
169 	/* Open a BPF device and hang it on this interface... */
170 	info->rfdesc = if_register_bpf(info);
171 
172 	/* Make sure the BPF version is in range... */
173 	if (ioctl(info->rfdesc, BIOCVERSION, &v) == -1)
174 		error("Can't get BPF version: %m");
175 
176 	if (v.bv_major != BPF_MAJOR_VERSION ||
177 	    v.bv_minor < BPF_MINOR_VERSION)
178 		error("Kernel BPF version out of range - recompile dhcpd!");
179 
180 	/*
181 	 * Set immediate mode so that reads return as soon as a packet
182 	 * comes in, rather than waiting for the input buffer to fill
183 	 * with packets.
184 	 */
185 	if (ioctl(info->rfdesc, BIOCIMMEDIATE, &flag) == -1)
186 		error("Can't set immediate mode on bpf device: %m");
187 
188 	/* make sure kernel fills in the source ethernet address */
189 	if (ioctl(info->rfdesc, BIOCSHDRCMPLT, &cmplt) == -1)
190 		error("Can't set header complete flag on bpf device: %m");
191 
192 	/* Get the required BPF buffer length from the kernel. */
193 	if (ioctl(info->rfdesc, BIOCGBLEN, &sz) == -1)
194 		error("Can't get bpf buffer length: %m");
195 	info->rbuf_max = sz;
196 	info->rbuf = malloc(info->rbuf_max);
197 	if (!info->rbuf)
198 		error("Can't allocate %lu bytes for bpf input buffer.",
199 		    (unsigned long)info->rbuf_max);
200 	info->rbuf_offset = 0;
201 	info->rbuf_len = 0;
202 
203 	/* Set up the bpf filter program structure. */
204 	p.bf_len = dhcp_bpf_filter_len;
205 	p.bf_insns = dhcp_bpf_filter;
206 
207 	if (ioctl(info->rfdesc, BIOCSETF, &p) == -1)
208 		error("Can't install packet filter program: %m");
209 
210 	/* Set up the bpf write filter program structure. */
211 	p.bf_len = dhcp_bpf_wfilter_len;
212 	p.bf_insns = dhcp_bpf_wfilter;
213 
214 	if (ioctl(info->rfdesc, BIOCSETWF, &p) == -1)
215 		error("Can't install write filter program: %m");
216 
217 	/* make sure these settings cannot be changed after dropping privs */
218 	if (ioctl(info->rfdesc, BIOCLOCK) == -1)
219 		error("Failed to lock bpf descriptor: %m");
220 }
221 
222 ssize_t
223 send_packet(struct interface_info *interface,
224     struct dhcp_packet *raw, size_t len, struct in_addr from,
225     struct sockaddr_in *to, struct hardware *hto)
226 {
227 	unsigned char buf[256];
228 	struct iovec iov[2];
229 	int result, bufp = 0;
230 
231 	/* Assemble the headers... */
232 	assemble_hw_header(interface, buf, &bufp, hto);
233 	assemble_udp_ip_header(interface, buf, &bufp, from.s_addr,
234 	    to->sin_addr.s_addr, to->sin_port, (unsigned char *)raw, len);
235 
236 	/* Fire it off */
237 	iov[0].iov_base = (char *)buf;
238 	iov[0].iov_len = bufp;
239 	iov[1].iov_base = (char *)raw;
240 	iov[1].iov_len = len;
241 
242 	result = writev(interface->wfdesc, iov, 2);
243 	if (result == -1)
244 		warning("send_packet: %m");
245 	return (result);
246 }
247 
248 ssize_t
249 receive_packet(struct interface_info *interface, unsigned char *buf,
250     size_t len, struct sockaddr_in *from, struct hardware *hfrom)
251 {
252 	int length = 0, offset = 0;
253 	struct bpf_hdr hdr;
254 
255 	/*
256 	 * All this complexity is because BPF doesn't guarantee that
257 	 * only one packet will be returned at a time.  We're getting
258 	 * what we deserve, though - this is a terrible abuse of the BPF
259 	 * interface.  Sigh.
260 	 */
261 
262 	/* Process packets until we get one we can return or until we've
263 	 * done a read and gotten nothing we can return...
264 	 */
265 	do {
266 		/* If the buffer is empty, fill it. */
267 		if (interface->rbuf_offset == interface->rbuf_len) {
268 			length = read(interface->rfdesc, interface->rbuf,
269 			    interface->rbuf_max);
270 			if (length <= 0)
271 				return (length);
272 			interface->rbuf_offset = 0;
273 			interface->rbuf_len = length;
274 		}
275 
276 		/*
277 		 * If there isn't room for a whole bpf header, something
278 		 * went wrong, but we'll ignore it and hope it goes
279 		 * away... XXX
280 		 */
281 		if (interface->rbuf_len - interface->rbuf_offset <
282 		    sizeof(hdr)) {
283 			interface->rbuf_offset = interface->rbuf_len;
284 			continue;
285 		}
286 
287 		/* Copy out a bpf header... */
288 		memcpy(&hdr, &interface->rbuf[interface->rbuf_offset],
289 		    sizeof(hdr));
290 
291 		/*
292 		 * If the bpf header plus data doesn't fit in what's
293 		 * left of the buffer, stick head in sand yet again...
294 		 */
295 		if (interface->rbuf_offset + hdr.bh_hdrlen + hdr.bh_caplen >
296 		    interface->rbuf_len) {
297 			interface->rbuf_offset = interface->rbuf_len;
298 			continue;
299 		}
300 
301 		/*
302 		 * If the captured data wasn't the whole packet, or if
303 		 * the packet won't fit in the input buffer, all we can
304 		 * do is drop it.
305 		 */
306 		if (hdr.bh_caplen != hdr.bh_datalen) {
307 			interface->rbuf_offset += hdr.bh_hdrlen = hdr.bh_caplen;
308 			continue;
309 		}
310 
311 		/* Skip over the BPF header... */
312 		interface->rbuf_offset += hdr.bh_hdrlen;
313 
314 		/* Decode the physical header... */
315 		offset = decode_hw_header(interface,
316 		    interface->rbuf, interface->rbuf_offset, hfrom);
317 
318 		/*
319 		 * If a physical layer checksum failed (dunno of any
320 		 * physical layer that supports this, but WTH), skip
321 		 * this packet.
322 		 */
323 		if (offset < 0) {
324 			interface->rbuf_offset += hdr.bh_caplen;
325 			continue;
326 		}
327 		interface->rbuf_offset += offset;
328 		hdr.bh_caplen -= offset;
329 
330 		/* Decode the IP and UDP headers... */
331 		offset = decode_udp_ip_header(interface, interface->rbuf,
332 		    interface->rbuf_offset, from, NULL, hdr.bh_caplen);
333 
334 		/* If the IP or UDP checksum was bad, skip the packet... */
335 		if (offset < 0) {
336 			interface->rbuf_offset += hdr.bh_caplen;
337 			continue;
338 		}
339 		interface->rbuf_offset += offset;
340 		hdr.bh_caplen -= offset;
341 
342 		/*
343 		 * If there's not enough room to stash the packet data,
344 		 * we have to skip it (this shouldn't happen in real
345 		 * life, though).
346 		 */
347 		if (hdr.bh_caplen > len) {
348 			interface->rbuf_offset += hdr.bh_caplen;
349 			continue;
350 		}
351 
352 		/* Copy out the data in the packet... */
353 		memcpy(buf, interface->rbuf + interface->rbuf_offset,
354 		    hdr.bh_caplen);
355 		interface->rbuf_offset += hdr.bh_caplen;
356 		return (hdr.bh_caplen);
357 	} while (!length);
358 	return (0);
359 }
360