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 * 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.
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
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #if !defined(KLD_MODULE)
38 #error "IPDIVERT requires INET."
41 #error "IPDIVERT requires IPFIREWALL"
45 #include <sys/param.h>
46 #include <sys/kernel.h>
48 #include <sys/malloc.h>
50 #include <sys/module.h>
51 #include <sys/kernel.h>
54 #include <sys/protosw.h>
55 #include <sys/rwlock.h>
56 #include <sys/signalvar.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/systm.h>
66 #include <net/netisr.h>
67 #include <net/route.h>
70 #include <netinet/in.h>
71 #include <netinet/in_pcb.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/in_var.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_divert.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_fw.h>
79 #include <netinet/sctp_crc32.h>
82 #include <security/mac/mac_framework.h>
89 * Allocate enough space to hold a full IP packet
91 #define DIVSNDQ (65536 + 100)
92 #define DIVRCVQ (65536 + 100)
95 * Divert sockets work in conjunction with ipfw, see the divert(4)
96 * manpage for features.
97 * Internally, packets selected by ipfw in ip_input() or ip_output(),
98 * and never diverted before, are passed to the input queue of the
99 * divert socket with a given 'divert_port' number (as specified in
100 * the matching ipfw rule), and they are tagged with a 16 bit cookie
101 * (representing the rule number of the matching ipfw rule), which
102 * is passed to process reading from the socket.
104 * Packets written to the divert socket are again tagged with a cookie
105 * (usually the same as above) and a destination address.
106 * If the destination address is INADDR_ANY then the packet is
107 * treated as outgoing and sent to ip_output(), otherwise it is
108 * treated as incoming and sent to ip_input().
109 * In both cases, the packet is tagged with the cookie.
111 * On reinjection, processing in ip_input() and ip_output()
112 * will be exactly the same as for the original packet, except that
113 * ipfw processing will start at the rule number after the one
114 * written in the cookie (so, tagging a packet with a cookie of 0
115 * will cause it to be effectively considered as a standard packet).
118 /* Internal variables. */
119 static VNET_DEFINE(struct inpcbhead, divcb);
120 static VNET_DEFINE(struct inpcbinfo, divcbinfo);
122 #define V_divcb VNET(divcb)
123 #define V_divcbinfo VNET(divcbinfo)
125 static u_long div_sendspace = DIVSNDQ; /* XXX sysctl ? */
126 static u_long div_recvspace = DIVRCVQ; /* XXX sysctl ? */
128 static eventhandler_tag ip_divert_event_tag;
131 * Initialize divert connection block queue.
134 div_zone_change(void *tag)
137 uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
141 div_inpcb_init(void *mem, int size, int flags)
143 struct inpcb *inp = mem;
145 INP_LOCK_INIT(inp, "inp", "divinp");
150 div_inpcb_fini(void *mem, int size)
152 struct inpcb *inp = mem;
154 INP_LOCK_DESTROY(inp);
161 INP_INFO_LOCK_INIT(&V_divcbinfo, "div");
163 V_divcbinfo.ipi_listhead = &V_divcb;
165 V_divcbinfo.ipi_vnet = curvnet;
168 * XXX We don't use the hash list for divert IP, but it's easier
169 * to allocate a one entry hash list than it is to check all
170 * over the place for hashbase == NULL.
172 V_divcbinfo.ipi_hashbase = hashinit(1, M_PCB, &V_divcbinfo.ipi_hashmask);
173 V_divcbinfo.ipi_porthashbase = hashinit(1, M_PCB,
174 &V_divcbinfo.ipi_porthashmask);
175 V_divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
176 NULL, NULL, div_inpcb_init, div_inpcb_fini, UMA_ALIGN_PTR,
178 uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
185 INP_INFO_LOCK_DESTROY(&V_divcbinfo);
186 uma_zdestroy(V_divcbinfo.ipi_zone);
187 hashdestroy(V_divcbinfo.ipi_hashbase, M_PCB, V_divcbinfo.ipi_hashmask);
188 hashdestroy(V_divcbinfo.ipi_porthashbase, M_PCB,
189 V_divcbinfo.ipi_porthashmask);
193 * IPPROTO_DIVERT is not in the real IP protocol number space; this
194 * function should never be called. Just in case, drop any packets.
197 div_input(struct mbuf *m, int off)
200 KMOD_IPSTAT_INC(ips_noproto);
205 * Divert a packet by passing it up to the divert socket at port 'port'.
207 * Setup generic address and protocol structures for div_input routine,
208 * then pass them along with mbuf chain.
211 divert_packet(struct mbuf *m, int incoming)
217 struct sockaddr_in divsrc;
220 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
222 printf("%s: no divert tag\n", __func__);
227 if (m->m_len < sizeof(struct ip) &&
228 (m = m_pullup(m, sizeof(struct ip))) == 0)
230 ip = mtod(m, struct ip *);
232 /* Delayed checksums are currently not compatible with divert. */
233 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
234 ip->ip_len = ntohs(ip->ip_len);
236 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
237 ip->ip_len = htons(ip->ip_len);
240 if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
241 ip->ip_len = ntohs(ip->ip_len);
242 sctp_delayed_cksum(m);
243 m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
244 ip->ip_len = htons(ip->ip_len);
248 * Record receive interface address, if any.
249 * But only for incoming packets.
251 bzero(&divsrc, sizeof(divsrc));
252 divsrc.sin_len = sizeof(divsrc);
253 divsrc.sin_family = AF_INET;
254 divsrc.sin_port = divert_cookie(mtag); /* record matching rule */
262 /* Find IP address for receive interface */
263 ifp = m->m_pkthdr.rcvif;
265 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
266 if (ifa->ifa_addr->sa_family != AF_INET)
269 ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
272 if_addr_runlock(ifp);
275 * Record the incoming interface name whenever we have one.
277 if (m->m_pkthdr.rcvif) {
279 * Hide the actual interface name in there in the
280 * sin_zero array. XXX This needs to be moved to a
281 * different sockaddr type for divert, e.g.
282 * sockaddr_div with multiple fields like
283 * sockaddr_dl. Presently we have only 7 bytes
284 * but that will do for now as most interfaces
285 * are 4 or less + 2 or less bytes for unit.
286 * There is probably a faster way of doing this,
287 * possibly taking it from the sockaddr_dl on the iface.
288 * This solves the problem of a P2P link and a LAN interface
289 * having the same address, which can result in the wrong
290 * interface being assigned to the packet when fed back
291 * into the divert socket. Theoretically if the daemon saves
292 * and re-uses the sockaddr_in as suggested in the man pages,
293 * this iface name will come along for the ride.
294 * (see div_output for the other half of this.)
296 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
297 sizeof(divsrc.sin_zero));
300 /* Put packet on socket queue, if any */
302 nport = htons((u_int16_t)divert_info(mtag));
303 INP_INFO_RLOCK(&V_divcbinfo);
304 LIST_FOREACH(inp, &V_divcb, inp_list) {
305 /* XXX why does only one socket match? */
306 if (inp->inp_lport == nport) {
308 sa = inp->inp_socket;
309 SOCKBUF_LOCK(&sa->so_rcv);
310 if (sbappendaddr_locked(&sa->so_rcv,
311 (struct sockaddr *)&divsrc, m,
312 (struct mbuf *)0) == 0) {
313 SOCKBUF_UNLOCK(&sa->so_rcv);
314 sa = NULL; /* force mbuf reclaim below */
316 sorwakeup_locked(sa);
321 INP_INFO_RUNLOCK(&V_divcbinfo);
324 KMOD_IPSTAT_INC(ips_noproto);
325 KMOD_IPSTAT_DEC(ips_delivered);
330 * Deliver packet back into the IP processing machinery.
332 * If no address specified, or address is 0.0.0.0, send to ip_output();
333 * otherwise, send to ip_input() and mark as having been received on
334 * the interface with that address.
337 div_output(struct socket *so, struct mbuf *m, struct sockaddr_in *sin,
338 struct mbuf *control)
341 struct divert_tag *dt;
343 struct mbuf *options;
346 * An mbuf may hasn't come from userland, but we pretend
349 m->m_pkthdr.rcvif = NULL;
351 M_SETFIB(m, so->so_fibnum);
354 m_freem(control); /* XXX */
356 if ((mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL)) == NULL) {
357 mtag = m_tag_get(PACKET_TAG_DIVERT, sizeof(struct divert_tag),
363 dt = (struct divert_tag *)(mtag+1);
364 m_tag_prepend(m, mtag);
366 dt = (struct divert_tag *)(mtag+1);
368 /* Loopback avoidance and state recovery */
372 dt->cookie = sin->sin_port;
374 * Find receive interface with the given name, stuffed
375 * (if it exists) in the sin_zero[] field.
376 * The name is user supplied data so don't trust its size
377 * or that it is zero terminated.
379 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
381 if ( i > 0 && i < sizeof(sin->sin_zero))
382 m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
385 /* Reinject packet into the system as incoming or outgoing */
386 if (!sin || sin->sin_addr.s_addr == 0) {
387 struct ip *const ip = mtod(m, struct ip *);
390 dt->info |= IP_FW_DIVERT_OUTPUT_FLAG;
391 INP_INFO_WLOCK(&V_divcbinfo);
395 * Don't allow both user specified and setsockopt options,
396 * and don't allow packet length sizes that will crash
398 if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
399 ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
402 INP_INFO_WUNLOCK(&V_divcbinfo);
405 /* Convert fields to host order for ip_output() */
406 ip->ip_len = ntohs(ip->ip_len);
407 ip->ip_off = ntohs(ip->ip_off);
409 /* Send packet to output processing */
410 KMOD_IPSTAT_INC(ips_rawout); /* XXX */
413 mac_inpcb_create_mbuf(inp, m);
416 * Get ready to inject the packet into ip_output().
417 * Just in case socket options were specified on the
418 * divert socket, we duplicate them. This is done
419 * to avoid having to hold the PCB locks over the call
420 * to ip_output(), as doing this results in a number of
421 * lock ordering complexities.
423 * Note that we set the multicast options argument for
424 * ip_output() to NULL since it should be invariant that
425 * they are not present.
427 KASSERT(inp->inp_moptions == NULL,
428 ("multicast options set on a divert socket"));
431 * XXXCSJP: It is unclear to me whether or not it makes
432 * sense for divert sockets to have options. However,
433 * for now we will duplicate them with the INP locks
434 * held so we can use them in ip_output() without
435 * requring a reference to the pcb.
437 if (inp->inp_options != NULL) {
438 options = m_dup(inp->inp_options, M_DONTWAIT);
443 INP_INFO_WUNLOCK(&V_divcbinfo);
444 if (error == ENOBUFS) {
448 error = ip_output(m, options, NULL,
449 ((so->so_options & SO_DONTROUTE) ?
450 IP_ROUTETOIF : 0) | IP_ALLOWBROADCAST |
451 IP_RAWOUTPUT, NULL, NULL);
456 dt->info |= IP_FW_DIVERT_LOOPBACK_FLAG;
457 if (m->m_pkthdr.rcvif == NULL) {
459 * No luck with the name, check by IP address.
460 * Clear the port and the ifname to make sure
461 * there are no distractions for ifa_ifwithaddr.
465 bzero(sin->sin_zero, sizeof(sin->sin_zero));
467 ifa = ifa_ifwithaddr((struct sockaddr *) sin);
469 error = EADDRNOTAVAIL;
472 m->m_pkthdr.rcvif = ifa->ifa_ifp;
476 mac_socket_create_mbuf(so, m);
478 /* Send packet to input processing via netisr */
479 netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
490 div_attach(struct socket *so, int proto, struct thread *td)
496 KASSERT(inp == NULL, ("div_attach: inp != NULL"));
498 error = priv_check(td, PRIV_NETINET_DIVERT);
502 error = soreserve(so, div_sendspace, div_recvspace);
505 INP_INFO_WLOCK(&V_divcbinfo);
506 error = in_pcballoc(so, &V_divcbinfo);
508 INP_INFO_WUNLOCK(&V_divcbinfo);
511 inp = (struct inpcb *)so->so_pcb;
512 INP_INFO_WUNLOCK(&V_divcbinfo);
513 inp->inp_ip_p = proto;
514 inp->inp_vflag |= INP_IPV4;
515 inp->inp_flags |= INP_HDRINCL;
521 div_detach(struct socket *so)
526 KASSERT(inp != NULL, ("div_detach: inp == NULL"));
527 INP_INFO_WLOCK(&V_divcbinfo);
531 INP_INFO_WUNLOCK(&V_divcbinfo);
535 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
541 KASSERT(inp != NULL, ("div_bind: inp == NULL"));
542 /* in_pcbbind assumes that nam is a sockaddr_in
543 * and in_pcbbind requires a valid address. Since divert
544 * sockets don't we need to make sure the address is
545 * filled in properly.
546 * XXX -- divert should not be abusing in_pcbind
547 * and should probably have its own family.
549 if (nam->sa_family != AF_INET)
551 ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
552 INP_INFO_WLOCK(&V_divcbinfo);
554 error = in_pcbbind(inp, nam, td->td_ucred);
556 INP_INFO_WUNLOCK(&V_divcbinfo);
561 div_shutdown(struct socket *so)
566 KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
574 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
575 struct mbuf *control, struct thread *td)
578 /* Packet must have a header (but that's about it) */
579 if (m->m_len < sizeof (struct ip) &&
580 (m = m_pullup(m, sizeof (struct ip))) == 0) {
581 KMOD_IPSTAT_INC(ips_toosmall);
587 return div_output(so, m, (struct sockaddr_in *)nam, control);
591 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
593 struct in_addr faddr;
595 faddr = ((struct sockaddr_in *)sa)->sin_addr;
596 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
598 if (PRC_IS_REDIRECT(cmd))
603 div_pcblist(SYSCTL_HANDLER_ARGS)
606 struct inpcb *inp, **inp_list;
611 * The process of preparing the TCB list is too time-consuming and
612 * resource-intensive to repeat twice on every request.
614 if (req->oldptr == 0) {
615 n = V_divcbinfo.ipi_count;
616 req->oldidx = 2 * (sizeof xig)
617 + (n + n/8) * sizeof(struct xinpcb);
621 if (req->newptr != 0)
625 * OK, now we're committed to doing something.
627 INP_INFO_RLOCK(&V_divcbinfo);
628 gencnt = V_divcbinfo.ipi_gencnt;
629 n = V_divcbinfo.ipi_count;
630 INP_INFO_RUNLOCK(&V_divcbinfo);
632 error = sysctl_wire_old_buffer(req,
633 2 * sizeof(xig) + n*sizeof(struct xinpcb));
637 xig.xig_len = sizeof xig;
639 xig.xig_gen = gencnt;
640 xig.xig_sogen = so_gencnt;
641 error = SYSCTL_OUT(req, &xig, sizeof xig);
645 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
649 INP_INFO_RLOCK(&V_divcbinfo);
650 for (inp = LIST_FIRST(V_divcbinfo.ipi_listhead), i = 0; inp && i < n;
651 inp = LIST_NEXT(inp, inp_list)) {
653 if (inp->inp_gencnt <= gencnt &&
654 cr_canseeinpcb(req->td->td_ucred, inp) == 0)
658 INP_INFO_RUNLOCK(&V_divcbinfo);
662 for (i = 0; i < n; i++) {
665 if (inp->inp_gencnt <= gencnt) {
667 bzero(&xi, sizeof(xi));
668 xi.xi_len = sizeof xi;
669 /* XXX should avoid extra copy */
670 bcopy(inp, &xi.xi_inp, sizeof *inp);
672 sotoxsocket(inp->inp_socket, &xi.xi_socket);
674 error = SYSCTL_OUT(req, &xi, sizeof xi);
680 * Give the user an updated idea of our state.
681 * If the generation differs from what we told
682 * her before, she knows that something happened
683 * while we were processing this request, and it
684 * might be necessary to retry.
686 INP_INFO_RLOCK(&V_divcbinfo);
687 xig.xig_gen = V_divcbinfo.ipi_gencnt;
688 xig.xig_sogen = so_gencnt;
689 xig.xig_count = V_divcbinfo.ipi_count;
690 INP_INFO_RUNLOCK(&V_divcbinfo);
691 error = SYSCTL_OUT(req, &xig, sizeof xig);
693 free(inp_list, M_TEMP);
698 SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
699 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
700 div_pcblist, "S,xinpcb", "List of active divert sockets");
703 struct pr_usrreqs div_usrreqs = {
704 .pru_attach = div_attach,
705 .pru_bind = div_bind,
706 .pru_control = in_control,
707 .pru_detach = div_detach,
708 .pru_peeraddr = in_getpeeraddr,
709 .pru_send = div_send,
710 .pru_shutdown = div_shutdown,
711 .pru_sockaddr = in_getsockaddr,
712 .pru_sosetlabel = in_pcbsosetlabel
715 struct protosw div_protosw = {
717 .pr_protocol = IPPROTO_DIVERT,
718 .pr_flags = PR_ATOMIC|PR_ADDR,
719 .pr_input = div_input,
720 .pr_ctlinput = div_ctlinput,
721 .pr_ctloutput = ip_ctloutput,
724 .pr_destroy = div_destroy,
726 .pr_usrreqs = &div_usrreqs
730 div_modevent(module_t mod, int type, void *unused)
740 * Protocol will be initialized by pf_proto_register().
741 * We don't have to register ip_protox because we are not
742 * a true IP protocol that goes over the wire.
744 err = pf_proto_register(PF_INET, &div_protosw);
747 ip_divert_ptr = divert_packet;
748 ip_divert_event_tag = EVENTHANDLER_REGISTER(maxsockets_change,
749 div_zone_change, NULL, EVENTHANDLER_PRI_ANY);
753 * IPDIVERT may normally not be unloaded because of the
754 * potential race conditions. Tell kldunload we can't be
755 * unloaded unless the unload is forced.
767 * Module ipdivert can only be unloaded if no sockets are
768 * connected. Maybe this can be changed later to forcefully
769 * disconnect any open sockets.
771 * XXXRW: Note that there is a slight race here, as a new
772 * socket open request could be spinning on the lock and then
773 * we destroy the lock.
775 INP_INFO_WLOCK(&V_divcbinfo);
776 n = V_divcbinfo.ipi_count;
779 INP_INFO_WUNLOCK(&V_divcbinfo);
782 ip_divert_ptr = NULL;
783 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
784 INP_INFO_WUNLOCK(&V_divcbinfo);
786 EVENTHANDLER_DEREGISTER(maxsockets_change, ip_divert_event_tag);
796 static moduledata_t ipdivertmod = {
802 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
803 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
804 MODULE_VERSION(ipdivert, 1);