xref: /freebsd/sys/netinet/ip_divert.c (revision 7773002178c8dbc52b44e4d705f07706409af8e4)
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 /*
115  * Initialize divert connection block queue.
116  */
117 void
118 div_init(void)
119 {
120 	INP_INFO_LOCK_INIT(&divcbinfo, "div");
121 	LIST_INIT(&divcb);
122 	divcbinfo.listhead = &divcb;
123 	/*
124 	 * XXX We don't use the hash list for divert IP, but it's easier
125 	 * to allocate a one entry hash list than it is to check all
126 	 * over the place for hashbase == NULL.
127 	 */
128 	divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
129 	divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
130 	divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
131 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
132 	uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
133 }
134 
135 /*
136  * IPPROTO_DIVERT is not in the real IP protocol number space; this
137  * function should never be called.  Just in case, drop any packets.
138  */
139 void
140 div_input(struct mbuf *m, int off)
141 {
142 	ipstat.ips_noproto++;
143 	m_freem(m);
144 }
145 
146 /*
147  * Divert a packet by passing it up to the divert socket at port 'port'.
148  *
149  * Setup generic address and protocol structures for div_input routine,
150  * then pass them along with mbuf chain.
151  */
152 void
153 divert_packet(struct mbuf *m, int incoming, int port, int rule)
154 {
155 	struct ip *ip;
156 	struct inpcb *inp;
157 	struct socket *sa;
158 	u_int16_t nport;
159 	struct sockaddr_in divsrc;
160 
161 	/* Sanity check */
162 	KASSERT(port != 0, ("%s: port=0", __func__));
163 
164 	/* Assure header */
165 	if (m->m_len < sizeof(struct ip) &&
166 	    (m = m_pullup(m, sizeof(struct ip))) == 0)
167 		return;
168 	ip = mtod(m, struct ip *);
169 
170 	/*
171 	 * Record receive interface address, if any.
172 	 * But only for incoming packets.
173 	 */
174 	bzero(&divsrc, sizeof(divsrc));
175 	divsrc.sin_len = sizeof(divsrc);
176 	divsrc.sin_family = AF_INET;
177 	divsrc.sin_port = rule;		/* record matching rule */
178 	if (incoming) {
179 		struct ifaddr *ifa;
180 
181 		/* Sanity check */
182 		M_ASSERTPKTHDR(m);
183 
184 		/* Find IP address for receive interface */
185 		TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
186 			if (ifa->ifa_addr == NULL)
187 				continue;
188 			if (ifa->ifa_addr->sa_family != AF_INET)
189 				continue;
190 			divsrc.sin_addr =
191 			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
192 			break;
193 		}
194 	}
195 	/*
196 	 * Record the incoming interface name whenever we have one.
197 	 */
198 	if (m->m_pkthdr.rcvif) {
199 		/*
200 		 * Hide the actual interface name in there in the
201 		 * sin_zero array. XXX This needs to be moved to a
202 		 * different sockaddr type for divert, e.g.
203 		 * sockaddr_div with multiple fields like
204 		 * sockaddr_dl. Presently we have only 7 bytes
205 		 * but that will do for now as most interfaces
206 		 * are 4 or less + 2 or less bytes for unit.
207 		 * There is probably a faster way of doing this,
208 		 * possibly taking it from the sockaddr_dl on the iface.
209 		 * This solves the problem of a P2P link and a LAN interface
210 		 * having the same address, which can result in the wrong
211 		 * interface being assigned to the packet when fed back
212 		 * into the divert socket. Theoretically if the daemon saves
213 		 * and re-uses the sockaddr_in as suggested in the man pages,
214 		 * this iface name will come along for the ride.
215 		 * (see div_output for the other half of this.)
216 		 */
217 		strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
218 		    sizeof(divsrc.sin_zero));
219 	}
220 
221 	/* Put packet on socket queue, if any */
222 	sa = NULL;
223 	nport = htons((u_int16_t)port);
224 	INP_INFO_RLOCK(&divcbinfo);
225 	LIST_FOREACH(inp, &divcb, inp_list) {
226 		INP_LOCK(inp);
227 		/* XXX why does only one socket match? */
228 		if (inp->inp_lport == nport) {
229 			sa = inp->inp_socket;
230 			if (sbappendaddr(&sa->so_rcv,
231 			    (struct sockaddr *)&divsrc, m,
232 			    (struct mbuf *)0) == 0)
233 				sa = NULL;	/* force mbuf reclaim below */
234 			else
235 				sorwakeup(sa);
236 			INP_UNLOCK(inp);
237 			break;
238 		}
239 		INP_UNLOCK(inp);
240 	}
241 	INP_INFO_RUNLOCK(&divcbinfo);
242 	if (sa == NULL) {
243 		m_freem(m);
244 		ipstat.ips_noproto++;
245 		ipstat.ips_delivered--;
246         }
247 }
248 
249 /*
250  * Deliver packet back into the IP processing machinery.
251  *
252  * If no address specified, or address is 0.0.0.0, send to ip_output();
253  * otherwise, send to ip_input() and mark as having been received on
254  * the interface with that address.
255  */
256 static int
257 div_output(struct socket *so, struct mbuf *m,
258 	struct sockaddr_in *sin, struct mbuf *control)
259 {
260 	int error = 0;
261 	struct m_hdr divert_tag;
262 
263 	/*
264 	 * Prepare the tag for divert info. Note that a packet
265 	 * with a 0 tag in mh_data is effectively untagged,
266 	 * so we could optimize that case.
267 	 */
268 	divert_tag.mh_type = MT_TAG;
269 	divert_tag.mh_flags = PACKET_TAG_DIVERT;
270 	divert_tag.mh_next = m;
271 	divert_tag.mh_data = 0;		/* the matching rule # */
272 	m->m_pkthdr.rcvif = NULL;	/* XXX is it necessary ? */
273 
274 #ifdef MAC
275 	mac_create_mbuf_from_socket(so, m);
276 #endif
277 
278 	if (control)
279 		m_freem(control);		/* XXX */
280 
281 	/* Loopback avoidance and state recovery */
282 	if (sin) {
283 		int i;
284 
285 		divert_tag.mh_data = (caddr_t)(uintptr_t)sin->sin_port;
286 		/*
287 		 * Find receive interface with the given name, stuffed
288 		 * (if it exists) in the sin_zero[] field.
289 		 * The name is user supplied data so don't trust its size
290 		 * or that it is zero terminated.
291 		 */
292 		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
293 			;
294 		if ( i > 0 && i < sizeof(sin->sin_zero))
295 			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
296 	}
297 
298 	/* Reinject packet into the system as incoming or outgoing */
299 	if (!sin || sin->sin_addr.s_addr == 0) {
300 		struct inpcb *const inp = sotoinpcb(so);
301 		struct ip *const ip = mtod(m, struct ip *);
302 
303 		/*
304 		 * Don't allow both user specified and setsockopt options,
305 		 * and don't allow packet length sizes that will crash
306 		 */
307 		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
308 		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
309 			error = EINVAL;
310 			goto cantsend;
311 		}
312 
313 		/* Convert fields to host order for ip_output() */
314 		ip->ip_len = ntohs(ip->ip_len);
315 		ip->ip_off = ntohs(ip->ip_off);
316 
317 		/* Send packet to output processing */
318 		ipstat.ips_rawout++;			/* XXX */
319 		error = ip_output((struct mbuf *)&divert_tag,
320 			    inp->inp_options, &inp->inp_route,
321 			    (so->so_options & SO_DONTROUTE) |
322 			    IP_ALLOWBROADCAST | IP_RAWOUTPUT,
323 			    inp->inp_moptions, NULL);
324 	} else {
325 		if (m->m_pkthdr.rcvif == NULL) {
326 			/*
327 			 * No luck with the name, check by IP address.
328 			 * Clear the port and the ifname to make sure
329 			 * there are no distractions for ifa_ifwithaddr.
330 			 */
331 			struct	ifaddr *ifa;
332 
333 			bzero(sin->sin_zero, sizeof(sin->sin_zero));
334 			sin->sin_port = 0;
335 			ifa = ifa_ifwithaddr((struct sockaddr *) sin);
336 			if (ifa == NULL) {
337 				error = EADDRNOTAVAIL;
338 				goto cantsend;
339 			}
340 			m->m_pkthdr.rcvif = ifa->ifa_ifp;
341 		}
342 		/* Send packet to input processing */
343 		ip_input((struct mbuf *)&divert_tag);
344 	}
345 
346 	return error;
347 
348 cantsend:
349 	m_freem(m);
350 	return error;
351 }
352 
353 static int
354 div_attach(struct socket *so, int proto, struct thread *td)
355 {
356 	struct inpcb *inp;
357 	int error;
358 
359 	INP_INFO_WLOCK(&divcbinfo);
360 	inp  = sotoinpcb(so);
361 	if (inp != 0) {
362 		INP_INFO_WUNLOCK(&divcbinfo);
363 		return EINVAL;
364 	}
365 	if (td && (error = suser(td)) != 0) {
366 		INP_INFO_WUNLOCK(&divcbinfo);
367 		return error;
368 	}
369 	error = soreserve(so, div_sendspace, div_recvspace);
370 	if (error) {
371 		INP_INFO_WUNLOCK(&divcbinfo);
372 		return error;
373 	}
374 	error = in_pcballoc(so, &divcbinfo, td);
375 	if (error) {
376 		INP_INFO_WUNLOCK(&divcbinfo);
377 		return error;
378 	}
379 	inp = (struct inpcb *)so->so_pcb;
380 	INP_LOCK(inp);
381 	INP_INFO_WUNLOCK(&divcbinfo);
382 	inp->inp_ip_p = proto;
383 	inp->inp_vflag |= INP_IPV4;
384 	inp->inp_flags |= INP_HDRINCL;
385 	/* The socket is always "connected" because
386 	   we always know "where" to send the packet */
387 	INP_UNLOCK(inp);
388 	so->so_state |= SS_ISCONNECTED;
389 	return 0;
390 }
391 
392 static int
393 div_detach(struct socket *so)
394 {
395 	struct inpcb *inp;
396 
397 	INP_INFO_WLOCK(&divcbinfo);
398 	inp = sotoinpcb(so);
399 	if (inp == 0) {
400 		INP_INFO_WUNLOCK(&divcbinfo);
401 		return EINVAL;
402 	}
403 	INP_LOCK(inp);
404 	in_pcbdetach(inp);
405 	INP_INFO_WUNLOCK(&divcbinfo);
406 	return 0;
407 }
408 
409 static int
410 div_abort(struct socket *so)
411 {
412 	soisdisconnected(so);
413 	return div_detach(so);
414 }
415 
416 static int
417 div_disconnect(struct socket *so)
418 {
419 	if ((so->so_state & SS_ISCONNECTED) == 0)
420 		return ENOTCONN;
421 	return div_abort(so);
422 }
423 
424 static int
425 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
426 {
427 	struct inpcb *inp;
428 	int error;
429 
430 	INP_INFO_WLOCK(&divcbinfo);
431 	inp = sotoinpcb(so);
432 	if (inp == 0) {
433 		INP_INFO_WUNLOCK(&divcbinfo);
434 		return EINVAL;
435 	}
436 	/* in_pcbbind assumes that nam is a sockaddr_in
437 	 * and in_pcbbind requires a valid address. Since divert
438 	 * sockets don't we need to make sure the address is
439 	 * filled in properly.
440 	 * XXX -- divert should not be abusing in_pcbind
441 	 * and should probably have its own family.
442 	 */
443 	if (nam->sa_family != AF_INET)
444 		error = EAFNOSUPPORT;
445 	else {
446 		((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
447 		INP_LOCK(inp);
448 		error = in_pcbbind(inp, nam, td);
449 		INP_UNLOCK(inp);
450 	}
451 	INP_INFO_WUNLOCK(&divcbinfo);
452 	return error;
453 }
454 
455 static int
456 div_shutdown(struct socket *so)
457 {
458 	socantsendmore(so);
459 	return 0;
460 }
461 
462 static int
463 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
464 	 struct mbuf *control, struct thread *td)
465 {
466 	/* Packet must have a header (but that's about it) */
467 	if (m->m_len < sizeof (struct ip) &&
468 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
469 		ipstat.ips_toosmall++;
470 		m_freem(m);
471 		return EINVAL;
472 	}
473 
474 	/* Send packet */
475 	return div_output(so, m, (struct sockaddr_in *)nam, control);
476 }
477 
478 static int
479 div_pcblist(SYSCTL_HANDLER_ARGS)
480 {
481 	int error, i, n;
482 	struct inpcb *inp, **inp_list;
483 	inp_gen_t gencnt;
484 	struct xinpgen xig;
485 
486 	/*
487 	 * The process of preparing the TCB list is too time-consuming and
488 	 * resource-intensive to repeat twice on every request.
489 	 */
490 	if (req->oldptr == 0) {
491 		n = divcbinfo.ipi_count;
492 		req->oldidx = 2 * (sizeof xig)
493 			+ (n + n/8) * sizeof(struct xinpcb);
494 		return 0;
495 	}
496 
497 	if (req->newptr != 0)
498 		return EPERM;
499 
500 	/*
501 	 * OK, now we're committed to doing something.
502 	 */
503 	INP_INFO_RLOCK(&divcbinfo);
504 	gencnt = divcbinfo.ipi_gencnt;
505 	n = divcbinfo.ipi_count;
506 	INP_INFO_RUNLOCK(&divcbinfo);
507 
508 	sysctl_wire_old_buffer(req, 2 * sizeof(xig) + n*sizeof(struct xinpcb));
509 
510 	xig.xig_len = sizeof xig;
511 	xig.xig_count = n;
512 	xig.xig_gen = gencnt;
513 	xig.xig_sogen = so_gencnt;
514 	error = SYSCTL_OUT(req, &xig, sizeof xig);
515 	if (error)
516 		return error;
517 
518 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
519 	if (inp_list == 0)
520 		return ENOMEM;
521 
522 	INP_INFO_RLOCK(&divcbinfo);
523 	for (inp = LIST_FIRST(divcbinfo.listhead), i = 0; inp && i < n;
524 	     inp = LIST_NEXT(inp, inp_list)) {
525 		INP_LOCK(inp);
526 		if (inp->inp_gencnt <= gencnt &&
527 		    cr_canseesocket(req->td->td_ucred, inp->inp_socket) == 0)
528 			inp_list[i++] = inp;
529 		INP_UNLOCK(inp);
530 	}
531 	INP_INFO_RUNLOCK(&divcbinfo);
532 	n = i;
533 
534 	error = 0;
535 	for (i = 0; i < n; i++) {
536 		inp = inp_list[i];
537 		if (inp->inp_gencnt <= gencnt) {
538 			struct xinpcb xi;
539 			xi.xi_len = sizeof xi;
540 			/* XXX should avoid extra copy */
541 			bcopy(inp, &xi.xi_inp, sizeof *inp);
542 			if (inp->inp_socket)
543 				sotoxsocket(inp->inp_socket, &xi.xi_socket);
544 			error = SYSCTL_OUT(req, &xi, sizeof xi);
545 		}
546 	}
547 	if (!error) {
548 		/*
549 		 * Give the user an updated idea of our state.
550 		 * If the generation differs from what we told
551 		 * her before, she knows that something happened
552 		 * while we were processing this request, and it
553 		 * might be necessary to retry.
554 		 */
555 		INP_INFO_RLOCK(&divcbinfo);
556 		xig.xig_gen = divcbinfo.ipi_gencnt;
557 		xig.xig_sogen = so_gencnt;
558 		xig.xig_count = divcbinfo.ipi_count;
559 		INP_INFO_RUNLOCK(&divcbinfo);
560 		error = SYSCTL_OUT(req, &xig, sizeof xig);
561 	}
562 	free(inp_list, M_TEMP);
563 	return error;
564 }
565 
566 /*
567  * This is the wrapper function for in_setsockaddr.  We just pass down
568  * the pcbinfo for in_setpeeraddr to lock.
569  */
570 static int
571 div_sockaddr(struct socket *so, struct sockaddr **nam)
572 {
573 	return (in_setsockaddr(so, nam, &divcbinfo));
574 }
575 
576 /*
577  * This is the wrapper function for in_setpeeraddr. We just pass down
578  * the pcbinfo for in_setpeeraddr to lock.
579  */
580 static int
581 div_peeraddr(struct socket *so, struct sockaddr **nam)
582 {
583 	return (in_setpeeraddr(so, nam, &divcbinfo));
584 }
585 
586 
587 SYSCTL_DECL(_net_inet_divert);
588 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
589 	    div_pcblist, "S,xinpcb", "List of active divert sockets");
590 
591 struct pr_usrreqs div_usrreqs = {
592 	div_abort, pru_accept_notsupp, div_attach, div_bind,
593 	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
594 	div_disconnect, pru_listen_notsupp, div_peeraddr, pru_rcvd_notsupp,
595 	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
596 	div_sockaddr, sosend, soreceive, sopoll
597 };
598