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