ip_divert.c revision 54175
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 54175 1999-12-06 00:43:07Z archie $
34 */
35
36#include "opt_inet.h"
37#include "opt_ipfw.h"
38#include "opt_ipdivert.h"
39
40#ifndef INET
41#error "IPDIVERT requires INET."
42#endif
43
44#include <sys/param.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>
47#include <sys/socket.h>
48#include <sys/protosw.h>
49#include <sys/socketvar.h>
50#include <sys/systm.h>
51#include <sys/proc.h>
52
53#include <vm/vm_zone.h>
54
55#include <net/if.h>
56#include <net/route.h>
57
58#include <netinet/in.h>
59#include <netinet/in_systm.h>
60#include <netinet/ip.h>
61#include <netinet/in_pcb.h>
62#include <netinet/in_var.h>
63#include <netinet/ip_var.h>
64
65/*
66 * Divert sockets
67 */
68
69/*
70 * Allocate enough space to hold a full IP packet
71 */
72#define	DIVSNDQ		(65536 + 100)
73#define	DIVRCVQ		(65536 + 100)
74
75/*
76 * A 16 bit cookie is passed to and from the user process.
77 * The user process can send it back to help the caller know
78 * something about where the packet originally came from.
79 *
80 * In the case of ipfw, then the cookie is the rule that sent
81 * us here. On reinjection is is the rule after which processing
82 * should continue. Leaving it the same will make processing start
83 * at the rule number after that which sent it here. Setting it to
84 * 0 will restart processing at the beginning.
85 *
86 * For divert_packet(), ip_divert_cookie is an input value only.
87 * For div_output(), ip_divert_cookie is an output value only.
88 */
89u_int16_t ip_divert_cookie;
90
91/* Internal variables */
92static struct inpcbhead divcb;
93static struct inpcbinfo divcbinfo;
94
95static u_long	div_sendspace = DIVSNDQ;	/* XXX sysctl ? */
96static u_long	div_recvspace = DIVRCVQ;	/* XXX sysctl ? */
97
98/* Optimization: have this preinitialized */
99static struct sockaddr_in divsrc = { sizeof(divsrc), AF_INET };
100
101/* Internal functions */
102static int div_output(struct socket *so,
103		struct mbuf *m, struct sockaddr *addr, struct mbuf *control);
104
105/*
106 * Initialize divert connection block queue.
107 */
108void
109div_init(void)
110{
111	LIST_INIT(&divcb);
112	divcbinfo.listhead = &divcb;
113	/*
114	 * XXX We don't use the hash list for divert IP, but it's easier
115	 * to allocate a one entry hash list than it is to check all
116	 * over the place for hashbase == NULL.
117	 */
118	divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
119	divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
120	divcbinfo.ipi_zone = zinit("divcb", sizeof(struct inpcb),
121				   maxsockets, ZONE_INTERRUPT, 0);
122}
123
124/*
125 * IPPROTO_DIVERT is not a real IP protocol; don't allow any packets
126 * with that protocol number to enter the system from the outside.
127 */
128void
129div_input(struct mbuf *m, int hlen)
130{
131	ipstat.ips_noproto++;
132	m_freem(m);
133}
134
135/*
136 * Divert a packet by passing it up to the divert socket at port 'port'.
137 *
138 * Setup generic address and protocol structures for div_input routine,
139 * then pass them along with mbuf chain.
140 */
141void
142divert_packet(struct mbuf *m, int incoming, int port)
143{
144	struct ip *ip;
145	struct inpcb *inp;
146	struct socket *sa;
147	u_int16_t nport;
148
149	/* Sanity check */
150	KASSERT(port != 0, ("%s: port=0", __FUNCTION__));
151
152	/* Record and reset divert cookie */
153	divsrc.sin_port = ip_divert_cookie;
154	ip_divert_cookie = 0;
155
156	/* Assure header */
157	if (m->m_len < sizeof(struct ip) &&
158	    (m = m_pullup(m, sizeof(struct ip))) == 0) {
159		return;
160	}
161	ip = mtod(m, struct ip *);
162
163	/*
164	 * Record receive interface address, if any.
165	 * But only for incoming packets.
166	 */
167	divsrc.sin_addr.s_addr = 0;
168	if (incoming) {
169		struct ifaddr *ifa;
170
171		/* Sanity check */
172		KASSERT((m->m_flags & M_PKTHDR), ("%s: !PKTHDR", __FUNCTION__));
173
174		/* Find IP address for receive interface */
175		for (ifa = m->m_pkthdr.rcvif->if_addrhead.tqh_first;
176		    ifa != NULL; ifa = ifa->ifa_link.tqe_next) {
177			if (ifa->ifa_addr == NULL)
178				continue;
179			if (ifa->ifa_addr->sa_family != AF_INET)
180				continue;
181			divsrc.sin_addr =
182			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
183			break;
184		}
185	}
186	/*
187	 * Record the incoming interface name whenever we have one.
188	 */
189	bzero(&divsrc.sin_zero, sizeof(divsrc.sin_zero));
190	if (m->m_pkthdr.rcvif) {
191		/*
192		 * Hide the actual interface name in there in the
193		 * sin_zero array. XXX This needs to be moved to a
194		 * different sockaddr type for divert, e.g.
195		 * sockaddr_div with multiple fields like
196		 * sockaddr_dl. Presently we have only 7 bytes
197		 * but that will do for now as most interfaces
198		 * are 4 or less + 2 or less bytes for unit.
199		 * There is probably a faster way of doing this,
200		 * possibly taking it from the sockaddr_dl on the iface.
201		 * This solves the problem of a P2P link and a LAN interface
202		 * having the same address, which can result in the wrong
203		 * interface being assigned to the packet when fed back
204		 * into the divert socket. Theoretically if the daemon saves
205		 * and re-uses the sockaddr_in as suggested in the man pages,
206		 * this iface name will come along for the ride.
207		 * (see div_output for the other half of this.)
208		 */
209		snprintf(divsrc.sin_zero, sizeof(divsrc.sin_zero),
210			"%s%d", m->m_pkthdr.rcvif->if_name,
211			m->m_pkthdr.rcvif->if_unit);
212	}
213
214	/* Put packet on socket queue, if any */
215	sa = NULL;
216	nport = htons((u_int16_t)port);
217	for (inp = divcb.lh_first; inp != NULL; inp = inp->inp_list.le_next) {
218		if (inp->inp_lport == nport)
219			sa = inp->inp_socket;
220	}
221	if (sa) {
222		if (sbappendaddr(&sa->so_rcv, (struct sockaddr *)&divsrc,
223				m, (struct mbuf *)0) == 0)
224			m_freem(m);
225		else
226			sorwakeup(sa);
227	} else {
228		m_freem(m);
229		ipstat.ips_noproto++;
230		ipstat.ips_delivered--;
231        }
232}
233
234/*
235 * Deliver packet back into the IP processing machinery.
236 *
237 * If no address specified, or address is 0.0.0.0, send to ip_output();
238 * otherwise, send to ip_input() and mark as having been received on
239 * the interface with that address.
240 */
241static int
242div_output(so, m, addr, control)
243	struct socket *so;
244	register struct mbuf *m;
245	struct sockaddr *addr;
246	struct mbuf *control;
247{
248	register struct inpcb *const inp = sotoinpcb(so);
249	register struct ip *const ip = mtod(m, struct ip *);
250	struct sockaddr_in *sin = (struct sockaddr_in *)addr;
251	int error = 0;
252
253	if (control)
254		m_freem(control);		/* XXX */
255
256	/* Loopback avoidance and state recovery */
257	if (sin) {
258		int	len = 0;
259		char	*c = sin->sin_zero;
260
261		ip_divert_cookie = sin->sin_port;
262
263		/*
264		 * Find receive interface with the given name or IP address.
265		 * The name is user supplied data so don't trust it's size or
266		 * that it is zero terminated. The name has priority.
267		 * We are presently assuming that the sockaddr_in
268		 * has not been replaced by a sockaddr_div, so we limit it
269		 * to 16 bytes in total. the name is stuffed (if it exists)
270		 * in the sin_zero[] field.
271		 */
272		while (*c++ && (len++ < sizeof(sin->sin_zero)));
273		if ((len > 0) && (len < sizeof(sin->sin_zero)))
274			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
275	} else {
276		ip_divert_cookie = 0;
277	}
278
279	/* Reinject packet into the system as incoming or outgoing */
280	if (!sin || sin->sin_addr.s_addr == 0) {
281		/*
282		 * Don't allow both user specified and setsockopt options,
283		 * and don't allow packet length sizes that will crash
284		 */
285		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
286		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
287			error = EINVAL;
288			goto cantsend;
289		}
290
291		/* Convert fields to host order for ip_output() */
292		NTOHS(ip->ip_len);
293		NTOHS(ip->ip_off);
294
295		/* Send packet to output processing */
296		ipstat.ips_rawout++;			/* XXX */
297		error = ip_output(m, inp->inp_options, &inp->inp_route,
298			(so->so_options & SO_DONTROUTE) |
299			IP_ALLOWBROADCAST | IP_RAWOUTPUT, inp->inp_moptions);
300	} else {
301		struct	ifaddr *ifa;
302
303		/* If no luck with the name above. check by IP address.  */
304		if (m->m_pkthdr.rcvif == NULL) {
305			/*
306			 * Make sure there are no distractions
307			 * for ifa_ifwithaddr. Clear the port and the ifname.
308			 * Maybe zap all 8 bytes at once using a 64bit write?
309			 */
310			bzero(sin->sin_zero, sizeof(sin->sin_zero));
311			/* *((u_int64_t *)sin->sin_zero) = 0; */ /* XXX ?? */
312			sin->sin_port = 0;
313			if (!(ifa = ifa_ifwithaddr((struct sockaddr *) sin))) {
314				error = EADDRNOTAVAIL;
315				goto cantsend;
316			}
317			m->m_pkthdr.rcvif = ifa->ifa_ifp;
318		}
319
320		/* Send packet to input processing */
321		ip_input(m);
322	}
323
324	/* paranoid: Reset for next time (and other packets) */
325	/* almost definitly already done in the ipfw filter but.. */
326	ip_divert_cookie = 0;
327	return error;
328
329cantsend:
330	m_freem(m);
331	ip_divert_cookie = 0;
332	return error;
333}
334
335static int
336div_attach(struct socket *so, int proto, struct proc *p)
337{
338	struct inpcb *inp;
339	int error, s;
340
341	inp  = sotoinpcb(so);
342	if (inp)
343		panic("div_attach");
344	if (p && (error = suser(p)) != 0)
345		return error;
346
347	s = splnet();
348	error = in_pcballoc(so, &divcbinfo, p);
349	splx(s);
350	if (error)
351		return error;
352	error = soreserve(so, div_sendspace, div_recvspace);
353	if (error)
354		return error;
355	inp = (struct inpcb *)so->so_pcb;
356	inp->inp_ip_p = proto;
357	inp->inp_flags |= INP_HDRINCL;
358	/* The socket is always "connected" because
359	   we always know "where" to send the packet */
360	so->so_state |= SS_ISCONNECTED;
361	return 0;
362}
363
364static int
365div_detach(struct socket *so)
366{
367	struct inpcb *inp;
368
369	inp = sotoinpcb(so);
370	if (inp == 0)
371		panic("div_detach");
372	in_pcbdetach(inp);
373	return 0;
374}
375
376static int
377div_abort(struct socket *so)
378{
379	soisdisconnected(so);
380	return div_detach(so);
381}
382
383static int
384div_disconnect(struct socket *so)
385{
386	if ((so->so_state & SS_ISCONNECTED) == 0)
387		return ENOTCONN;
388	return div_abort(so);
389}
390
391static int
392div_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
393{
394	struct inpcb *inp;
395	int s;
396	int error;
397
398	s = splnet();
399	inp = sotoinpcb(so);
400	error = in_pcbbind(inp, nam, p);
401	splx(s);
402	return 0;
403}
404
405static int
406div_shutdown(struct socket *so)
407{
408	socantsendmore(so);
409	return 0;
410}
411
412static int
413div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
414	 struct mbuf *control, struct proc *p)
415{
416	/* Packet must have a header (but that's about it) */
417	if (m->m_len < sizeof (struct ip) ||
418	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
419		ipstat.ips_toosmall++;
420		m_freem(m);
421		return EINVAL;
422	}
423
424	/* Send packet */
425	return div_output(so, m, nam, control);
426}
427
428struct pr_usrreqs div_usrreqs = {
429	div_abort, pru_accept_notsupp, div_attach, div_bind,
430	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
431	div_disconnect, pru_listen_notsupp, in_setpeeraddr, pru_rcvd_notsupp,
432	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
433	in_setsockaddr, sosend, soreceive, sopoll
434};
435