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);
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;
395 INP_INFO_WLOCK(&V_divcbinfo);
399 * Don't allow both user specified and setsockopt options,
400 * and don't allow packet length sizes that will crash
402 if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
403 ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
406 INP_INFO_WUNLOCK(&V_divcbinfo);
409 /* Convert fields to host order for ip_output() */
410 ip->ip_len = ntohs(ip->ip_len);
411 ip->ip_off = ntohs(ip->ip_off);
413 /* Send packet to output processing */
414 KMOD_IPSTAT_INC(ips_rawout); /* XXX */
417 mac_inpcb_create_mbuf(inp, m);
420 * Get ready to inject the packet into ip_output().
421 * Just in case socket options were specified on the
422 * divert socket, we duplicate them. This is done
423 * to avoid having to hold the PCB locks over the call
424 * to ip_output(), as doing this results in a number of
425 * lock ordering complexities.
427 * Note that we set the multicast options argument for
428 * ip_output() to NULL since it should be invariant that
429 * they are not present.
431 KASSERT(inp->inp_moptions == NULL,
432 ("multicast options set on a divert socket"));
435 * XXXCSJP: It is unclear to me whether or not it makes
436 * sense for divert sockets to have options. However,
437 * for now we will duplicate them with the INP locks
438 * held so we can use them in ip_output() without
439 * requring a reference to the pcb.
441 if (inp->inp_options != NULL) {
442 options = m_dup(inp->inp_options, M_DONTWAIT);
447 INP_INFO_WUNLOCK(&V_divcbinfo);
448 if (error == ENOBUFS) {
452 error = ip_output(m, options, NULL,
453 ((so->so_options & SO_DONTROUTE) ?
454 IP_ROUTETOIF : 0) | IP_ALLOWBROADCAST |
455 IP_RAWOUTPUT, NULL, NULL);
460 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
461 if (m->m_pkthdr.rcvif == NULL) {
463 * No luck with the name, check by IP address.
464 * Clear the port and the ifname to make sure
465 * there are no distractions for ifa_ifwithaddr.
469 bzero(sin->sin_zero, sizeof(sin->sin_zero));
471 ifa = ifa_ifwithaddr((struct sockaddr *) sin);
473 error = EADDRNOTAVAIL;
476 m->m_pkthdr.rcvif = ifa->ifa_ifp;
480 mac_socket_create_mbuf(so, m);
482 /* Send packet to input processing via netisr */
483 netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
494 div_attach(struct socket *so, int proto, struct thread *td)
500 KASSERT(inp == NULL, ("div_attach: inp != NULL"));
502 error = priv_check(td, PRIV_NETINET_DIVERT);
506 error = soreserve(so, div_sendspace, div_recvspace);
509 INP_INFO_WLOCK(&V_divcbinfo);
510 error = in_pcballoc(so, &V_divcbinfo);
512 INP_INFO_WUNLOCK(&V_divcbinfo);
515 inp = (struct inpcb *)so->so_pcb;
516 INP_INFO_WUNLOCK(&V_divcbinfo);
517 inp->inp_ip_p = proto;
518 inp->inp_vflag |= INP_IPV4;
519 inp->inp_flags |= INP_HDRINCL;
525 div_detach(struct socket *so)
530 KASSERT(inp != NULL, ("div_detach: inp == NULL"));
531 INP_INFO_WLOCK(&V_divcbinfo);
535 INP_INFO_WUNLOCK(&V_divcbinfo);
539 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
545 KASSERT(inp != NULL, ("div_bind: inp == NULL"));
546 /* in_pcbbind assumes that nam is a sockaddr_in
547 * and in_pcbbind requires a valid address. Since divert
548 * sockets don't we need to make sure the address is
549 * filled in properly.
550 * XXX -- divert should not be abusing in_pcbind
551 * and should probably have its own family.
553 if (nam->sa_family != AF_INET)
555 ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
556 INP_INFO_WLOCK(&V_divcbinfo);
558 error = in_pcbbind(inp, nam, td->td_ucred);
560 INP_INFO_WUNLOCK(&V_divcbinfo);
565 div_shutdown(struct socket *so)
570 KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
578 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
579 struct mbuf *control, struct thread *td)
582 /* Packet must have a header (but that's about it) */
583 if (m->m_len < sizeof (struct ip) &&
584 (m = m_pullup(m, sizeof (struct ip))) == 0) {
585 KMOD_IPSTAT_INC(ips_toosmall);
591 return div_output(so, m, (struct sockaddr_in *)nam, control);
595 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
597 struct in_addr faddr;
599 faddr = ((struct sockaddr_in *)sa)->sin_addr;
600 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
602 if (PRC_IS_REDIRECT(cmd))
607 div_pcblist(SYSCTL_HANDLER_ARGS)
610 struct inpcb *inp, **inp_list;
615 * The process of preparing the TCB list is too time-consuming and
616 * resource-intensive to repeat twice on every request.
618 if (req->oldptr == 0) {
619 n = V_divcbinfo.ipi_count;
620 req->oldidx = 2 * (sizeof xig)
621 + (n + n/8) * sizeof(struct xinpcb);
625 if (req->newptr != 0)
629 * OK, now we're committed to doing something.
631 INP_INFO_RLOCK(&V_divcbinfo);
632 gencnt = V_divcbinfo.ipi_gencnt;
633 n = V_divcbinfo.ipi_count;
634 INP_INFO_RUNLOCK(&V_divcbinfo);
636 error = sysctl_wire_old_buffer(req,
637 2 * sizeof(xig) + n*sizeof(struct xinpcb));
641 xig.xig_len = sizeof xig;
643 xig.xig_gen = gencnt;
644 xig.xig_sogen = so_gencnt;
645 error = SYSCTL_OUT(req, &xig, sizeof xig);
649 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
653 INP_INFO_RLOCK(&V_divcbinfo);
654 for (inp = LIST_FIRST(V_divcbinfo.ipi_listhead), i = 0; inp && i < n;
655 inp = LIST_NEXT(inp, inp_list)) {
657 if (inp->inp_gencnt <= gencnt &&
658 cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
664 INP_INFO_RUNLOCK(&V_divcbinfo);
668 for (i = 0; i < n; i++) {
671 if (inp->inp_gencnt <= gencnt) {
673 bzero(&xi, sizeof(xi));
674 xi.xi_len = sizeof xi;
675 /* XXX should avoid extra copy */
676 bcopy(inp, &xi.xi_inp, sizeof *inp);
678 sotoxsocket(inp->inp_socket, &xi.xi_socket);
680 error = SYSCTL_OUT(req, &xi, sizeof xi);
684 INP_INFO_WLOCK(&V_divcbinfo);
685 for (i = 0; i < n; i++) {
688 if (!in_pcbrele(inp))
691 INP_INFO_WUNLOCK(&V_divcbinfo);
695 * Give the user an updated idea of our state.
696 * If the generation differs from what we told
697 * her before, she knows that something happened
698 * while we were processing this request, and it
699 * might be necessary to retry.
701 INP_INFO_RLOCK(&V_divcbinfo);
702 xig.xig_gen = V_divcbinfo.ipi_gencnt;
703 xig.xig_sogen = so_gencnt;
704 xig.xig_count = V_divcbinfo.ipi_count;
705 INP_INFO_RUNLOCK(&V_divcbinfo);
706 error = SYSCTL_OUT(req, &xig, sizeof xig);
708 free(inp_list, M_TEMP);
713 SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
714 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
715 div_pcblist, "S,xinpcb", "List of active divert sockets");
718 struct pr_usrreqs div_usrreqs = {
719 .pru_attach = div_attach,
720 .pru_bind = div_bind,
721 .pru_control = in_control,
722 .pru_detach = div_detach,
723 .pru_peeraddr = in_getpeeraddr,
724 .pru_send = div_send,
725 .pru_shutdown = div_shutdown,
726 .pru_sockaddr = in_getsockaddr,
727 .pru_sosetlabel = in_pcbsosetlabel
730 struct protosw div_protosw = {
732 .pr_protocol = IPPROTO_DIVERT,
733 .pr_flags = PR_ATOMIC|PR_ADDR,
734 .pr_input = div_input,
735 .pr_ctlinput = div_ctlinput,
736 .pr_ctloutput = ip_ctloutput,
739 .pr_destroy = div_destroy,
741 .pr_usrreqs = &div_usrreqs
745 div_modevent(module_t mod, int type, void *unused)
755 * Protocol will be initialized by pf_proto_register().
756 * We don't have to register ip_protox because we are not
757 * a true IP protocol that goes over the wire.
759 err = pf_proto_register(PF_INET, &div_protosw);
762 ip_divert_ptr = divert_packet;
763 ip_divert_event_tag = EVENTHANDLER_REGISTER(maxsockets_change,
764 div_zone_change, NULL, EVENTHANDLER_PRI_ANY);
768 * IPDIVERT may normally not be unloaded because of the
769 * potential race conditions. Tell kldunload we can't be
770 * unloaded unless the unload is forced.
782 * Module ipdivert can only be unloaded if no sockets are
783 * connected. Maybe this can be changed later to forcefully
784 * disconnect any open sockets.
786 * XXXRW: Note that there is a slight race here, as a new
787 * socket open request could be spinning on the lock and then
788 * we destroy the lock.
790 INP_INFO_WLOCK(&V_divcbinfo);
791 n = V_divcbinfo.ipi_count;
794 INP_INFO_WUNLOCK(&V_divcbinfo);
797 ip_divert_ptr = NULL;
798 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
799 INP_INFO_WUNLOCK(&V_divcbinfo);
801 EVENTHANDLER_DEREGISTER(maxsockets_change, ip_divert_event_tag);
811 static moduledata_t ipdivertmod = {
817 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
818 MODULE_DEPEND(ipdivert, ipfw, 2, 2, 2);
819 MODULE_VERSION(ipdivert, 1);