xref: /freebsd/sys/netinet/ip_divert.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 		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 	INP_INFO_RLOCK(&divcbinfo);
226 	LIST_FOREACH(inp, &divcb, inp_list) {
227 		INP_LOCK(inp);
228 		/* XXX why does only one socket match? */
229 		if (inp->inp_lport == nport) {
230 			sa = inp->inp_socket;
231 			if (sbappendaddr(&sa->so_rcv,
232 			    (struct sockaddr *)&divsrc, m,
233 			    (struct mbuf *)0) == 0)
234 				sa = NULL;	/* force mbuf reclaim below */
235 			else
236 				sorwakeup(sa);
237 			INP_UNLOCK(inp);
238 			break;
239 		}
240 		INP_UNLOCK(inp);
241 	}
242 	INP_INFO_RUNLOCK(&divcbinfo);
243 	if (sa == NULL) {
244 		m_freem(m);
245 		ipstat.ips_noproto++;
246 		ipstat.ips_delivered--;
247         }
248 }
249 
250 /*
251  * Deliver packet back into the IP processing machinery.
252  *
253  * If no address specified, or address is 0.0.0.0, send to ip_output();
254  * otherwise, send to ip_input() and mark as having been received on
255  * the interface with that address.
256  */
257 static int
258 div_output(struct socket *so, struct mbuf *m,
259 	struct sockaddr_in *sin, struct mbuf *control)
260 {
261 	int error = 0;
262 	struct m_hdr divert_tag;
263 
264 	/*
265 	 * Prepare the tag for divert info. Note that a packet
266 	 * with a 0 tag in mh_data is effectively untagged,
267 	 * so we could optimize that case.
268 	 */
269 	divert_tag.mh_type = MT_TAG;
270 	divert_tag.mh_flags = PACKET_TAG_DIVERT;
271 	divert_tag.mh_next = m;
272 	divert_tag.mh_data = 0;		/* the matching rule # */
273 	m->m_pkthdr.rcvif = NULL;	/* XXX is it necessary ? */
274 
275 #ifdef MAC
276 	mac_create_mbuf_from_socket(so, m);
277 #endif
278 
279 	if (control)
280 		m_freem(control);		/* XXX */
281 
282 	/* Loopback avoidance and state recovery */
283 	if (sin) {
284 		int i;
285 
286 		divert_tag.mh_data = (caddr_t)(uintptr_t)sin->sin_port;
287 		/*
288 		 * Find receive interface with the given name, stuffed
289 		 * (if it exists) in the sin_zero[] field.
290 		 * The name is user supplied data so don't trust its size
291 		 * or that it is zero terminated.
292 		 */
293 		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
294 			;
295 		if ( i > 0 && i < sizeof(sin->sin_zero))
296 			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
297 	}
298 
299 	/* Reinject packet into the system as incoming or outgoing */
300 	if (!sin || sin->sin_addr.s_addr == 0) {
301 		struct inpcb *const inp = sotoinpcb(so);
302 		struct ip *const ip = mtod(m, struct ip *);
303 
304 		/*
305 		 * Don't allow both user specified and setsockopt options,
306 		 * and don't allow packet length sizes that will crash
307 		 */
308 		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
309 		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
310 			error = EINVAL;
311 			goto cantsend;
312 		}
313 
314 		/* Convert fields to host order for ip_output() */
315 		ip->ip_len = ntohs(ip->ip_len);
316 		ip->ip_off = ntohs(ip->ip_off);
317 
318 		/* Send packet to output processing */
319 		ipstat.ips_rawout++;			/* XXX */
320 		error = ip_output((struct mbuf *)&divert_tag,
321 			    inp->inp_options, &inp->inp_route,
322 			    (so->so_options & SO_DONTROUTE) |
323 			    IP_ALLOWBROADCAST | IP_RAWOUTPUT,
324 			    inp->inp_moptions, NULL);
325 	} else {
326 		if (m->m_pkthdr.rcvif == NULL) {
327 			/*
328 			 * No luck with the name, check by IP address.
329 			 * Clear the port and the ifname to make sure
330 			 * there are no distractions for ifa_ifwithaddr.
331 			 */
332 			struct	ifaddr *ifa;
333 
334 			bzero(sin->sin_zero, sizeof(sin->sin_zero));
335 			sin->sin_port = 0;
336 			ifa = ifa_ifwithaddr((struct sockaddr *) sin);
337 			if (ifa == NULL) {
338 				error = EADDRNOTAVAIL;
339 				goto cantsend;
340 			}
341 			m->m_pkthdr.rcvif = ifa->ifa_ifp;
342 		}
343 		/* Send packet to input processing */
344 		ip_input((struct mbuf *)&divert_tag);
345 	}
346 
347 	return error;
348 
349 cantsend:
350 	m_freem(m);
351 	return error;
352 }
353 
354 static int
355 div_attach(struct socket *so, int proto, struct thread *td)
356 {
357 	struct inpcb *inp;
358 	int error;
359 
360 	INP_INFO_WLOCK(&divcbinfo);
361 	inp  = sotoinpcb(so);
362 	if (inp != 0) {
363 		INP_INFO_WUNLOCK(&divcbinfo);
364 		return EINVAL;
365 	}
366 	if (td && (error = suser(td)) != 0) {
367 		INP_INFO_WUNLOCK(&divcbinfo);
368 		return error;
369 	}
370 	error = soreserve(so, div_sendspace, div_recvspace);
371 	if (error) {
372 		INP_INFO_WUNLOCK(&divcbinfo);
373 		return error;
374 	}
375 	error = in_pcballoc(so, &divcbinfo, td);
376 	if (error) {
377 		INP_INFO_WUNLOCK(&divcbinfo);
378 		return error;
379 	}
380 	inp = (struct inpcb *)so->so_pcb;
381 	INP_LOCK(inp);
382 	INP_INFO_WUNLOCK(&divcbinfo);
383 	inp->inp_ip_p = proto;
384 	inp->inp_vflag |= INP_IPV4;
385 	inp->inp_flags |= INP_HDRINCL;
386 	/* The socket is always "connected" because
387 	   we always know "where" to send the packet */
388 	INP_UNLOCK(inp);
389 	so->so_state |= SS_ISCONNECTED;
390 	return 0;
391 }
392 
393 static int
394 div_detach(struct socket *so)
395 {
396 	struct inpcb *inp;
397 
398 	INP_INFO_WLOCK(&divcbinfo);
399 	inp = sotoinpcb(so);
400 	if (inp == 0) {
401 		INP_INFO_WUNLOCK(&divcbinfo);
402 		return EINVAL;
403 	}
404 	INP_LOCK(inp);
405 	in_pcbdetach(inp);
406 	INP_INFO_WUNLOCK(&divcbinfo);
407 	return 0;
408 }
409 
410 static int
411 div_abort(struct socket *so)
412 {
413 	soisdisconnected(so);
414 	return div_detach(so);
415 }
416 
417 static int
418 div_disconnect(struct socket *so)
419 {
420 	if ((so->so_state & SS_ISCONNECTED) == 0)
421 		return ENOTCONN;
422 	return div_abort(so);
423 }
424 
425 static int
426 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
427 {
428 	struct inpcb *inp;
429 	int error;
430 
431 	INP_INFO_WLOCK(&divcbinfo);
432 	inp = sotoinpcb(so);
433 	if (inp == 0) {
434 		INP_INFO_WUNLOCK(&divcbinfo);
435 		return EINVAL;
436 	}
437 	/* in_pcbbind assumes that nam is a sockaddr_in
438 	 * and in_pcbbind requires a valid address. Since divert
439 	 * sockets don't we need to make sure the address is
440 	 * filled in properly.
441 	 * XXX -- divert should not be abusing in_pcbind
442 	 * and should probably have its own family.
443 	 */
444 	if (nam->sa_family != AF_INET)
445 		error = EAFNOSUPPORT;
446 	else {
447 		((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
448 		INP_LOCK(inp);
449 		error = in_pcbbind(inp, nam, td);
450 		INP_UNLOCK(inp);
451 	}
452 	INP_INFO_WUNLOCK(&divcbinfo);
453 	return error;
454 }
455 
456 static int
457 div_shutdown(struct socket *so)
458 {
459 	socantsendmore(so);
460 	return 0;
461 }
462 
463 static int
464 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
465 	 struct mbuf *control, struct thread *td)
466 {
467 	/* Packet must have a header (but that's about it) */
468 	if (m->m_len < sizeof (struct ip) &&
469 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
470 		ipstat.ips_toosmall++;
471 		m_freem(m);
472 		return EINVAL;
473 	}
474 
475 	/* Send packet */
476 	return div_output(so, m, (struct sockaddr_in *)nam, control);
477 }
478 
479 static int
480 div_pcblist(SYSCTL_HANDLER_ARGS)
481 {
482 	int error, i, n;
483 	struct inpcb *inp, **inp_list;
484 	inp_gen_t gencnt;
485 	struct xinpgen xig;
486 
487 	/*
488 	 * The process of preparing the TCB list is too time-consuming and
489 	 * resource-intensive to repeat twice on every request.
490 	 */
491 	if (req->oldptr == 0) {
492 		n = divcbinfo.ipi_count;
493 		req->oldidx = 2 * (sizeof xig)
494 			+ (n + n/8) * sizeof(struct xinpcb);
495 		return 0;
496 	}
497 
498 	if (req->newptr != 0)
499 		return EPERM;
500 
501 	/*
502 	 * OK, now we're committed to doing something.
503 	 */
504 	INP_INFO_RLOCK(&divcbinfo);
505 	gencnt = divcbinfo.ipi_gencnt;
506 	n = divcbinfo.ipi_count;
507 	INP_INFO_RUNLOCK(&divcbinfo);
508 
509 	sysctl_wire_old_buffer(req, 2 * sizeof(xig) + n*sizeof(struct xinpcb));
510 
511 	xig.xig_len = sizeof xig;
512 	xig.xig_count = n;
513 	xig.xig_gen = gencnt;
514 	xig.xig_sogen = so_gencnt;
515 	error = SYSCTL_OUT(req, &xig, sizeof xig);
516 	if (error)
517 		return error;
518 
519 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
520 	if (inp_list == 0)
521 		return ENOMEM;
522 
523 	INP_INFO_RLOCK(&divcbinfo);
524 	for (inp = LIST_FIRST(divcbinfo.listhead), i = 0; inp && i < n;
525 	     inp = LIST_NEXT(inp, inp_list)) {
526 		INP_LOCK(inp);
527 		if (inp->inp_gencnt <= gencnt &&
528 		    cr_canseesocket(req->td->td_ucred, inp->inp_socket) == 0)
529 			inp_list[i++] = inp;
530 		INP_UNLOCK(inp);
531 	}
532 	INP_INFO_RUNLOCK(&divcbinfo);
533 	n = i;
534 
535 	error = 0;
536 	for (i = 0; i < n; i++) {
537 		inp = inp_list[i];
538 		if (inp->inp_gencnt <= gencnt) {
539 			struct xinpcb xi;
540 			xi.xi_len = sizeof xi;
541 			/* XXX should avoid extra copy */
542 			bcopy(inp, &xi.xi_inp, sizeof *inp);
543 			if (inp->inp_socket)
544 				sotoxsocket(inp->inp_socket, &xi.xi_socket);
545 			error = SYSCTL_OUT(req, &xi, sizeof xi);
546 		}
547 	}
548 	if (!error) {
549 		/*
550 		 * Give the user an updated idea of our state.
551 		 * If the generation differs from what we told
552 		 * her before, she knows that something happened
553 		 * while we were processing this request, and it
554 		 * might be necessary to retry.
555 		 */
556 		INP_INFO_RLOCK(&divcbinfo);
557 		xig.xig_gen = divcbinfo.ipi_gencnt;
558 		xig.xig_sogen = so_gencnt;
559 		xig.xig_count = divcbinfo.ipi_count;
560 		INP_INFO_RUNLOCK(&divcbinfo);
561 		error = SYSCTL_OUT(req, &xig, sizeof xig);
562 	}
563 	free(inp_list, M_TEMP);
564 	return error;
565 }
566 
567 /*
568  * This is the wrapper function for in_setsockaddr.  We just pass down
569  * the pcbinfo for in_setpeeraddr to lock.
570  */
571 static int
572 div_sockaddr(struct socket *so, struct sockaddr **nam)
573 {
574 	return (in_setsockaddr(so, nam, &divcbinfo));
575 }
576 
577 /*
578  * This is the wrapper function for in_setpeeraddr. We just pass down
579  * the pcbinfo for in_setpeeraddr to lock.
580  */
581 static int
582 div_peeraddr(struct socket *so, struct sockaddr **nam)
583 {
584 	return (in_setpeeraddr(so, nam, &divcbinfo));
585 }
586 
587 
588 SYSCTL_DECL(_net_inet_divert);
589 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
590 	    div_pcblist, "S,xinpcb", "List of active divert sockets");
591 
592 struct pr_usrreqs div_usrreqs = {
593 	div_abort, pru_accept_notsupp, div_attach, div_bind,
594 	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
595 	div_disconnect, pru_listen_notsupp, div_peeraddr, pru_rcvd_notsupp,
596 	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
597 	div_sockaddr, sosend, soreceive, sopoll
598 };
599