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