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)
37 #error "IPDIVERT requires INET."
41 #include <sys/param.h>
42 #include <sys/kernel.h>
44 #include <sys/malloc.h>
46 #include <sys/module.h>
47 #include <sys/kernel.h>
50 #include <sys/protosw.h>
51 #include <sys/rwlock.h>
52 #include <sys/signalvar.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/systm.h>
62 #include <net/netisr.h>
63 #include <net/route.h>
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>
73 #include <netinet/sctp_crc32.h>
76 #include <security/mac/mac_framework.h>
83 * Allocate enough space to hold a full IP packet
85 #define DIVSNDQ (65536 + 100)
86 #define DIVRCVQ (65536 + 100)
89 * Divert sockets work in conjunction with ipfw or other packet filters,
90 * see the divert(4) manpage for features.
91 * Packets are selected by the packet filter and tagged with an
92 * MTAG_IPFW_RULE tag carrying the 'divert port' number (as set by
93 * the packet filter) and information on the matching filter rule for
94 * subsequent reinjection. The divert_port is used to put the packet
95 * on the corresponding divert socket, while the rule number is passed
96 * up (at least partially) as the sin_port in the struct sockaddr.
98 * Packets written to the divert socket carry in sin_addr a
99 * destination address, and in sin_port the number of the filter rule
100 * after which to continue processing.
101 * If the destination address is INADDR_ANY, the packet is treated as
102 * as outgoing and sent to ip_output(); otherwise it is treated as
103 * incoming and sent to ip_input().
104 * Further, sin_zero carries some information on the interface,
105 * which can be used in the reinject -- see comments in the code.
107 * On reinjection, processing in ip_input() and ip_output()
108 * will be exactly the same as for the original packet, except that
109 * packet filter processing will start at the rule number after the one
110 * written in the sin_port (ipfw does not allow a rule #0, so sin_port=0
111 * will apply the entire ruleset to the packet).
114 /* Internal variables. */
115 static VNET_DEFINE(struct inpcbhead, divcb);
116 static VNET_DEFINE(struct inpcbinfo, divcbinfo);
118 #define V_divcb VNET(divcb)
119 #define V_divcbinfo VNET(divcbinfo)
121 static u_long div_sendspace = DIVSNDQ; /* XXX sysctl ? */
122 static u_long div_recvspace = DIVRCVQ; /* XXX sysctl ? */
124 static eventhandler_tag ip_divert_event_tag;
127 * Initialize divert connection block queue.
130 div_zone_change(void *tag)
133 uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
137 div_inpcb_init(void *mem, int size, int flags)
139 struct inpcb *inp = mem;
141 INP_LOCK_INIT(inp, "inp", "divinp");
146 div_inpcb_fini(void *mem, int size)
148 struct inpcb *inp = mem;
150 INP_LOCK_DESTROY(inp);
157 INP_INFO_LOCK_INIT(&V_divcbinfo, "div");
159 V_divcbinfo.ipi_listhead = &V_divcb;
161 V_divcbinfo.ipi_vnet = curvnet;
164 * XXX We don't use the hash list for divert IP, but it's easier
165 * to allocate a one entry hash list than it is to check all
166 * over the place for hashbase == NULL.
168 V_divcbinfo.ipi_hashbase = hashinit(1, M_PCB, &V_divcbinfo.ipi_hashmask);
169 V_divcbinfo.ipi_porthashbase = hashinit(1, M_PCB,
170 &V_divcbinfo.ipi_porthashmask);
171 V_divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
172 NULL, NULL, div_inpcb_init, div_inpcb_fini, UMA_ALIGN_PTR,
174 uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
181 INP_INFO_LOCK_DESTROY(&V_divcbinfo);
182 uma_zdestroy(V_divcbinfo.ipi_zone);
183 hashdestroy(V_divcbinfo.ipi_hashbase, M_PCB, V_divcbinfo.ipi_hashmask);
184 hashdestroy(V_divcbinfo.ipi_porthashbase, M_PCB,
185 V_divcbinfo.ipi_porthashmask);
189 * IPPROTO_DIVERT is not in the real IP protocol number space; this
190 * function should never be called. Just in case, drop any packets.
193 div_input(struct mbuf *m, int off)
196 KMOD_IPSTAT_INC(ips_noproto);
201 * Divert a packet by passing it up to the divert socket at port 'port'.
203 * Setup generic address and protocol structures for div_input routine,
204 * then pass them along with mbuf chain.
207 divert_packet(struct mbuf *m, int incoming)
213 struct sockaddr_in divsrc;
216 mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
222 if (m->m_len < sizeof(struct ip) &&
223 (m = m_pullup(m, sizeof(struct ip))) == 0)
225 ip = mtod(m, struct ip *);
227 /* Delayed checksums are currently not compatible with divert. */
228 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
229 ip->ip_len = ntohs(ip->ip_len);
231 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
232 ip->ip_len = htons(ip->ip_len);
235 if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
236 ip->ip_len = ntohs(ip->ip_len);
237 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
238 m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
239 ip->ip_len = htons(ip->ip_len);
242 bzero(&divsrc, sizeof(divsrc));
243 divsrc.sin_len = sizeof(divsrc);
244 divsrc.sin_family = AF_INET;
245 /* record matching rule, in host format */
246 divsrc.sin_port = ((struct ipfw_rule_ref *)(mtag+1))->rulenum;
248 * Record receive interface address, if any.
249 * But only for incoming packets.
258 /* Find IP address for receive interface */
259 ifp = m->m_pkthdr.rcvif;
261 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
262 if (ifa->ifa_addr->sa_family != AF_INET)
265 ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
268 if_addr_runlock(ifp);
271 * Record the incoming interface name whenever we have one.
273 if (m->m_pkthdr.rcvif) {
275 * Hide the actual interface name in there in the
276 * sin_zero array. XXX This needs to be moved to a
277 * different sockaddr type for divert, e.g.
278 * sockaddr_div with multiple fields like
279 * sockaddr_dl. Presently we have only 7 bytes
280 * but that will do for now as most interfaces
281 * are 4 or less + 2 or less bytes for unit.
282 * There is probably a faster way of doing this,
283 * possibly taking it from the sockaddr_dl on the iface.
284 * This solves the problem of a P2P link and a LAN interface
285 * having the same address, which can result in the wrong
286 * interface being assigned to the packet when fed back
287 * into the divert socket. Theoretically if the daemon saves
288 * and re-uses the sockaddr_in as suggested in the man pages,
289 * this iface name will come along for the ride.
290 * (see div_output for the other half of this.)
292 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
293 sizeof(divsrc.sin_zero));
296 /* Put packet on socket queue, if any */
298 nport = htons((u_int16_t)(((struct ipfw_rule_ref *)(mtag+1))->info));
299 INP_INFO_RLOCK(&V_divcbinfo);
300 LIST_FOREACH(inp, &V_divcb, inp_list) {
301 /* XXX why does only one socket match? */
302 if (inp->inp_lport == nport) {
304 sa = inp->inp_socket;
305 SOCKBUF_LOCK(&sa->so_rcv);
306 if (sbappendaddr_locked(&sa->so_rcv,
307 (struct sockaddr *)&divsrc, m,
308 (struct mbuf *)0) == 0) {
309 SOCKBUF_UNLOCK(&sa->so_rcv);
310 sa = NULL; /* force mbuf reclaim below */
312 sorwakeup_locked(sa);
317 INP_INFO_RUNLOCK(&V_divcbinfo);
320 KMOD_IPSTAT_INC(ips_noproto);
321 KMOD_IPSTAT_DEC(ips_delivered);
326 * Deliver packet back into the IP processing machinery.
328 * If no address specified, or address is 0.0.0.0, send to ip_output();
329 * otherwise, send to ip_input() and mark as having been received on
330 * the interface with that address.
333 div_output(struct socket *so, struct mbuf *m, struct sockaddr_in *sin,
334 struct mbuf *control)
337 struct ipfw_rule_ref *dt;
339 struct mbuf *options;
342 * An mbuf may hasn't come from userland, but we pretend
345 m->m_pkthdr.rcvif = NULL;
347 M_SETFIB(m, so->so_fibnum);
350 m_freem(control); /* XXX */
352 mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
354 /* this should be normal */
355 mtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
356 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
361 m_tag_prepend(m, mtag);
363 dt = (struct ipfw_rule_ref *)(mtag+1);
365 /* Loopback avoidance and state recovery */
369 /* set the starting point. We provide a non-zero slot,
370 * but a non_matching chain_id to skip that info and use
371 * the rulenum/rule_id.
373 dt->slot = 1; /* dummy, chain_id is invalid */
375 dt->rulenum = sin->sin_port+1; /* host format ? */
378 * Find receive interface with the given name, stuffed
379 * (if it exists) in the sin_zero[] field.
380 * The name is user supplied data so don't trust its size
381 * or that it is zero terminated.
383 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
385 if ( i > 0 && i < sizeof(sin->sin_zero))
386 m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
389 /* Reinject packet into the system as incoming or outgoing */
390 if (!sin || sin->sin_addr.s_addr == 0) {
391 struct ip *const ip = mtod(m, struct ip *);
394 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_OUT;
398 * Don't allow both user specified and setsockopt options,
399 * and don't allow packet length sizes that will crash
401 if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
402 ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
407 /* Convert fields to host order for ip_output() */
408 ip->ip_len = ntohs(ip->ip_len);
409 ip->ip_off = ntohs(ip->ip_off);
411 /* Send packet to output processing */
412 KMOD_IPSTAT_INC(ips_rawout); /* XXX */
415 mac_inpcb_create_mbuf(inp, m);
418 * Get ready to inject the packet into ip_output().
419 * Just in case socket options were specified on the
420 * divert socket, we duplicate them. This is done
421 * to avoid having to hold the PCB locks over the call
422 * to ip_output(), as doing this results in a number of
423 * lock ordering complexities.
425 * Note that we set the multicast options argument for
426 * ip_output() to NULL since it should be invariant that
427 * they are not present.
429 KASSERT(inp->inp_moptions == NULL,
430 ("multicast options set on a divert socket"));
433 * XXXCSJP: It is unclear to me whether or not it makes
434 * sense for divert sockets to have options. However,
435 * for now we will duplicate them with the INP locks
436 * held so we can use them in ip_output() without
437 * requring a reference to the pcb.
439 if (inp->inp_options != NULL) {
440 options = m_dup(inp->inp_options, M_DONTWAIT);
445 if (error == ENOBUFS) {
449 error = ip_output(m, options, NULL,
450 ((so->so_options & SO_DONTROUTE) ?
451 IP_ROUTETOIF : 0) | IP_ALLOWBROADCAST |
452 IP_RAWOUTPUT, NULL, NULL);
457 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
458 if (m->m_pkthdr.rcvif == NULL) {
460 * No luck with the name, check by IP address.
461 * Clear the port and the ifname to make sure
462 * there are no distractions for ifa_ifwithaddr.
466 bzero(sin->sin_zero, sizeof(sin->sin_zero));
468 ifa = ifa_ifwithaddr((struct sockaddr *) sin);
470 error = EADDRNOTAVAIL;
473 m->m_pkthdr.rcvif = ifa->ifa_ifp;
477 mac_socket_create_mbuf(so, m);
479 /* Send packet to input processing via netisr */
480 netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
491 div_attach(struct socket *so, int proto, struct thread *td)
497 KASSERT(inp == NULL, ("div_attach: inp != NULL"));
499 error = priv_check(td, PRIV_NETINET_DIVERT);
503 error = soreserve(so, div_sendspace, div_recvspace);
506 INP_INFO_WLOCK(&V_divcbinfo);
507 error = in_pcballoc(so, &V_divcbinfo);
509 INP_INFO_WUNLOCK(&V_divcbinfo);
512 inp = (struct inpcb *)so->so_pcb;
513 INP_INFO_WUNLOCK(&V_divcbinfo);
514 inp->inp_ip_p = proto;
515 inp->inp_vflag |= INP_IPV4;
516 inp->inp_flags |= INP_HDRINCL;
522 div_detach(struct socket *so)
527 KASSERT(inp != NULL, ("div_detach: inp == NULL"));
528 INP_INFO_WLOCK(&V_divcbinfo);
532 INP_INFO_WUNLOCK(&V_divcbinfo);
536 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
542 KASSERT(inp != NULL, ("div_bind: inp == NULL"));
543 /* in_pcbbind assumes that nam is a sockaddr_in
544 * and in_pcbbind requires a valid address. Since divert
545 * sockets don't we need to make sure the address is
546 * filled in properly.
547 * XXX -- divert should not be abusing in_pcbind
548 * and should probably have its own family.
550 if (nam->sa_family != AF_INET)
552 ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
553 INP_INFO_WLOCK(&V_divcbinfo);
555 error = in_pcbbind(inp, nam, td->td_ucred);
557 INP_INFO_WUNLOCK(&V_divcbinfo);
562 div_shutdown(struct socket *so)
567 KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
575 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
576 struct mbuf *control, struct thread *td)
579 /* Packet must have a header (but that's about it) */
580 if (m->m_len < sizeof (struct ip) &&
581 (m = m_pullup(m, sizeof (struct ip))) == 0) {
582 KMOD_IPSTAT_INC(ips_toosmall);
588 return div_output(so, m, (struct sockaddr_in *)nam, control);
592 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
594 struct in_addr faddr;
596 faddr = ((struct sockaddr_in *)sa)->sin_addr;
597 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
599 if (PRC_IS_REDIRECT(cmd))
604 div_pcblist(SYSCTL_HANDLER_ARGS)
607 struct inpcb *inp, **inp_list;
612 * The process of preparing the TCB list is too time-consuming and
613 * resource-intensive to repeat twice on every request.
615 if (req->oldptr == 0) {
616 n = V_divcbinfo.ipi_count;
617 n += imax(n / 8, 10);
618 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
622 if (req->newptr != 0)
626 * OK, now we're committed to doing something.
628 INP_INFO_RLOCK(&V_divcbinfo);
629 gencnt = V_divcbinfo.ipi_gencnt;
630 n = V_divcbinfo.ipi_count;
631 INP_INFO_RUNLOCK(&V_divcbinfo);
633 error = sysctl_wire_old_buffer(req,
634 2 * sizeof(xig) + n*sizeof(struct xinpcb));
638 xig.xig_len = sizeof xig;
640 xig.xig_gen = gencnt;
641 xig.xig_sogen = so_gencnt;
642 error = SYSCTL_OUT(req, &xig, sizeof xig);
646 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
650 INP_INFO_RLOCK(&V_divcbinfo);
651 for (inp = LIST_FIRST(V_divcbinfo.ipi_listhead), i = 0; inp && i < n;
652 inp = LIST_NEXT(inp, inp_list)) {
654 if (inp->inp_gencnt <= gencnt &&
655 cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
661 INP_INFO_RUNLOCK(&V_divcbinfo);
665 for (i = 0; i < n; i++) {
668 if (inp->inp_gencnt <= gencnt) {
670 bzero(&xi, sizeof(xi));
671 xi.xi_len = sizeof xi;
672 /* XXX should avoid extra copy */
673 bcopy(inp, &xi.xi_inp, sizeof *inp);
675 sotoxsocket(inp->inp_socket, &xi.xi_socket);
677 error = SYSCTL_OUT(req, &xi, sizeof xi);
681 INP_INFO_WLOCK(&V_divcbinfo);
682 for (i = 0; i < n; i++) {
685 if (!in_pcbrele(inp))
688 INP_INFO_WUNLOCK(&V_divcbinfo);
692 * Give the user an updated idea of our state.
693 * If the generation differs from what we told
694 * her before, she knows that something happened
695 * while we were processing this request, and it
696 * might be necessary to retry.
698 INP_INFO_RLOCK(&V_divcbinfo);
699 xig.xig_gen = V_divcbinfo.ipi_gencnt;
700 xig.xig_sogen = so_gencnt;
701 xig.xig_count = V_divcbinfo.ipi_count;
702 INP_INFO_RUNLOCK(&V_divcbinfo);
703 error = SYSCTL_OUT(req, &xig, sizeof xig);
705 free(inp_list, M_TEMP);
710 SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
711 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
712 NULL, 0, div_pcblist, "S,xinpcb", "List of active divert sockets");
715 struct pr_usrreqs div_usrreqs = {
716 .pru_attach = div_attach,
717 .pru_bind = div_bind,
718 .pru_control = in_control,
719 .pru_detach = div_detach,
720 .pru_peeraddr = in_getpeeraddr,
721 .pru_send = div_send,
722 .pru_shutdown = div_shutdown,
723 .pru_sockaddr = in_getsockaddr,
724 .pru_sosetlabel = in_pcbsosetlabel
727 struct protosw div_protosw = {
729 .pr_protocol = IPPROTO_DIVERT,
730 .pr_flags = PR_ATOMIC|PR_ADDR,
731 .pr_input = div_input,
732 .pr_ctlinput = div_ctlinput,
733 .pr_ctloutput = ip_ctloutput,
736 .pr_destroy = div_destroy,
738 .pr_usrreqs = &div_usrreqs
742 div_modevent(module_t mod, int type, void *unused)
752 * Protocol will be initialized by pf_proto_register().
753 * We don't have to register ip_protox because we are not
754 * a true IP protocol that goes over the wire.
756 err = pf_proto_register(PF_INET, &div_protosw);
759 ip_divert_ptr = divert_packet;
760 ip_divert_event_tag = EVENTHANDLER_REGISTER(maxsockets_change,
761 div_zone_change, NULL, EVENTHANDLER_PRI_ANY);
765 * IPDIVERT may normally not be unloaded because of the
766 * potential race conditions. Tell kldunload we can't be
767 * unloaded unless the unload is forced.
779 * Module ipdivert can only be unloaded if no sockets are
780 * connected. Maybe this can be changed later to forcefully
781 * disconnect any open sockets.
783 * XXXRW: Note that there is a slight race here, as a new
784 * socket open request could be spinning on the lock and then
785 * we destroy the lock.
787 INP_INFO_WLOCK(&V_divcbinfo);
788 n = V_divcbinfo.ipi_count;
791 INP_INFO_WUNLOCK(&V_divcbinfo);
794 ip_divert_ptr = NULL;
795 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
796 INP_INFO_WUNLOCK(&V_divcbinfo);
798 EVENTHANDLER_DEREGISTER(maxsockets_change, ip_divert_event_tag);
808 static moduledata_t ipdivertmod = {
814 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
815 MODULE_DEPEND(ipdivert, ipfw, 2, 2, 2);
816 MODULE_VERSION(ipdivert, 1);