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
32 #if !defined(KLD_MODULE)
37 #error "IPDIVERT requires INET."
40 #error "IPDIVERT requires IPFIREWALL"
44 #include <sys/param.h>
45 #include <sys/kernel.h>
47 #include <sys/malloc.h>
49 #include <sys/module.h>
50 #include <sys/kernel.h>
53 #include <sys/protosw.h>
54 #include <sys/signalvar.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
64 #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_divert.h>
72 #include <netinet/ip_var.h>
73 #include <netinet/ip_fw.h>
75 #include <security/mac/mac_framework.h>
82 * Allocate enough space to hold a full IP packet
84 #define DIVSNDQ (65536 + 100)
85 #define DIVRCVQ (65536 + 100)
88 * Divert sockets work in conjunction with ipfw, see the divert(4)
89 * manpage for features.
90 * Internally, packets selected by ipfw in ip_input() or ip_output(),
91 * and never diverted before, are passed to the input queue of the
92 * divert socket with a given 'divert_port' number (as specified in
93 * the matching ipfw rule), and they are tagged with a 16 bit cookie
94 * (representing the rule number of the matching ipfw rule), which
95 * is passed to process reading from the socket.
97 * Packets written to the divert socket are again tagged with a cookie
98 * (usually the same as above) and a destination address.
99 * If the destination address is INADDR_ANY then the packet is
100 * treated as outgoing and sent to ip_output(), otherwise it is
101 * treated as incoming and sent to ip_input().
102 * In both cases, the packet is tagged with the cookie.
104 * On reinjection, processing in ip_input() and ip_output()
105 * will be exactly the same as for the original packet, except that
106 * ipfw processing will start at the rule number after the one
107 * written in the cookie (so, tagging a packet with a cookie of 0
108 * will cause it to be effectively considered as a standard packet).
111 /* Internal variables. */
112 static struct inpcbhead divcb;
113 static struct inpcbinfo divcbinfo;
115 static u_long div_sendspace = DIVSNDQ; /* XXX sysctl ? */
116 static u_long div_recvspace = DIVRCVQ; /* XXX sysctl ? */
119 * Initialize divert connection block queue.
122 div_zone_change(void *tag)
125 uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
129 div_inpcb_init(void *mem, int size, int flags)
131 struct inpcb *inp = mem;
133 INP_LOCK_INIT(inp, "inp", "divinp");
138 div_inpcb_fini(void *mem, int size)
140 struct inpcb *inp = mem;
142 INP_LOCK_DESTROY(inp);
149 INP_INFO_LOCK_INIT(&divcbinfo, "div");
151 divcbinfo.ipi_listhead = &divcb;
153 * XXX We don't use the hash list for divert IP, but it's easier
154 * to allocate a one entry hash list than it is to check all
155 * over the place for hashbase == NULL.
157 divcbinfo.ipi_hashbase = hashinit(1, M_PCB, &divcbinfo.ipi_hashmask);
158 divcbinfo.ipi_porthashbase = hashinit(1, M_PCB,
159 &divcbinfo.ipi_porthashmask);
160 divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
161 NULL, NULL, div_inpcb_init, div_inpcb_fini, UMA_ALIGN_PTR,
163 uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
164 EVENTHANDLER_REGISTER(maxsockets_change, div_zone_change,
165 NULL, EVENTHANDLER_PRI_ANY);
169 * IPPROTO_DIVERT is not in the real IP protocol number space; this
170 * function should never be called. Just in case, drop any packets.
173 div_input(struct mbuf *m, int off)
175 ipstat.ips_noproto++;
180 * Divert a packet by passing it up to the divert socket at port 'port'.
182 * Setup generic address and protocol structures for div_input routine,
183 * then pass them along with mbuf chain.
186 divert_packet(struct mbuf *m, int incoming)
192 struct sockaddr_in divsrc;
195 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
197 printf("%s: no divert tag\n", __func__);
202 if (m->m_len < sizeof(struct ip) &&
203 (m = m_pullup(m, sizeof(struct ip))) == 0)
205 ip = mtod(m, struct ip *);
207 /* Delayed checksums are currently not compatible with divert. */
208 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
209 ip->ip_len = ntohs(ip->ip_len);
211 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
212 ip->ip_len = htons(ip->ip_len);
216 * Record receive interface address, if any.
217 * But only for incoming packets.
219 bzero(&divsrc, sizeof(divsrc));
220 divsrc.sin_len = sizeof(divsrc);
221 divsrc.sin_family = AF_INET;
222 divsrc.sin_port = divert_cookie(mtag); /* record matching rule */
229 /* Find IP address for receive interface */
230 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
231 if (ifa->ifa_addr->sa_family != AF_INET)
234 ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
239 * Record the incoming interface name whenever we have one.
241 if (m->m_pkthdr.rcvif) {
243 * Hide the actual interface name in there in the
244 * sin_zero array. XXX This needs to be moved to a
245 * different sockaddr type for divert, e.g.
246 * sockaddr_div with multiple fields like
247 * sockaddr_dl. Presently we have only 7 bytes
248 * but that will do for now as most interfaces
249 * are 4 or less + 2 or less bytes for unit.
250 * There is probably a faster way of doing this,
251 * possibly taking it from the sockaddr_dl on the iface.
252 * This solves the problem of a P2P link and a LAN interface
253 * having the same address, which can result in the wrong
254 * interface being assigned to the packet when fed back
255 * into the divert socket. Theoretically if the daemon saves
256 * and re-uses the sockaddr_in as suggested in the man pages,
257 * this iface name will come along for the ride.
258 * (see div_output for the other half of this.)
260 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
261 sizeof(divsrc.sin_zero));
264 /* Put packet on socket queue, if any */
266 nport = htons((u_int16_t)divert_info(mtag));
267 INP_INFO_RLOCK(&divcbinfo);
268 LIST_FOREACH(inp, &divcb, inp_list) {
270 /* XXX why does only one socket match? */
271 if (inp->inp_lport == nport) {
272 sa = inp->inp_socket;
273 SOCKBUF_LOCK(&sa->so_rcv);
274 if (sbappendaddr_locked(&sa->so_rcv,
275 (struct sockaddr *)&divsrc, m,
276 (struct mbuf *)0) == 0) {
277 SOCKBUF_UNLOCK(&sa->so_rcv);
278 sa = NULL; /* force mbuf reclaim below */
280 sorwakeup_locked(sa);
286 INP_INFO_RUNLOCK(&divcbinfo);
289 ipstat.ips_noproto++;
290 ipstat.ips_delivered--;
295 * Deliver packet back into the IP processing machinery.
297 * If no address specified, or address is 0.0.0.0, send to ip_output();
298 * otherwise, send to ip_input() and mark as having been received on
299 * the interface with that address.
302 div_output(struct socket *so, struct mbuf *m, struct sockaddr_in *sin,
303 struct mbuf *control)
306 struct divert_tag *dt;
310 * An mbuf may hasn't come from userland, but we pretend
313 m->m_pkthdr.rcvif = NULL;
317 m_freem(control); /* XXX */
319 if ((mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL)) == NULL) {
320 mtag = m_tag_get(PACKET_TAG_DIVERT, sizeof(struct divert_tag),
326 dt = (struct divert_tag *)(mtag+1);
327 m_tag_prepend(m, mtag);
329 dt = (struct divert_tag *)(mtag+1);
331 /* Loopback avoidance and state recovery */
335 dt->cookie = sin->sin_port;
337 * Find receive interface with the given name, stuffed
338 * (if it exists) in the sin_zero[] field.
339 * The name is user supplied data so don't trust its size
340 * or that it is zero terminated.
342 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
344 if ( i > 0 && i < sizeof(sin->sin_zero))
345 m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
348 /* Reinject packet into the system as incoming or outgoing */
349 if (!sin || sin->sin_addr.s_addr == 0) {
350 struct ip *const ip = mtod(m, struct ip *);
353 dt->info |= IP_FW_DIVERT_OUTPUT_FLAG;
354 INP_INFO_WLOCK(&divcbinfo);
358 * Don't allow both user specified and setsockopt options,
359 * and don't allow packet length sizes that will crash
361 if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
362 ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
366 /* Convert fields to host order for ip_output() */
367 ip->ip_len = ntohs(ip->ip_len);
368 ip->ip_off = ntohs(ip->ip_off);
370 /* Send packet to output processing */
371 ipstat.ips_rawout++; /* XXX */
374 mac_create_mbuf_from_inpcb(inp, m);
377 inp->inp_options, NULL,
378 ((so->so_options & SO_DONTROUTE) ?
380 IP_ALLOWBROADCAST | IP_RAWOUTPUT,
381 inp->inp_moptions, NULL);
384 INP_INFO_WUNLOCK(&divcbinfo);
386 dt->info |= IP_FW_DIVERT_LOOPBACK_FLAG;
387 if (m->m_pkthdr.rcvif == NULL) {
389 * No luck with the name, check by IP address.
390 * Clear the port and the ifname to make sure
391 * there are no distractions for ifa_ifwithaddr.
395 bzero(sin->sin_zero, sizeof(sin->sin_zero));
397 ifa = ifa_ifwithaddr((struct sockaddr *) sin);
399 error = EADDRNOTAVAIL;
402 m->m_pkthdr.rcvif = ifa->ifa_ifp;
406 mac_create_mbuf_from_socket(so, m);
409 /* Send packet to input processing */
421 div_attach(struct socket *so, int proto, struct thread *td)
427 KASSERT(inp == NULL, ("div_attach: inp != NULL"));
429 error = priv_check(td, PRIV_NETINET_DIVERT);
433 error = soreserve(so, div_sendspace, div_recvspace);
436 INP_INFO_WLOCK(&divcbinfo);
437 error = in_pcballoc(so, &divcbinfo);
439 INP_INFO_WUNLOCK(&divcbinfo);
442 inp = (struct inpcb *)so->so_pcb;
443 INP_INFO_WUNLOCK(&divcbinfo);
444 inp->inp_ip_p = proto;
445 inp->inp_vflag |= INP_IPV4;
446 inp->inp_flags |= INP_HDRINCL;
452 div_detach(struct socket *so)
457 KASSERT(inp != NULL, ("div_detach: inp == NULL"));
458 INP_INFO_WLOCK(&divcbinfo);
462 INP_INFO_WUNLOCK(&divcbinfo);
466 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
472 KASSERT(inp != NULL, ("div_bind: inp == NULL"));
473 /* in_pcbbind assumes that nam is a sockaddr_in
474 * and in_pcbbind requires a valid address. Since divert
475 * sockets don't we need to make sure the address is
476 * filled in properly.
477 * XXX -- divert should not be abusing in_pcbind
478 * and should probably have its own family.
480 if (nam->sa_family != AF_INET)
482 ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
483 INP_INFO_WLOCK(&divcbinfo);
485 error = in_pcbbind(inp, nam, td->td_ucred);
487 INP_INFO_WUNLOCK(&divcbinfo);
492 div_shutdown(struct socket *so)
497 KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
505 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
506 struct mbuf *control, struct thread *td)
508 /* Packet must have a header (but that's about it) */
509 if (m->m_len < sizeof (struct ip) &&
510 (m = m_pullup(m, sizeof (struct ip))) == 0) {
511 ipstat.ips_toosmall++;
517 return div_output(so, m, (struct sockaddr_in *)nam, control);
521 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
523 struct in_addr faddr;
525 faddr = ((struct sockaddr_in *)sa)->sin_addr;
526 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
528 if (PRC_IS_REDIRECT(cmd))
533 div_pcblist(SYSCTL_HANDLER_ARGS)
536 struct inpcb *inp, **inp_list;
541 * The process of preparing the TCB list is too time-consuming and
542 * resource-intensive to repeat twice on every request.
544 if (req->oldptr == 0) {
545 n = divcbinfo.ipi_count;
546 req->oldidx = 2 * (sizeof xig)
547 + (n + n/8) * sizeof(struct xinpcb);
551 if (req->newptr != 0)
555 * OK, now we're committed to doing something.
557 INP_INFO_RLOCK(&divcbinfo);
558 gencnt = divcbinfo.ipi_gencnt;
559 n = divcbinfo.ipi_count;
560 INP_INFO_RUNLOCK(&divcbinfo);
562 error = sysctl_wire_old_buffer(req,
563 2 * sizeof(xig) + n*sizeof(struct xinpcb));
567 xig.xig_len = sizeof xig;
569 xig.xig_gen = gencnt;
570 xig.xig_sogen = so_gencnt;
571 error = SYSCTL_OUT(req, &xig, sizeof xig);
575 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
579 INP_INFO_RLOCK(&divcbinfo);
580 for (inp = LIST_FIRST(divcbinfo.ipi_listhead), i = 0; inp && i < n;
581 inp = LIST_NEXT(inp, inp_list)) {
583 if (inp->inp_gencnt <= gencnt &&
584 cr_canseesocket(req->td->td_ucred, inp->inp_socket) == 0)
588 INP_INFO_RUNLOCK(&divcbinfo);
592 for (i = 0; i < n; i++) {
595 if (inp->inp_gencnt <= gencnt) {
597 bzero(&xi, sizeof(xi));
598 xi.xi_len = sizeof xi;
599 /* XXX should avoid extra copy */
600 bcopy(inp, &xi.xi_inp, sizeof *inp);
602 sotoxsocket(inp->inp_socket, &xi.xi_socket);
604 error = SYSCTL_OUT(req, &xi, sizeof xi);
610 * Give the user an updated idea of our state.
611 * If the generation differs from what we told
612 * her before, she knows that something happened
613 * while we were processing this request, and it
614 * might be necessary to retry.
616 INP_INFO_RLOCK(&divcbinfo);
617 xig.xig_gen = divcbinfo.ipi_gencnt;
618 xig.xig_sogen = so_gencnt;
619 xig.xig_count = divcbinfo.ipi_count;
620 INP_INFO_RUNLOCK(&divcbinfo);
621 error = SYSCTL_OUT(req, &xig, sizeof xig);
623 free(inp_list, M_TEMP);
628 SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
629 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
630 div_pcblist, "S,xinpcb", "List of active divert sockets");
633 struct pr_usrreqs div_usrreqs = {
634 .pru_attach = div_attach,
635 .pru_bind = div_bind,
636 .pru_control = in_control,
637 .pru_detach = div_detach,
638 .pru_peeraddr = in_getpeeraddr,
639 .pru_send = div_send,
640 .pru_shutdown = div_shutdown,
641 .pru_sockaddr = in_getsockaddr,
642 .pru_sosetlabel = in_pcbsosetlabel
645 struct protosw div_protosw = {
647 .pr_protocol = IPPROTO_DIVERT,
648 .pr_flags = PR_ATOMIC|PR_ADDR,
649 .pr_input = div_input,
650 .pr_ctlinput = div_ctlinput,
651 .pr_ctloutput = ip_ctloutput,
653 .pr_usrreqs = &div_usrreqs
657 div_modevent(module_t mod, int type, void *unused)
665 * Protocol will be initialized by pf_proto_register().
666 * We don't have to register ip_protox because we are not
667 * a true IP protocol that goes over the wire.
669 err = pf_proto_register(PF_INET, &div_protosw);
670 ip_divert_ptr = divert_packet;
674 * IPDIVERT may normally not be unloaded because of the
675 * potential race conditions. Tell kldunload we can't be
676 * unloaded unless the unload is forced.
684 * Module ipdivert can only be unloaded if no sockets are
685 * connected. Maybe this can be changed later to forcefully
686 * disconnect any open sockets.
688 * XXXRW: Note that there is a slight race here, as a new
689 * socket open request could be spinning on the lock and then
690 * we destroy the lock.
692 INP_INFO_WLOCK(&divcbinfo);
693 n = divcbinfo.ipi_count;
696 INP_INFO_WUNLOCK(&divcbinfo);
699 ip_divert_ptr = NULL;
700 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
701 INP_INFO_WUNLOCK(&divcbinfo);
702 INP_INFO_LOCK_DESTROY(&divcbinfo);
703 uma_zdestroy(divcbinfo.ipi_zone);
712 static moduledata_t ipdivertmod = {
718 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
719 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
720 MODULE_VERSION(ipdivert, 1);