2 * Copyright (c) 1982, 1986, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
33 * $FreeBSD: src/sys/netinet/ip_divert.c,v 1.42.2.6 2003/01/23 21:06:45 sam Exp $
34 * $DragonFly: src/sys/netinet/ip_divert.c,v 1.39 2008/09/13 08:48:42 sephe Exp $
41 #include "opt_ipdivert.h"
42 #include "opt_ipsec.h"
45 #error "IPDIVERT requires INET."
48 #include <sys/param.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
52 #include <sys/socket.h>
53 #include <sys/protosw.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/systm.h>
58 #include <sys/thread2.h>
59 #include <sys/in_cksum.h>
61 #include <sys/msgport.h>
64 #include <vm/vm_zone.h>
67 #include <net/route.h>
69 #include <net/netmsg2.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/in_pcb.h>
76 #include <netinet/in_var.h>
77 #include <netinet/ip_var.h>
78 #include <netinet/ip_divert.h>
85 * Allocate enough space to hold a full IP packet
87 #define DIVSNDQ (65536 + 100)
88 #define DIVRCVQ (65536 + 100)
90 #define DIV_IS_OUTPUT(sin) ((sin) == NULL || (sin)->sin_addr.s_addr == 0)
92 #define DIV_OUTPUT 0x10000
93 #define DIV_INPUT 0x20000
96 * Divert sockets work in conjunction with ipfw, see the divert(4)
97 * manpage for features.
98 * Internally, packets selected by ipfw in ip_input() or ip_output(),
99 * and never diverted before, are passed to the input queue of the
100 * divert socket with a given 'divert_port' number (as specified in
101 * the matching ipfw rule), and they are tagged with a 16 bit cookie
102 * (representing the rule number of the matching ipfw rule), which
103 * is passed to process reading from the socket.
105 * Packets written to the divert socket are again tagged with a cookie
106 * (usually the same as above) and a destination address.
107 * If the destination address is INADDR_ANY then the packet is
108 * treated as outgoing and sent to ip_output(), otherwise it is
109 * treated as incoming and sent to ip_input().
110 * In both cases, the packet is tagged with the cookie.
112 * On reinjection, processing in ip_input() and ip_output()
113 * will be exactly the same as for the original packet, except that
114 * ipfw processing will start at the rule number after the one
115 * written in the cookie (so, tagging a packet with a cookie of 0
116 * will cause it to be effectively considered as a standard packet).
119 /* Internal variables */
120 static struct inpcbinfo divcbinfo;
122 static u_long div_sendspace = DIVSNDQ; /* XXX sysctl ? */
123 static u_long div_recvspace = DIVRCVQ; /* XXX sysctl ? */
125 static struct mbuf *ip_divert(struct mbuf *, int, int);
128 * Initialize divert connection block queue.
133 in_pcbinfo_init(&divcbinfo);
135 * XXX We don't use the hash list for divert IP, but it's easier
136 * to allocate a one entry hash list than it is to check all
137 * over the place for hashbase == NULL.
139 divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
140 divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
141 divcbinfo.wildcardhashbase = hashinit(1, M_PCB,
142 &divcbinfo.wildcardhashmask);
143 divcbinfo.ipi_zone = zinit("divcb", sizeof(struct inpcb),
144 maxsockets, ZONE_INTERRUPT, 0);
145 ip_divert_p = ip_divert;
149 * IPPROTO_DIVERT is not a real IP protocol; don't allow any packets
150 * with that protocol number to enter the system from the outside.
153 div_input(struct mbuf *m, ...)
155 ipstat.ips_noproto++;
160 div_soport(struct socket *so, struct sockaddr *nam,
161 struct mbuf **mptr, int req)
163 struct sockaddr_in *sin;
167 /* Except for send(), everything happens on CPU0 */
169 return cpu0_soport(so, nam, mptr, req);
171 sin = (struct sockaddr_in *)nam;
175 m->m_pkthdr.rcvif = NULL;
176 dir = DIV_IS_OUTPUT(sin) ? IP_MPORT_OUT : IP_MPORT_IN;
182 * Try locating the interface, if we originally had one.
183 * This is done even for outgoing packets, since for a
184 * forwarded packet, there must be an interface attached.
186 * Find receive interface with the given name, stuffed
187 * (if it exists) in the sin_zero[] field.
188 * The name is user supplied data so don't trust its size
189 * or that it is zero terminated.
191 for (i = 0; sin->sin_zero[i] && i < sizeof(sin->sin_zero); i++)
193 if (i > 0 && i < sizeof(sin->sin_zero))
194 m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
197 if (dir == IP_MPORT_IN && m->m_pkthdr.rcvif == NULL) {
199 * No luck with the name, check by IP address.
200 * Clear the port and the ifname to make sure
201 * there are no distractions for ifa_ifwithaddr.
203 * Be careful not to trash sin->sin_port; it will
204 * be used later in div_output().
209 bzero(sin->sin_zero, sizeof(sin->sin_zero));
210 sin_port = sin->sin_port; /* save */
212 ifa = ifa_ifwithaddr((struct sockaddr *)sin);
218 sin->sin_port = sin_port; /* restore */
219 m->m_pkthdr.rcvif = ifa->ifa_ifp;
222 return ip_mport(mptr, dir);
226 * Divert a packet by passing it up to the divert socket at port 'port'.
228 * Setup generic address and protocol structures for div_input routine,
229 * then pass them along with mbuf chain.
232 div_packet(struct mbuf *m, int incoming, int port)
234 struct sockaddr_in divsrc = { sizeof divsrc, AF_INET };
238 struct divert_info *divinfo;
241 /* Locate the divert info */
242 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
243 divinfo = m_tag_data(mtag);
244 divsrc.sin_port = divinfo->skipto;
247 * Record receive interface address, if any.
248 * But only for incoming packets.
250 divsrc.sin_addr.s_addr = 0;
252 struct ifaddr_container *ifac;
254 /* Find IP address for receive interface */
255 TAILQ_FOREACH(ifac, &m->m_pkthdr.rcvif->if_addrheads[mycpuid],
257 struct ifaddr *ifa = ifac->ifa;
259 if (ifa->ifa_addr == NULL)
261 if (ifa->ifa_addr->sa_family != AF_INET)
264 ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
269 * Record the incoming interface name whenever we have one.
271 if (m->m_pkthdr.rcvif) {
273 * Hide the actual interface name in there in the
274 * sin_zero array. XXX This needs to be moved to a
275 * different sockaddr type for divert, e.g.
276 * sockaddr_div with multiple fields like
277 * sockaddr_dl. Presently we have only 7 bytes
278 * but that will do for now as most interfaces
279 * are 4 or less + 2 or less bytes for unit.
280 * There is probably a faster way of doing this,
281 * possibly taking it from the sockaddr_dl on the iface.
282 * This solves the problem of a P2P link and a LAN interface
283 * having the same address, which can result in the wrong
284 * interface being assigned to the packet when fed back
285 * into the divert socket. Theoretically if the daemon saves
286 * and re-uses the sockaddr_in as suggested in the man pages,
287 * this iface name will come along for the ride.
288 * (see div_output for the other half of this.)
290 ksnprintf(divsrc.sin_zero, sizeof divsrc.sin_zero,
291 m->m_pkthdr.rcvif->if_xname);
294 /* Put packet on socket queue, if any */
296 nport = htons((u_int16_t)port);
297 LIST_FOREACH(inp, &divcbinfo.pcblisthead, inp_list) {
298 if (inp->inp_flags & INP_PLACEMARKER)
300 if (inp->inp_lport == nport)
301 sa = inp->inp_socket;
304 if (ssb_appendaddr(&sa->so_rcv, (struct sockaddr *)&divsrc, m,
305 (struct mbuf *)NULL) == 0)
311 ipstat.ips_noproto++;
312 ipstat.ips_delivered--;
318 div_packet_handler(struct netmsg *nmsg)
320 struct netmsg_packet *nmp;
321 struct lwkt_msg *msg;
323 int port, incoming = 0;
325 nmp = (struct netmsg_packet *)nmsg;
328 msg = &nmsg->nm_lmsg;
329 port = msg->u.ms_result32 & 0xffff;
330 if (msg->u.ms_result32 & DIV_INPUT)
333 div_packet(m, incoming, port);
338 divert_packet(struct mbuf *m, int incoming)
341 struct divert_info *divinfo;
347 if (m->m_len < sizeof(struct ip) &&
348 (m = m_pullup(m, sizeof(struct ip))) == NULL)
351 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
352 KASSERT(mtag != NULL, ("%s no divert tag!", __func__));
353 divinfo = m_tag_data(mtag);
355 port = divinfo->port;
356 KASSERT(port != 0, ("%s: port=0", __func__));
360 struct netmsg_packet *nmp;
361 struct lwkt_msg *msg;
363 nmp = &m->m_hdr.mh_netmsg;
364 netmsg_init(&nmp->nm_netmsg, &netisr_apanic_rport, 0,
368 msg = &nmp->nm_netmsg.nm_lmsg;
369 msg->u.ms_result32 = port; /* port is 16bits */
371 msg->u.ms_result32 |= DIV_INPUT;
373 msg->u.ms_result32 |= DIV_OUTPUT;
375 lwkt_sendmsg(cpu_portfn(0), &nmp->nm_netmsg.nm_lmsg);
378 div_packet(m, incoming, port);
382 * Deliver packet back into the IP processing machinery.
384 * If no address specified, or address is 0.0.0.0, send to ip_output();
385 * otherwise, send to ip_input() and mark as having been received on
386 * the interface with that address.
389 div_output(struct socket *so, struct mbuf *m,
390 struct sockaddr_in *sin, struct mbuf *control)
394 struct divert_info *divinfo;
397 m_freem(control); /* XXX */
400 * Prepare the tag for divert info. Note that a packet
401 * with a 0 tag in mh_data is effectively untagged,
402 * so we could optimize that case.
404 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT, sizeof(*divinfo), MB_DONTWAIT);
409 m_tag_prepend(m, mtag);
411 /* Loopback avoidance and state recovery */
412 divinfo = m_tag_data(mtag);
414 divinfo->skipto = sin->sin_port;
418 /* Reinject packet into the system as incoming or outgoing */
419 if (DIV_IS_OUTPUT(sin)) {
420 struct ip *const ip = mtod(m, struct ip *);
422 /* Don't allow packet length sizes that will crash */
423 if ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len) {
428 /* Convert fields to host order for ip_output() */
429 ip->ip_len = ntohs(ip->ip_len);
430 ip->ip_off = ntohs(ip->ip_off);
432 /* Send packet to output processing */
433 ipstat.ips_rawout++; /* XXX */
434 error = ip_output(m, NULL, NULL,
435 (so->so_options & SO_DONTROUTE) |
436 IP_ALLOWBROADCAST | IP_RAWOUTPUT,
449 div_attach(struct socket *so, int proto, struct pru_attach_info *ai)
457 if ((error = suser_cred(ai->p_ucred, NULL_CRED_OKAY)) != 0)
460 error = soreserve(so, div_sendspace, div_recvspace, ai->sb_rlimit);
463 error = in_pcballoc(so, &divcbinfo);
466 inp = (struct inpcb *)so->so_pcb;
467 inp->inp_ip_p = proto;
468 inp->inp_vflag |= INP_IPV4;
469 inp->inp_flags |= INP_HDRINCL;
471 * The socket is always "connected" because
472 * we always know "where" to send the packet.
474 so->so_state |= SS_ISCONNECTED;
479 div_detach(struct socket *so)
491 div_abort(struct socket *so)
493 soisdisconnected(so);
494 return div_detach(so);
498 div_disconnect(struct socket *so)
500 if (!(so->so_state & SS_ISCONNECTED))
502 return div_abort(so);
506 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
511 * in_pcbbind assumes that nam is a sockaddr_in
512 * and in_pcbbind requires a valid address. Since divert
513 * sockets don't we need to make sure the address is
514 * filled in properly.
515 * XXX -- divert should not be abusing in_pcbind
516 * and should probably have its own family.
518 if (nam->sa_family != AF_INET) {
519 error = EAFNOSUPPORT;
521 ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
522 error = in_pcbbind(so->so_pcb, nam, td);
528 div_shutdown(struct socket *so)
535 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
536 struct mbuf *control, struct thread *td)
538 /* Length check already done in ip_mport() */
539 KASSERT(m->m_len >= sizeof(struct ip), ("IP header not in one mbuf"));
542 return div_output(so, m, (struct sockaddr_in *)nam, control);
545 SYSCTL_DECL(_net_inet_divert);
546 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, &divcbinfo, 0,
547 in_pcblist_global, "S,xinpcb", "List of active divert sockets");
549 struct pr_usrreqs div_usrreqs = {
550 .pru_abort = div_abort,
551 .pru_accept = pru_accept_notsupp,
552 .pru_attach = div_attach,
553 .pru_bind = div_bind,
554 .pru_connect = pru_connect_notsupp,
555 .pru_connect2 = pru_connect2_notsupp,
556 .pru_control = in_control,
557 .pru_detach = div_detach,
558 .pru_disconnect = div_disconnect,
559 .pru_listen = pru_listen_notsupp,
560 .pru_peeraddr = in_setpeeraddr,
561 .pru_rcvd = pru_rcvd_notsupp,
562 .pru_rcvoob = pru_rcvoob_notsupp,
563 .pru_send = div_send,
564 .pru_sense = pru_sense_null,
565 .pru_shutdown = div_shutdown,
566 .pru_sockaddr = in_setsockaddr,
567 .pru_sosend = sosend,
568 .pru_soreceive = soreceive,
573 ip_divert_out(struct mbuf *m, int tee)
575 struct mbuf *clone = NULL;
576 struct ip *ip = mtod(m, struct ip *);
578 /* Clone packet if we're doing a 'tee' */
580 clone = m_dup(m, MB_DONTWAIT);
584 * delayed checksums are not currently compatible
585 * with divert sockets.
587 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
589 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
592 /* Restore packet header fields to original values */
593 ip->ip_len = htons(ip->ip_len);
594 ip->ip_off = htons(ip->ip_off);
596 /* Deliver packet to divert input routine */
599 /* If 'tee', continue with original packet */
604 ip_divert_in(struct mbuf *m, int tee)
606 struct mbuf *clone = NULL;
607 struct ip *ip = mtod(m, struct ip *);
610 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
611 const struct divert_info *divinfo;
616 * Only trust divert info in the fragment
619 frag_off = ip->ip_off << 3;
621 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
622 m_tag_delete(m, mtag);
626 * Attempt reassembly; if it succeeds, proceed.
627 * ip_reass() will return a different mbuf.
632 ip = mtod(m, struct ip *);
634 /* Caller need to redispatch the packet, if it is for us */
635 m->m_pkthdr.fw_flags |= FW_MBUF_REDISPATCH;
638 * Get the header length of the reassembled
641 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
644 * Restore original checksum before diverting
648 ip->ip_len = htons(ip->ip_len);
649 ip->ip_off = htons(ip->ip_off);
651 if (hlen == sizeof(struct ip))
652 ip->ip_sum = in_cksum_hdr(ip);
654 ip->ip_sum = in_cksum(m, hlen);
655 ip->ip_off = ntohs(ip->ip_off);
656 ip->ip_len = ntohs(ip->ip_len);
659 * Only use the saved divert info
661 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
663 /* Wrongly configured ipfw */
664 kprintf("ip_input no divert info\n");
668 divinfo = m_tag_data(mtag);
673 * Divert or tee packet to the divert protocol if
677 /* Clone packet if we're doing a 'tee' */
679 clone = m_dup(m, MB_DONTWAIT);
682 * Restore packet header fields to original
685 ip->ip_len = htons(ip->ip_len);
686 ip->ip_off = htons(ip->ip_off);
688 /* Deliver packet to divert input routine */
691 /* Catch invalid reference */
695 ipstat.ips_delivered++;
697 /* If 'tee', continue with original packet */
700 * Complete processing of the packet.
701 * XXX Better safe than sorry, remove the DIVERT tag.
703 mtag = m_tag_find(clone, PACKET_TAG_IPFW_DIVERT, NULL);
704 KKASSERT(mtag != NULL);
705 m_tag_delete(clone, mtag);
711 ip_divert(struct mbuf *m, int tee, int incoming)
716 ret = ip_divert_in(m, tee);
718 ret = ip_divert_out(m, tee);