ip_divert.c revision 122331
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 122331 2003-11-08 23:09:42Z sam $
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	m->m_pkthdr.rcvif = NULL;	/* XXX is it necessary ? */
288
289#ifdef MAC
290	mac_create_mbuf_from_socket(so, m);
291#endif
292
293	if (control)
294		m_freem(control);		/* XXX */
295
296	/* Loopback avoidance and state recovery */
297	if (sin) {
298		int i;
299
300		divert_tag.mh_data = (caddr_t)(uintptr_t)sin->sin_port;
301		/*
302		 * Find receive interface with the given name, stuffed
303		 * (if it exists) in the sin_zero[] field.
304		 * The name is user supplied data so don't trust its size
305		 * or that it is zero terminated.
306		 */
307		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
308			;
309		if ( i > 0 && i < sizeof(sin->sin_zero))
310			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
311	}
312
313	/* Reinject packet into the system as incoming or outgoing */
314	if (!sin || sin->sin_addr.s_addr == 0) {
315		struct ip *const ip = mtod(m, struct ip *);
316		struct inpcb *inp;
317
318		INP_INFO_WLOCK(&divcbinfo);
319		inp = sotoinpcb(so);
320		INP_LOCK(inp);
321		/*
322		 * Don't allow both user specified and setsockopt options,
323		 * and don't allow packet length sizes that will crash
324		 */
325		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
326		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
327			error = EINVAL;
328			m_freem(m);
329		} else {
330			/* Convert fields to host order for ip_output() */
331			ip->ip_len = ntohs(ip->ip_len);
332			ip->ip_off = ntohs(ip->ip_off);
333
334			/* Send packet to output processing */
335			ipstat.ips_rawout++;			/* XXX */
336
337			error = ip_output((struct mbuf *)&divert_tag,
338				    inp->inp_options, &inp->inp_route,
339				    (so->so_options & SO_DONTROUTE) |
340				    IP_ALLOWBROADCAST | IP_RAWOUTPUT,
341				    inp->inp_moptions, NULL);
342		}
343		INP_UNLOCK(inp);
344		INP_INFO_WUNLOCK(&divcbinfo);
345	} else {
346		if (m->m_pkthdr.rcvif == NULL) {
347			/*
348			 * No luck with the name, check by IP address.
349			 * Clear the port and the ifname to make sure
350			 * there are no distractions for ifa_ifwithaddr.
351			 */
352			struct	ifaddr *ifa;
353
354			bzero(sin->sin_zero, sizeof(sin->sin_zero));
355			sin->sin_port = 0;
356			ifa = ifa_ifwithaddr((struct sockaddr *) sin);
357			if (ifa == NULL) {
358				error = EADDRNOTAVAIL;
359				goto cantsend;
360			}
361			m->m_pkthdr.rcvif = ifa->ifa_ifp;
362		}
363		/* Send packet to input processing */
364		ip_input((struct mbuf *)&divert_tag);
365	}
366
367	return error;
368
369cantsend:
370	m_freem(m);
371	return error;
372}
373
374static int
375div_attach(struct socket *so, int proto, struct thread *td)
376{
377	struct inpcb *inp;
378	int error;
379
380	INP_INFO_WLOCK(&divcbinfo);
381	inp  = sotoinpcb(so);
382	if (inp != 0) {
383		INP_INFO_WUNLOCK(&divcbinfo);
384		return EINVAL;
385	}
386	if (td && (error = suser(td)) != 0) {
387		INP_INFO_WUNLOCK(&divcbinfo);
388		return error;
389	}
390	error = soreserve(so, div_sendspace, div_recvspace);
391	if (error) {
392		INP_INFO_WUNLOCK(&divcbinfo);
393		return error;
394	}
395	error = in_pcballoc(so, &divcbinfo, td);
396	if (error) {
397		INP_INFO_WUNLOCK(&divcbinfo);
398		return error;
399	}
400	inp = (struct inpcb *)so->so_pcb;
401	INP_LOCK(inp);
402	INP_INFO_WUNLOCK(&divcbinfo);
403	inp->inp_ip_p = proto;
404	inp->inp_vflag |= INP_IPV4;
405	inp->inp_flags |= INP_HDRINCL;
406	/* The socket is always "connected" because
407	   we always know "where" to send the packet */
408	INP_UNLOCK(inp);
409	so->so_state |= SS_ISCONNECTED;
410	return 0;
411}
412
413static int
414div_detach(struct socket *so)
415{
416	struct inpcb *inp;
417
418	INP_INFO_WLOCK(&divcbinfo);
419	inp = sotoinpcb(so);
420	if (inp == 0) {
421		INP_INFO_WUNLOCK(&divcbinfo);
422		return EINVAL;
423	}
424	INP_LOCK(inp);
425	in_pcbdetach(inp);
426	INP_INFO_WUNLOCK(&divcbinfo);
427	return 0;
428}
429
430static int
431div_abort(struct socket *so)
432{
433	struct inpcb *inp;
434
435	INP_INFO_WLOCK(&divcbinfo);
436	inp = sotoinpcb(so);
437	if (inp == 0) {
438		INP_INFO_WUNLOCK(&divcbinfo);
439		return EINVAL;	/* ??? possible? panic instead? */
440	}
441	INP_LOCK(inp);
442	soisdisconnected(so);
443	in_pcbdetach(inp);
444	INP_INFO_WUNLOCK(&divcbinfo);
445	return 0;
446}
447
448static int
449div_disconnect(struct socket *so)
450{
451	if ((so->so_state & SS_ISCONNECTED) == 0)
452		return ENOTCONN;
453	return div_abort(so);
454}
455
456static int
457div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
458{
459	struct inpcb *inp;
460	int error;
461
462	INP_INFO_WLOCK(&divcbinfo);
463	inp = sotoinpcb(so);
464	if (inp == 0) {
465		INP_INFO_WUNLOCK(&divcbinfo);
466		return EINVAL;
467	}
468	/* in_pcbbind assumes that nam is a sockaddr_in
469	 * and in_pcbbind requires a valid address. Since divert
470	 * sockets don't we need to make sure the address is
471	 * filled in properly.
472	 * XXX -- divert should not be abusing in_pcbind
473	 * and should probably have its own family.
474	 */
475	if (nam->sa_family != AF_INET)
476		error = EAFNOSUPPORT;
477	else {
478		((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
479		INP_LOCK(inp);
480		error = in_pcbbind(inp, nam, td);
481		INP_UNLOCK(inp);
482	}
483	INP_INFO_WUNLOCK(&divcbinfo);
484	return error;
485}
486
487static int
488div_shutdown(struct socket *so)
489{
490	struct inpcb *inp;
491
492	INP_INFO_RLOCK(&divcbinfo);
493	inp = sotoinpcb(so);
494	if (inp == 0) {
495		INP_INFO_RUNLOCK(&divcbinfo);
496		return EINVAL;
497	}
498	INP_LOCK(inp);
499	INP_INFO_RUNLOCK(&divcbinfo);
500	socantsendmore(so);
501	INP_UNLOCK(inp);
502	return 0;
503}
504
505static int
506div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
507	 struct mbuf *control, struct thread *td)
508{
509	/* Packet must have a header (but that's about it) */
510	if (m->m_len < sizeof (struct ip) &&
511	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
512		ipstat.ips_toosmall++;
513		m_freem(m);
514		return EINVAL;
515	}
516
517	/* Send packet */
518	return div_output(so, m, (struct sockaddr_in *)nam, control);
519}
520
521void
522div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
523{
524        struct in_addr faddr;
525
526	faddr = ((struct sockaddr_in *)sa)->sin_addr;
527	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
528        	return;
529	if (PRC_IS_REDIRECT(cmd)) {
530		/* flush held routes */
531		in_pcbnotifyall(&divcbinfo, faddr,
532			inetctlerrmap[cmd], in_rtchange);
533	}
534}
535
536static int
537div_pcblist(SYSCTL_HANDLER_ARGS)
538{
539	int error, i, n;
540	struct inpcb *inp, **inp_list;
541	inp_gen_t gencnt;
542	struct xinpgen xig;
543
544	/*
545	 * The process of preparing the TCB list is too time-consuming and
546	 * resource-intensive to repeat twice on every request.
547	 */
548	if (req->oldptr == 0) {
549		n = divcbinfo.ipi_count;
550		req->oldidx = 2 * (sizeof xig)
551			+ (n + n/8) * sizeof(struct xinpcb);
552		return 0;
553	}
554
555	if (req->newptr != 0)
556		return EPERM;
557
558	/*
559	 * OK, now we're committed to doing something.
560	 */
561	INP_INFO_RLOCK(&divcbinfo);
562	gencnt = divcbinfo.ipi_gencnt;
563	n = divcbinfo.ipi_count;
564	INP_INFO_RUNLOCK(&divcbinfo);
565
566	sysctl_wire_old_buffer(req, 2 * sizeof(xig) + n*sizeof(struct xinpcb));
567
568	xig.xig_len = sizeof xig;
569	xig.xig_count = n;
570	xig.xig_gen = gencnt;
571	xig.xig_sogen = so_gencnt;
572	error = SYSCTL_OUT(req, &xig, sizeof xig);
573	if (error)
574		return error;
575
576	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
577	if (inp_list == 0)
578		return ENOMEM;
579
580	INP_INFO_RLOCK(&divcbinfo);
581	for (inp = LIST_FIRST(divcbinfo.listhead), i = 0; inp && i < n;
582	     inp = LIST_NEXT(inp, inp_list)) {
583		INP_LOCK(inp);
584		if (inp->inp_gencnt <= gencnt &&
585		    cr_canseesocket(req->td->td_ucred, inp->inp_socket) == 0)
586			inp_list[i++] = inp;
587		INP_UNLOCK(inp);
588	}
589	INP_INFO_RUNLOCK(&divcbinfo);
590	n = i;
591
592	error = 0;
593	for (i = 0; i < n; i++) {
594		inp = inp_list[i];
595		if (inp->inp_gencnt <= gencnt) {
596			struct xinpcb xi;
597			xi.xi_len = sizeof xi;
598			/* XXX should avoid extra copy */
599			bcopy(inp, &xi.xi_inp, sizeof *inp);
600			if (inp->inp_socket)
601				sotoxsocket(inp->inp_socket, &xi.xi_socket);
602			error = SYSCTL_OUT(req, &xi, sizeof xi);
603		}
604	}
605	if (!error) {
606		/*
607		 * Give the user an updated idea of our state.
608		 * If the generation differs from what we told
609		 * her before, she knows that something happened
610		 * while we were processing this request, and it
611		 * might be necessary to retry.
612		 */
613		INP_INFO_RLOCK(&divcbinfo);
614		xig.xig_gen = divcbinfo.ipi_gencnt;
615		xig.xig_sogen = so_gencnt;
616		xig.xig_count = divcbinfo.ipi_count;
617		INP_INFO_RUNLOCK(&divcbinfo);
618		error = SYSCTL_OUT(req, &xig, sizeof xig);
619	}
620	free(inp_list, M_TEMP);
621	return error;
622}
623
624/*
625 * This is the wrapper function for in_setsockaddr.  We just pass down
626 * the pcbinfo for in_setpeeraddr to lock.
627 */
628static int
629div_sockaddr(struct socket *so, struct sockaddr **nam)
630{
631	return (in_setsockaddr(so, nam, &divcbinfo));
632}
633
634/*
635 * This is the wrapper function for in_setpeeraddr. We just pass down
636 * the pcbinfo for in_setpeeraddr to lock.
637 */
638static int
639div_peeraddr(struct socket *so, struct sockaddr **nam)
640{
641	return (in_setpeeraddr(so, nam, &divcbinfo));
642}
643
644
645SYSCTL_DECL(_net_inet_divert);
646SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
647	    div_pcblist, "S,xinpcb", "List of active divert sockets");
648
649struct pr_usrreqs div_usrreqs = {
650	div_abort, pru_accept_notsupp, div_attach, div_bind,
651	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
652	div_disconnect, pru_listen_notsupp, div_peeraddr, pru_rcvd_notsupp,
653	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
654	div_sockaddr, sosend, soreceive, sopoll
655};
656