xref: /freebsd/sys/netinet/ip_divert.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD$
34  */
35 
36 #include "opt_inet.h"
37 #include "opt_ipfw.h"
38 #include "opt_ipdivert.h"
39 #include "opt_ipsec.h"
40 #include "opt_mac.h"
41 
42 #ifndef INET
43 #error "IPDIVERT requires INET."
44 #endif
45 
46 #include <sys/param.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mac.h>
51 #include <sys/mbuf.h>
52 #include <sys/proc.h>
53 #include <sys/protosw.h>
54 #include <sys/signalvar.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 
61 #include <vm/uma.h>
62 
63 #include <net/if.h>
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/in_var.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_var.h>
72 
73 /*
74  * Divert sockets
75  */
76 
77 /*
78  * Allocate enough space to hold a full IP packet
79  */
80 #define	DIVSNDQ		(65536 + 100)
81 #define	DIVRCVQ		(65536 + 100)
82 
83 /*
84  * Divert sockets work in conjunction with ipfw, see the divert(4)
85  * manpage for features.
86  * Internally, packets selected by ipfw in ip_input() or ip_output(),
87  * and never diverted before, are passed to the input queue of the
88  * divert socket with a given 'divert_port' number (as specified in
89  * the matching ipfw rule), and they are tagged with a 16 bit cookie
90  * (representing the rule number of the matching ipfw rule), which
91  * is passed to process reading from the socket.
92  *
93  * Packets written to the divert socket are again tagged with a cookie
94  * (usually the same as above) and a destination address.
95  * If the destination address is INADDR_ANY then the packet is
96  * treated as outgoing and sent to ip_output(), otherwise it is
97  * treated as incoming and sent to ip_input().
98  * In both cases, the packet is tagged with the cookie.
99  *
100  * On reinjection, processing in ip_input() and ip_output()
101  * will be exactly the same as for the original packet, except that
102  * ipfw processing will start at the rule number after the one
103  * written in the cookie (so, tagging a packet with a cookie of 0
104  * will cause it to be effectively considered as a standard packet).
105  */
106 
107 /* Internal variables */
108 static struct inpcbhead divcb;
109 static struct inpcbinfo divcbinfo;
110 
111 static u_long	div_sendspace = DIVSNDQ;	/* XXX sysctl ? */
112 static u_long	div_recvspace = DIVRCVQ;	/* XXX sysctl ? */
113 
114 /* Optimization: have this preinitialized */
115 static struct sockaddr_in divsrc = { sizeof(divsrc), AF_INET };
116 
117 /*
118  * Initialize divert connection block queue.
119  */
120 void
121 div_init(void)
122 {
123 	INP_INFO_LOCK_INIT(&divcbinfo, "div");
124 	LIST_INIT(&divcb);
125 	divcbinfo.listhead = &divcb;
126 	/*
127 	 * XXX We don't use the hash list for divert IP, but it's easier
128 	 * to allocate a one entry hash list than it is to check all
129 	 * over the place for hashbase == NULL.
130 	 */
131 	divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
132 	divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
133 	divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
134 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
135 	uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
136 }
137 
138 /*
139  * IPPROTO_DIVERT is not in the real IP protocol number space; this
140  * function should never be called.  Just in case, drop any packets.
141  */
142 void
143 div_input(struct mbuf *m, int off)
144 {
145 	ipstat.ips_noproto++;
146 	m_freem(m);
147 }
148 
149 /*
150  * Divert a packet by passing it up to the divert socket at port 'port'.
151  *
152  * Setup generic address and protocol structures for div_input routine,
153  * then pass them along with mbuf chain.
154  */
155 void
156 divert_packet(struct mbuf *m, int incoming, int port, int rule)
157 {
158 	struct ip *ip;
159 	struct inpcb *inp;
160 	struct socket *sa;
161 	u_int16_t nport;
162 
163 	/* Sanity check */
164 	KASSERT(port != 0, ("%s: port=0", __func__));
165 
166 	divsrc.sin_port = rule;		/* record matching rule */
167 
168 	/* Assure header */
169 	if (m->m_len < sizeof(struct ip) &&
170 	    (m = m_pullup(m, sizeof(struct ip))) == 0)
171 		return;
172 	ip = mtod(m, struct ip *);
173 
174 	/*
175 	 * Record receive interface address, if any.
176 	 * But only for incoming packets.
177 	 */
178 	divsrc.sin_addr.s_addr = 0;
179 	if (incoming) {
180 		struct ifaddr *ifa;
181 
182 		/* Sanity check */
183 		KASSERT((m->m_flags & M_PKTHDR), ("%s: !PKTHDR", __func__));
184 
185 		/* Find IP address for receive interface */
186 		TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
187 			if (ifa->ifa_addr == NULL)
188 				continue;
189 			if (ifa->ifa_addr->sa_family != AF_INET)
190 				continue;
191 			divsrc.sin_addr =
192 			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
193 			break;
194 		}
195 	}
196 	/*
197 	 * Record the incoming interface name whenever we have one.
198 	 */
199 	bzero(&divsrc.sin_zero, sizeof(divsrc.sin_zero));
200 	if (m->m_pkthdr.rcvif) {
201 		/*
202 		 * Hide the actual interface name in there in the
203 		 * sin_zero array. XXX This needs to be moved to a
204 		 * different sockaddr type for divert, e.g.
205 		 * sockaddr_div with multiple fields like
206 		 * sockaddr_dl. Presently we have only 7 bytes
207 		 * but that will do for now as most interfaces
208 		 * are 4 or less + 2 or less bytes for unit.
209 		 * There is probably a faster way of doing this,
210 		 * possibly taking it from the sockaddr_dl on the iface.
211 		 * This solves the problem of a P2P link and a LAN interface
212 		 * having the same address, which can result in the wrong
213 		 * interface being assigned to the packet when fed back
214 		 * into the divert socket. Theoretically if the daemon saves
215 		 * and re-uses the sockaddr_in as suggested in the man pages,
216 		 * this iface name will come along for the ride.
217 		 * (see div_output for the other half of this.)
218 		 */
219 		snprintf(divsrc.sin_zero, sizeof(divsrc.sin_zero),
220 			"%s%d", m->m_pkthdr.rcvif->if_name,
221 			m->m_pkthdr.rcvif->if_unit);
222 	}
223 
224 	/* Put packet on socket queue, if any */
225 	sa = NULL;
226 	nport = htons((u_int16_t)port);
227 	LIST_FOREACH(inp, &divcb, inp_list) {
228 		if (inp->inp_lport == nport)
229 			sa = inp->inp_socket;
230 	}
231 	if (sa) {
232 		if (sbappendaddr(&sa->so_rcv, (struct sockaddr *)&divsrc,
233 				m, (struct mbuf *)0) == 0)
234 			m_freem(m);
235 		else
236 			sorwakeup(sa);
237 	} else {
238 		m_freem(m);
239 		ipstat.ips_noproto++;
240 		ipstat.ips_delivered--;
241         }
242 }
243 
244 /*
245  * Deliver packet back into the IP processing machinery.
246  *
247  * If no address specified, or address is 0.0.0.0, send to ip_output();
248  * otherwise, send to ip_input() and mark as having been received on
249  * the interface with that address.
250  */
251 static int
252 div_output(struct socket *so, struct mbuf *m,
253 	struct sockaddr_in *sin, struct mbuf *control)
254 {
255 	int error = 0;
256 	struct m_hdr divert_tag;
257 
258 	/*
259 	 * Prepare the tag for divert info. Note that a packet
260 	 * with a 0 tag in mh_data is effectively untagged,
261 	 * so we could optimize that case.
262 	 */
263 	divert_tag.mh_type = MT_TAG;
264 	divert_tag.mh_flags = PACKET_TAG_DIVERT;
265 	divert_tag.mh_next = m;
266 	divert_tag.mh_data = 0;		/* the matching rule # */
267 	m->m_pkthdr.rcvif = NULL;	/* XXX is it necessary ? */
268 
269 #ifdef MAC
270 	mac_create_mbuf_from_socket(so, m);
271 #endif
272 
273 	if (control)
274 		m_freem(control);		/* XXX */
275 
276 	/* Loopback avoidance and state recovery */
277 	if (sin) {
278 		int i;
279 
280 		divert_tag.mh_data = (caddr_t)(uintptr_t)sin->sin_port;
281 		/*
282 		 * Find receive interface with the given name, stuffed
283 		 * (if it exists) in the sin_zero[] field.
284 		 * The name is user supplied data so don't trust its size
285 		 * or that it is zero terminated.
286 		 */
287 		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
288 			;
289 		if ( i > 0 && i < sizeof(sin->sin_zero))
290 			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
291 	}
292 
293 	/* Reinject packet into the system as incoming or outgoing */
294 	if (!sin || sin->sin_addr.s_addr == 0) {
295 		struct inpcb *const inp = sotoinpcb(so);
296 		struct ip *const ip = mtod(m, struct ip *);
297 
298 		/*
299 		 * Don't allow both user specified and setsockopt options,
300 		 * and don't allow packet length sizes that will crash
301 		 */
302 		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
303 		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
304 			error = EINVAL;
305 			goto cantsend;
306 		}
307 
308 		/* Convert fields to host order for ip_output() */
309 		ip->ip_len = ntohs(ip->ip_len);
310 		ip->ip_off = ntohs(ip->ip_off);
311 
312 		/* Send packet to output processing */
313 		ipstat.ips_rawout++;			/* XXX */
314 		error = ip_output((struct mbuf *)&divert_tag,
315 			    inp->inp_options, &inp->inp_route,
316 			    (so->so_options & SO_DONTROUTE) |
317 			    IP_ALLOWBROADCAST | IP_RAWOUTPUT,
318 			    inp->inp_moptions, NULL);
319 	} else {
320 		if (m->m_pkthdr.rcvif == NULL) {
321 			/*
322 			 * No luck with the name, check by IP address.
323 			 * Clear the port and the ifname to make sure
324 			 * there are no distractions for ifa_ifwithaddr.
325 			 */
326 			struct	ifaddr *ifa;
327 
328 			bzero(sin->sin_zero, sizeof(sin->sin_zero));
329 			sin->sin_port = 0;
330 			ifa = ifa_ifwithaddr((struct sockaddr *) sin);
331 			if (ifa == NULL) {
332 				error = EADDRNOTAVAIL;
333 				goto cantsend;
334 			}
335 			m->m_pkthdr.rcvif = ifa->ifa_ifp;
336 		}
337 		/* Send packet to input processing */
338 		ip_input((struct mbuf *)&divert_tag);
339 	}
340 
341 	return error;
342 
343 cantsend:
344 	m_freem(m);
345 	return error;
346 }
347 
348 static int
349 div_attach(struct socket *so, int proto, struct thread *td)
350 {
351 	struct inpcb *inp;
352 	int error, s;
353 
354 	inp  = sotoinpcb(so);
355 	if (inp)
356 		panic("div_attach");
357 	if (td && (error = suser(td)) != 0)
358 		return error;
359 
360 	error = soreserve(so, div_sendspace, div_recvspace);
361 	if (error)
362 		return error;
363 	s = splnet();
364 	error = in_pcballoc(so, &divcbinfo, td);
365 	splx(s);
366 	if (error)
367 		return error;
368 	inp = (struct inpcb *)so->so_pcb;
369 	inp->inp_ip_p = proto;
370 	inp->inp_vflag |= INP_IPV4;
371 	inp->inp_flags |= INP_HDRINCL;
372 	/* The socket is always "connected" because
373 	   we always know "where" to send the packet */
374 	so->so_state |= SS_ISCONNECTED;
375 	return 0;
376 }
377 
378 static int
379 div_detach(struct socket *so)
380 {
381 	struct inpcb *inp;
382 
383 	inp = sotoinpcb(so);
384 	if (inp == 0)
385 		panic("div_detach");
386 	in_pcbdetach(inp);
387 	return 0;
388 }
389 
390 static int
391 div_abort(struct socket *so)
392 {
393 	soisdisconnected(so);
394 	return div_detach(so);
395 }
396 
397 static int
398 div_disconnect(struct socket *so)
399 {
400 	if ((so->so_state & SS_ISCONNECTED) == 0)
401 		return ENOTCONN;
402 	return div_abort(so);
403 }
404 
405 static int
406 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
407 {
408 	struct inpcb *inp;
409 	int s;
410 	int error;
411 
412 	s = splnet();
413 	inp = sotoinpcb(so);
414 	/* in_pcbbind assumes that nam is a sockaddr_in
415 	 * and in_pcbbind requires a valid address. Since divert
416 	 * sockets don't we need to make sure the address is
417 	 * filled in properly.
418 	 * XXX -- divert should not be abusing in_pcbind
419 	 * and should probably have its own family.
420 	 */
421 	if (nam->sa_family != AF_INET)
422 		error = EAFNOSUPPORT;
423 	else {
424 		((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
425 		error = in_pcbbind(inp, nam, td);
426 	}
427 	splx(s);
428 	return error;
429 }
430 
431 static int
432 div_shutdown(struct socket *so)
433 {
434 	socantsendmore(so);
435 	return 0;
436 }
437 
438 static int
439 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
440 	 struct mbuf *control, struct thread *td)
441 {
442 	/* Packet must have a header (but that's about it) */
443 	if (m->m_len < sizeof (struct ip) &&
444 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
445 		ipstat.ips_toosmall++;
446 		m_freem(m);
447 		return EINVAL;
448 	}
449 
450 	/* Send packet */
451 	return div_output(so, m, (struct sockaddr_in *)nam, control);
452 }
453 
454 static int
455 div_pcblist(SYSCTL_HANDLER_ARGS)
456 {
457 	int error, i, n, s;
458 	struct inpcb *inp, **inp_list;
459 	inp_gen_t gencnt;
460 	struct xinpgen xig;
461 
462 	/*
463 	 * The process of preparing the TCB list is too time-consuming and
464 	 * resource-intensive to repeat twice on every request.
465 	 */
466 	if (req->oldptr == 0) {
467 		n = divcbinfo.ipi_count;
468 		req->oldidx = 2 * (sizeof xig)
469 			+ (n + n/8) * sizeof(struct xinpcb);
470 		return 0;
471 	}
472 
473 	if (req->newptr != 0)
474 		return EPERM;
475 
476 	/*
477 	 * OK, now we're committed to doing something.
478 	 */
479 	s = splnet();
480 	gencnt = divcbinfo.ipi_gencnt;
481 	n = divcbinfo.ipi_count;
482 	splx(s);
483 
484 	xig.xig_len = sizeof xig;
485 	xig.xig_count = n;
486 	xig.xig_gen = gencnt;
487 	xig.xig_sogen = so_gencnt;
488 	error = SYSCTL_OUT(req, &xig, sizeof xig);
489 	if (error)
490 		return error;
491 
492 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
493 	if (inp_list == 0)
494 		return ENOMEM;
495 
496 	s = splnet();
497 	for (inp = LIST_FIRST(divcbinfo.listhead), i = 0; inp && i < n;
498 	     inp = LIST_NEXT(inp, inp_list)) {
499 		if (inp->inp_gencnt <= gencnt && !prison_xinpcb(req->td, inp))
500 			inp_list[i++] = inp;
501 	}
502 	splx(s);
503 	n = i;
504 
505 	error = 0;
506 	for (i = 0; i < n; i++) {
507 		inp = inp_list[i];
508 		if (inp->inp_gencnt <= gencnt) {
509 			struct xinpcb xi;
510 			xi.xi_len = sizeof xi;
511 			/* XXX should avoid extra copy */
512 			bcopy(inp, &xi.xi_inp, sizeof *inp);
513 			if (inp->inp_socket)
514 				sotoxsocket(inp->inp_socket, &xi.xi_socket);
515 			error = SYSCTL_OUT(req, &xi, sizeof xi);
516 		}
517 	}
518 	if (!error) {
519 		/*
520 		 * Give the user an updated idea of our state.
521 		 * If the generation differs from what we told
522 		 * her before, she knows that something happened
523 		 * while we were processing this request, and it
524 		 * might be necessary to retry.
525 		 */
526 		s = splnet();
527 		xig.xig_gen = divcbinfo.ipi_gencnt;
528 		xig.xig_sogen = so_gencnt;
529 		xig.xig_count = divcbinfo.ipi_count;
530 		splx(s);
531 		error = SYSCTL_OUT(req, &xig, sizeof xig);
532 	}
533 	free(inp_list, M_TEMP);
534 	return error;
535 }
536 
537 /*
538  * This is the wrapper function for in_setsockaddr.  We just pass down
539  * the pcbinfo for in_setpeeraddr to lock.
540  */
541 static int
542 div_sockaddr(struct socket *so, struct sockaddr **nam)
543 {
544 	return (in_setsockaddr(so, nam, &divcbinfo));
545 }
546 
547 /*
548  * This is the wrapper function for in_setpeeraddr. We just pass down
549  * the pcbinfo for in_setpeeraddr to lock.
550  */
551 static int
552 div_peeraddr(struct socket *so, struct sockaddr **nam)
553 {
554 	return (in_setpeeraddr(so, nam, &divcbinfo));
555 }
556 
557 
558 SYSCTL_DECL(_net_inet_divert);
559 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
560 	    div_pcblist, "S,xinpcb", "List of active divert sockets");
561 
562 struct pr_usrreqs div_usrreqs = {
563 	div_abort, pru_accept_notsupp, div_attach, div_bind,
564 	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
565 	div_disconnect, pru_listen_notsupp, div_peeraddr, pru_rcvd_notsupp,
566 	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
567 	div_sockaddr, sosend, soreceive, sopoll
568 };
569