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