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