2 * Copyright (c) 2008 Paolo Pisati
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.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/eventhandler.h>
33 #include <sys/malloc.h>
34 #include <sys/kernel.h>
36 #include <sys/module.h>
37 #include <sys/rwlock.h>
39 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
41 #include <netinet/libalias/alias.h>
42 #include <netinet/libalias/alias_local.h>
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <netinet/ip_var.h>
48 #include <netinet/ip_fw.h>
49 #include <netinet/tcp.h>
50 #include <netinet/udp.h>
52 #include <netpfil/ipfw/ip_fw_private.h>
54 #include <machine/in_cksum.h> /* XXX for in_cksum */
56 static VNET_DEFINE(eventhandler_tag, ifaddr_event_tag);
57 #define V_ifaddr_event_tag VNET(ifaddr_event_tag)
60 ifaddr_change(void *arg __unused, struct ifnet *ifp)
64 struct ip_fw_chain *chain;
66 chain = &V_layer3_chain;
68 /* Check every nat entry... */
69 LIST_FOREACH(ptr, &chain->nat, _next) {
70 /* ...using nic 'ifp->if_xname' as dynamic alias address. */
71 if (strncmp(ptr->if_name, ifp->if_xname, IF_NAMESIZE) != 0)
74 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
75 if (ifa->ifa_addr == NULL)
77 if (ifa->ifa_addr->sa_family != AF_INET)
79 ptr->ip = ((struct sockaddr_in *)
80 (ifa->ifa_addr))->sin_addr;
81 LibAliasSetAddress(ptr->lib, ptr->ip);
89 * delete the pointers for nat entry ix, or all of them if ix < 0
92 flush_nat_ptrs(struct ip_fw_chain *chain, const int ix)
97 IPFW_WLOCK_ASSERT(chain);
98 for (i = 0; i < chain->n_rules; i++) {
99 cmd = (ipfw_insn_nat *)ACTION_PTR(chain->map[i]);
100 /* XXX skip log and the like ? */
101 if (cmd->o.opcode == O_NAT && cmd->nat != NULL &&
102 (ix < 0 || cmd->nat->id == ix))
108 del_redir_spool_cfg(struct cfg_nat *n, struct redir_chain *head)
110 struct cfg_redir *r, *tmp_r;
111 struct cfg_spool *s, *tmp_s;
114 LIST_FOREACH_SAFE(r, head, _next, tmp_r) {
115 num = 1; /* Number of alias_link to delete. */
122 /* Delete all libalias redirect entry. */
123 for (i = 0; i < num; i++)
124 LibAliasRedirectDelete(n->lib, r->alink[i]);
125 /* Del spool cfg if any. */
126 LIST_FOREACH_SAFE(s, &r->spool_chain, _next, tmp_s) {
127 LIST_REMOVE(s, _next);
130 free(r->alink, M_IPFW);
131 LIST_REMOVE(r, _next);
135 printf("unknown redirect mode: %u\n", r->mode);
136 /* XXX - panic?!?!? */
143 add_redir_spool_cfg(char *buf, struct cfg_nat *ptr)
145 struct cfg_redir *r, *ser_r;
146 struct cfg_spool *s, *ser_s;
149 for (cnt = 0, off = 0; cnt < ptr->redir_cnt; cnt++) {
150 ser_r = (struct cfg_redir *)&buf[off];
151 r = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
152 memcpy(r, ser_r, SOF_REDIR);
153 LIST_INIT(&r->spool_chain);
155 r->alink = malloc(sizeof(struct alias_link *) * r->pport_cnt,
156 M_IPFW, M_WAITOK | M_ZERO);
159 r->alink[0] = LibAliasRedirectAddr(ptr->lib, r->laddr,
163 for (i = 0 ; i < r->pport_cnt; i++) {
164 /* If remotePort is all ports, set it to 0. */
165 u_short remotePortCopy = r->rport + i;
166 if (r->rport_cnt == 1 && r->rport == 0)
168 r->alink[i] = LibAliasRedirectPort(ptr->lib,
169 r->laddr, htons(r->lport + i), r->raddr,
170 htons(remotePortCopy), r->paddr,
171 htons(r->pport + i), r->proto);
172 if (r->alink[i] == NULL) {
179 r->alink[0] = LibAliasRedirectProto(ptr->lib ,r->laddr,
180 r->raddr, r->paddr, r->proto);
183 printf("unknown redirect mode: %u\n", r->mode);
186 /* XXX perhaps return an error instead of panic ? */
187 if (r->alink[0] == NULL)
188 panic("LibAliasRedirect* returned NULL");
189 /* LSNAT handling. */
190 for (i = 0; i < r->spool_cnt; i++) {
191 ser_s = (struct cfg_spool *)&buf[off];
192 s = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
193 memcpy(s, ser_s, SOF_SPOOL);
194 LibAliasAddServer(ptr->lib, r->alink[0],
195 s->addr, htons(s->port));
197 /* Hook spool entry. */
198 LIST_INSERT_HEAD(&r->spool_chain, s, _next);
200 /* And finally hook this redir entry. */
201 LIST_INSERT_HEAD(&ptr->redir_chain, r, _next);
206 * ipfw_nat - perform mbuf header translation.
208 * Note V_layer3_chain has to be locked while calling ipfw_nat() in
209 * 'global' operation mode (t == NULL).
213 ipfw_nat(struct ip_fw_args *args, struct cfg_nat *t, struct mbuf *m)
217 /* XXX - libalias duct tape */
218 int ldt, retval, found;
219 struct ip_fw_chain *chain;
224 mcl = m_megapullup(m, m->m_pkthdr.len);
229 ip = mtod(mcl, struct ip *);
232 * XXX - Libalias checksum offload 'duct tape':
234 * locally generated packets have only pseudo-header checksum
235 * calculated and libalias will break it[1], so mark them for
236 * later fix. Moreover there are cases when libalias modifies
237 * tcp packet data[2], mark them for later fix too.
239 * [1] libalias was never meant to run in kernel, so it does
240 * not have any knowledge about checksum offloading, and
241 * expects a packet with a full internet checksum.
242 * Unfortunately, packets generated locally will have just the
243 * pseudo header calculated, and when libalias tries to adjust
244 * the checksum it will actually compute a wrong value.
246 * [2] when libalias modifies tcp's data content, full TCP
247 * checksum has to be recomputed: the problem is that
248 * libalias does not have any idea about checksum offloading.
249 * To work around this, we do not do checksumming in LibAlias,
250 * but only mark the packets in th_x2 field. If we receive a
251 * marked packet, we calculate correct checksum for it
252 * aware of offloading. Why such a terrible hack instead of
253 * recalculating checksum for each packet?
254 * Because the previous checksum was not checked!
255 * Recalculating checksums for EVERY packet will hide ALL
256 * transmission errors. Yes, marked packets still suffer from
257 * this problem. But, sigh, natd(8) has this problem, too.
259 * TODO: -make libalias mbuf aware (so
260 * it can handle delayed checksum and tso)
263 if (mcl->m_pkthdr.rcvif == NULL &&
264 mcl->m_pkthdr.csum_flags & CSUM_DELAY_DATA)
267 c = mtod(mcl, char *);
269 /* Check if this is 'global' instance */
271 if (args->oif == NULL) {
272 /* Wrong direction, skip processing */
278 chain = &V_layer3_chain;
279 IPFW_RLOCK_ASSERT(chain);
280 /* Check every nat entry... */
281 LIST_FOREACH(t, &chain->nat, _next) {
282 if ((t->mode & PKT_ALIAS_SKIP_GLOBAL) != 0)
284 retval = LibAliasOutTry(t->lib, c,
285 mcl->m_len + M_TRAILINGSPACE(mcl), 0);
286 if (retval == PKT_ALIAS_OK) {
287 /* Nat instance recognises state */
293 /* No instance found, return ignore */
298 if (args->oif == NULL)
299 retval = LibAliasIn(t->lib, c,
300 mcl->m_len + M_TRAILINGSPACE(mcl));
302 retval = LibAliasOut(t->lib, c,
303 mcl->m_len + M_TRAILINGSPACE(mcl));
307 * We drop packet when:
308 * 1. libalias returns PKT_ALIAS_ERROR;
309 * 2. For incoming packets:
310 * a) for unresolved fragments;
311 * b) libalias returns PKT_ALIAS_IGNORED and
312 * PKT_ALIAS_DENY_INCOMING flag is set.
314 if (retval == PKT_ALIAS_ERROR ||
315 (args->oif == NULL && (retval == PKT_ALIAS_UNRESOLVED_FRAGMENT ||
316 (retval == PKT_ALIAS_IGNORED &&
317 (t->mode & PKT_ALIAS_DENY_INCOMING) != 0)))) {
318 /* XXX - should i add some logging? */
324 if (retval == PKT_ALIAS_RESPOND)
325 mcl->m_flags |= M_SKIP_FIREWALL;
326 mcl->m_pkthdr.len = mcl->m_len = ntohs(ip->ip_len);
329 * XXX - libalias checksum offload
330 * 'duct tape' (see above)
333 if ((ip->ip_off & htons(IP_OFFMASK)) == 0 &&
334 ip->ip_p == IPPROTO_TCP) {
337 th = (struct tcphdr *)(ip + 1);
347 ip->ip_len = ntohs(ip->ip_len);
348 cksum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
349 htons(ip->ip_p + ip->ip_len - (ip->ip_hl << 2)));
353 th = (struct tcphdr *)(ip + 1);
355 * Maybe it was set in
360 mcl->m_pkthdr.csum_data =
361 offsetof(struct tcphdr, th_sum);
364 uh = (struct udphdr *)(ip + 1);
366 mcl->m_pkthdr.csum_data =
367 offsetof(struct udphdr, uh_sum);
370 /* No hw checksum offloading: do it ourselves */
371 if ((mcl->m_pkthdr.csum_flags & CSUM_DELAY_DATA) == 0) {
372 in_delayed_cksum(mcl);
373 mcl->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
375 ip->ip_len = htons(ip->ip_len);
381 static struct cfg_nat *
382 lookup_nat(struct nat_list *l, int nat_id)
386 LIST_FOREACH(res, l, _next) {
387 if (res->id == nat_id)
394 ipfw_nat_cfg(struct sockopt *sopt)
396 struct cfg_nat *cfg, *ptr;
398 struct ip_fw_chain *chain = &V_layer3_chain;
400 int gencnt, error = 0;
402 len = sopt->sopt_valsize;
403 buf = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
404 if ((error = sooptcopyin(sopt, buf, len, sizeof(struct cfg_nat))) != 0)
407 cfg = (struct cfg_nat *)buf;
414 * Find/create nat rule.
417 gencnt = chain->gencnt;
418 ptr = lookup_nat(&chain->nat, cfg->id);
421 /* New rule: allocate and init new instance. */
422 ptr = malloc(sizeof(struct cfg_nat), M_IPFW, M_WAITOK | M_ZERO);
423 ptr->lib = LibAliasInit(NULL);
424 LIST_INIT(&ptr->redir_chain);
426 /* Entry already present: temporarily unhook it. */
427 LIST_REMOVE(ptr, _next);
428 flush_nat_ptrs(chain, cfg->id);
433 * Basic nat configuration.
437 * XXX - what if this rule doesn't nat any ip and just
439 * do we set aliasaddress to 0.0.0.0?
442 ptr->redir_cnt = cfg->redir_cnt;
443 ptr->mode = cfg->mode;
444 LibAliasSetMode(ptr->lib, cfg->mode, cfg->mode);
445 LibAliasSetAddress(ptr->lib, ptr->ip);
446 memcpy(ptr->if_name, cfg->if_name, IF_NAMESIZE);
449 * Redir and LSNAT configuration.
451 /* Delete old cfgs. */
452 del_redir_spool_cfg(ptr, &ptr->redir_chain);
453 /* Add new entries. */
454 add_redir_spool_cfg(&buf[(sizeof(struct cfg_nat))], ptr);
457 /* Extra check to avoid race with another ipfw_nat_cfg() */
458 if (gencnt != chain->gencnt &&
459 ((cfg = lookup_nat(&chain->nat, ptr->id)) != NULL))
460 LIST_REMOVE(cfg, _next);
461 LIST_INSERT_HEAD(&chain->nat, ptr, _next);
471 ipfw_nat_del(struct sockopt *sopt)
474 struct ip_fw_chain *chain = &V_layer3_chain;
477 sooptcopyin(sopt, &i, sizeof i, sizeof i);
480 ptr = lookup_nat(&chain->nat, i);
485 LIST_REMOVE(ptr, _next);
486 flush_nat_ptrs(chain, i);
488 del_redir_spool_cfg(ptr, &ptr->redir_chain);
489 LibAliasUninit(ptr->lib);
495 ipfw_nat_get_cfg(struct sockopt *sopt)
497 struct ip_fw_chain *chain = &V_layer3_chain;
502 int gencnt, nat_cnt, len, error;
505 len = sizeof(nat_cnt);
509 gencnt = chain->gencnt;
510 /* Estimate memory amount */
511 LIST_FOREACH(n, &chain->nat, _next) {
513 len += sizeof(struct cfg_nat);
514 LIST_FOREACH(r, &n->redir_chain, _next) {
515 len += sizeof(struct cfg_redir);
516 LIST_FOREACH(s, &r->spool_chain, _next)
517 len += sizeof(struct cfg_spool);
522 data = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
523 bcopy(&nat_cnt, data, sizeof(nat_cnt));
526 len = sizeof(nat_cnt);
529 if (gencnt != chain->gencnt) {
533 /* Serialize all the data. */
534 LIST_FOREACH(n, &chain->nat, _next) {
535 bcopy(n, &data[len], sizeof(struct cfg_nat));
536 len += sizeof(struct cfg_nat);
537 LIST_FOREACH(r, &n->redir_chain, _next) {
538 bcopy(r, &data[len], sizeof(struct cfg_redir));
539 len += sizeof(struct cfg_redir);
540 LIST_FOREACH(s, &r->spool_chain, _next) {
541 bcopy(s, &data[len], sizeof(struct cfg_spool));
542 len += sizeof(struct cfg_spool);
548 error = sooptcopyout(sopt, data, len);
555 ipfw_nat_get_log(struct sockopt *sopt)
560 struct ip_fw_chain *chain;
562 chain = &V_layer3_chain;
565 /* one pass to count, one to copy the data */
567 LIST_FOREACH(ptr, &chain->nat, _next) {
568 if (ptr->lib->logDesc == NULL)
572 size = i * (LIBALIAS_BUF_SIZE + sizeof(int));
573 data = malloc(size, M_IPFW, M_NOWAIT | M_ZERO);
579 LIST_FOREACH(ptr, &chain->nat, _next) {
580 if (ptr->lib->logDesc == NULL)
582 bcopy(&ptr->id, &data[i], sizeof(int));
584 bcopy(ptr->lib->logDesc, &data[i], LIBALIAS_BUF_SIZE);
585 i += LIBALIAS_BUF_SIZE;
588 sooptcopyout(sopt, data, size);
597 IPFW_WLOCK(&V_layer3_chain);
598 /* init ipfw hooks */
599 ipfw_nat_ptr = ipfw_nat;
600 lookup_nat_ptr = lookup_nat;
601 ipfw_nat_cfg_ptr = ipfw_nat_cfg;
602 ipfw_nat_del_ptr = ipfw_nat_del;
603 ipfw_nat_get_cfg_ptr = ipfw_nat_get_cfg;
604 ipfw_nat_get_log_ptr = ipfw_nat_get_log;
605 IPFW_WUNLOCK(&V_layer3_chain);
606 V_ifaddr_event_tag = EVENTHANDLER_REGISTER(
607 ifaddr_event, ifaddr_change,
608 NULL, EVENTHANDLER_PRI_ANY);
612 ipfw_nat_destroy(void)
614 struct cfg_nat *ptr, *ptr_temp;
615 struct ip_fw_chain *chain;
617 chain = &V_layer3_chain;
619 LIST_FOREACH_SAFE(ptr, &chain->nat, _next, ptr_temp) {
620 LIST_REMOVE(ptr, _next);
621 del_redir_spool_cfg(ptr, &ptr->redir_chain);
622 LibAliasUninit(ptr->lib);
625 EVENTHANDLER_DEREGISTER(ifaddr_event, V_ifaddr_event_tag);
626 flush_nat_ptrs(chain, -1 /* flush all */);
627 /* deregister ipfw_nat */
629 lookup_nat_ptr = NULL;
630 ipfw_nat_cfg_ptr = NULL;
631 ipfw_nat_del_ptr = NULL;
632 ipfw_nat_get_cfg_ptr = NULL;
633 ipfw_nat_get_log_ptr = NULL;
638 ipfw_nat_modevent(module_t mod, int type, void *unused)
658 static moduledata_t ipfw_nat_mod = {
664 DECLARE_MODULE(ipfw_nat, ipfw_nat_mod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
665 MODULE_DEPEND(ipfw_nat, libalias, 1, 1, 1);
666 MODULE_DEPEND(ipfw_nat, ipfw, 2, 2, 2);
667 MODULE_VERSION(ipfw_nat, 1);