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/ipfw/ip_fw_private.h>
50 #include <netinet/tcp.h>
51 #include <netinet/udp.h>
53 #include <machine/in_cksum.h> /* XXX for in_cksum */
55 static VNET_DEFINE(eventhandler_tag, ifaddr_event_tag);
56 #define V_ifaddr_event_tag VNET(ifaddr_event_tag)
59 ifaddr_change(void *arg __unused, struct ifnet *ifp)
63 struct ip_fw_chain *chain;
65 chain = &V_layer3_chain;
67 /* Check every nat entry... */
68 LIST_FOREACH(ptr, &chain->nat, _next) {
69 /* ...using nic 'ifp->if_xname' as dynamic alias address. */
70 if (strncmp(ptr->if_name, ifp->if_xname, IF_NAMESIZE) != 0)
73 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
74 if (ifa->ifa_addr == NULL)
76 if (ifa->ifa_addr->sa_family != AF_INET)
78 ptr->ip = ((struct sockaddr_in *)
79 (ifa->ifa_addr))->sin_addr;
80 LibAliasSetAddress(ptr->lib, ptr->ip);
88 * delete the pointers for nat entry ix, or all of them if ix < 0
91 flush_nat_ptrs(struct ip_fw_chain *chain, const int ix)
96 IPFW_WLOCK_ASSERT(chain);
97 for (i = 0; i < chain->n_rules; i++) {
98 cmd = (ipfw_insn_nat *)ACTION_PTR(chain->map[i]);
99 /* XXX skip log and the like ? */
100 if (cmd->o.opcode == O_NAT && cmd->nat != NULL &&
101 (ix < 0 || cmd->nat->id == ix))
107 del_redir_spool_cfg(struct cfg_nat *n, struct redir_chain *head)
109 struct cfg_redir *r, *tmp_r;
110 struct cfg_spool *s, *tmp_s;
113 LIST_FOREACH_SAFE(r, head, _next, tmp_r) {
114 num = 1; /* Number of alias_link to delete. */
121 /* Delete all libalias redirect entry. */
122 for (i = 0; i < num; i++)
123 LibAliasRedirectDelete(n->lib, r->alink[i]);
124 /* Del spool cfg if any. */
125 LIST_FOREACH_SAFE(s, &r->spool_chain, _next, tmp_s) {
126 LIST_REMOVE(s, _next);
129 free(r->alink, M_IPFW);
130 LIST_REMOVE(r, _next);
134 printf("unknown redirect mode: %u\n", r->mode);
135 /* XXX - panic?!?!? */
142 add_redir_spool_cfg(char *buf, struct cfg_nat *ptr)
144 struct cfg_redir *r, *ser_r;
145 struct cfg_spool *s, *ser_s;
148 for (cnt = 0, off = 0; cnt < ptr->redir_cnt; cnt++) {
149 ser_r = (struct cfg_redir *)&buf[off];
150 r = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
151 memcpy(r, ser_r, SOF_REDIR);
152 LIST_INIT(&r->spool_chain);
154 r->alink = malloc(sizeof(struct alias_link *) * r->pport_cnt,
155 M_IPFW, M_WAITOK | M_ZERO);
158 r->alink[0] = LibAliasRedirectAddr(ptr->lib, r->laddr,
162 for (i = 0 ; i < r->pport_cnt; i++) {
163 /* If remotePort is all ports, set it to 0. */
164 u_short remotePortCopy = r->rport + i;
165 if (r->rport_cnt == 1 && r->rport == 0)
167 r->alink[i] = LibAliasRedirectPort(ptr->lib,
168 r->laddr, htons(r->lport + i), r->raddr,
169 htons(remotePortCopy), r->paddr,
170 htons(r->pport + i), r->proto);
171 if (r->alink[i] == NULL) {
178 r->alink[0] = LibAliasRedirectProto(ptr->lib ,r->laddr,
179 r->raddr, r->paddr, r->proto);
182 printf("unknown redirect mode: %u\n", r->mode);
185 /* XXX perhaps return an error instead of panic ? */
186 if (r->alink[0] == NULL)
187 panic("LibAliasRedirect* returned NULL");
188 /* LSNAT handling. */
189 for (i = 0; i < r->spool_cnt; i++) {
190 ser_s = (struct cfg_spool *)&buf[off];
191 s = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
192 memcpy(s, ser_s, SOF_SPOOL);
193 LibAliasAddServer(ptr->lib, r->alink[0],
194 s->addr, htons(s->port));
196 /* Hook spool entry. */
197 LIST_INSERT_HEAD(&r->spool_chain, s, _next);
199 /* And finally hook this redir entry. */
200 LIST_INSERT_HEAD(&ptr->redir_chain, r, _next);
205 ipfw_nat(struct ip_fw_args *args, struct cfg_nat *t, struct mbuf *m)
209 /* XXX - libalias duct tape */
210 int ldt, retval, found;
211 struct ip_fw_chain *chain;
216 mcl = m_megapullup(m, m->m_pkthdr.len);
221 ip = mtod(mcl, struct ip *);
224 * XXX - Libalias checksum offload 'duct tape':
226 * locally generated packets have only pseudo-header checksum
227 * calculated and libalias will break it[1], so mark them for
228 * later fix. Moreover there are cases when libalias modifies
229 * tcp packet data[2], mark them for later fix too.
231 * [1] libalias was never meant to run in kernel, so it does
232 * not have any knowledge about checksum offloading, and
233 * expects a packet with a full internet checksum.
234 * Unfortunately, packets generated locally will have just the
235 * pseudo header calculated, and when libalias tries to adjust
236 * the checksum it will actually compute a wrong value.
238 * [2] when libalias modifies tcp's data content, full TCP
239 * checksum has to be recomputed: the problem is that
240 * libalias does not have any idea about checksum offloading.
241 * To work around this, we do not do checksumming in LibAlias,
242 * but only mark the packets in th_x2 field. If we receive a
243 * marked packet, we calculate correct checksum for it
244 * aware of offloading. Why such a terrible hack instead of
245 * recalculating checksum for each packet?
246 * Because the previous checksum was not checked!
247 * Recalculating checksums for EVERY packet will hide ALL
248 * transmission errors. Yes, marked packets still suffer from
249 * this problem. But, sigh, natd(8) has this problem, too.
251 * TODO: -make libalias mbuf aware (so
252 * it can handle delayed checksum and tso)
255 if (mcl->m_pkthdr.rcvif == NULL &&
256 mcl->m_pkthdr.csum_flags & CSUM_DELAY_DATA)
259 c = mtod(mcl, char *);
261 /* Check if this is 'global' instance */
263 if (args->oif == NULL) {
264 /* Wrong direction, skip processing */
270 chain = &V_layer3_chain;
272 /* Check every nat entry... */
273 LIST_FOREACH(t, &chain->nat, _next) {
274 if ((t->mode & PKT_ALIAS_SKIP_GLOBAL) != 0)
276 retval = LibAliasOutTry(t->lib, c,
277 mcl->m_len + M_TRAILINGSPACE(mcl), 0);
278 if (retval == PKT_ALIAS_OK) {
279 /* Nat instance recognises state */
286 /* No instance found, return ignore */
291 if (args->oif == NULL)
292 retval = LibAliasIn(t->lib, c,
293 mcl->m_len + M_TRAILINGSPACE(mcl));
295 retval = LibAliasOut(t->lib, c,
296 mcl->m_len + M_TRAILINGSPACE(mcl));
300 * We drop packet when:
301 * 1. libalias returns PKT_ALIAS_ERROR;
302 * 2. For incoming packets:
303 * a) for unresolved fragments;
304 * b) libalias returns PKT_ALIAS_IGNORED and
305 * PKT_ALIAS_DENY_INCOMING flag is set.
307 if (retval == PKT_ALIAS_ERROR ||
308 (args->oif == NULL && (retval == PKT_ALIAS_UNRESOLVED_FRAGMENT ||
309 (retval == PKT_ALIAS_IGNORED &&
310 (t->mode & PKT_ALIAS_DENY_INCOMING) != 0)))) {
311 /* XXX - should i add some logging? */
317 if (retval == PKT_ALIAS_RESPOND)
318 m->m_flags |= M_SKIP_FIREWALL;
319 mcl->m_pkthdr.len = mcl->m_len = ntohs(ip->ip_len);
322 * XXX - libalias checksum offload
323 * 'duct tape' (see above)
326 if ((ip->ip_off & htons(IP_OFFMASK)) == 0 &&
327 ip->ip_p == IPPROTO_TCP) {
330 th = (struct tcphdr *)(ip + 1);
340 ip->ip_len = ntohs(ip->ip_len);
341 cksum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
342 htons(ip->ip_p + ip->ip_len - (ip->ip_hl << 2)));
346 th = (struct tcphdr *)(ip + 1);
348 * Maybe it was set in
353 mcl->m_pkthdr.csum_data =
354 offsetof(struct tcphdr, th_sum);
357 uh = (struct udphdr *)(ip + 1);
359 mcl->m_pkthdr.csum_data =
360 offsetof(struct udphdr, uh_sum);
363 /* No hw checksum offloading: do it ourselves */
364 if ((mcl->m_pkthdr.csum_flags & CSUM_DELAY_DATA) == 0) {
365 in_delayed_cksum(mcl);
366 mcl->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
368 ip->ip_len = htons(ip->ip_len);
374 static struct cfg_nat *
375 lookup_nat(struct nat_list *l, int nat_id)
379 LIST_FOREACH(res, l, _next) {
380 if (res->id == nat_id)
387 ipfw_nat_cfg(struct sockopt *sopt)
389 struct cfg_nat *cfg, *ptr;
391 struct ip_fw_chain *chain = &V_layer3_chain;
393 int gencnt, error = 0;
395 len = sopt->sopt_valsize;
396 buf = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
397 if ((error = sooptcopyin(sopt, buf, len, sizeof(struct cfg_nat))) != 0)
400 cfg = (struct cfg_nat *)buf;
407 * Find/create nat rule.
410 gencnt = chain->gencnt;
411 ptr = lookup_nat(&chain->nat, cfg->id);
414 /* New rule: allocate and init new instance. */
415 ptr = malloc(sizeof(struct cfg_nat), M_IPFW, M_WAITOK | M_ZERO);
416 ptr->lib = LibAliasInit(NULL);
417 LIST_INIT(&ptr->redir_chain);
419 /* Entry already present: temporarily unhook it. */
420 LIST_REMOVE(ptr, _next);
421 flush_nat_ptrs(chain, cfg->id);
426 * Basic nat configuration.
430 * XXX - what if this rule doesn't nat any ip and just
432 * do we set aliasaddress to 0.0.0.0?
435 ptr->redir_cnt = cfg->redir_cnt;
436 ptr->mode = cfg->mode;
437 LibAliasSetMode(ptr->lib, cfg->mode, cfg->mode);
438 LibAliasSetAddress(ptr->lib, ptr->ip);
439 memcpy(ptr->if_name, cfg->if_name, IF_NAMESIZE);
442 * Redir and LSNAT configuration.
444 /* Delete old cfgs. */
445 del_redir_spool_cfg(ptr, &ptr->redir_chain);
446 /* Add new entries. */
447 add_redir_spool_cfg(&buf[(sizeof(struct cfg_nat))], ptr);
450 /* Extra check to avoid race with another ipfw_nat_cfg() */
451 if (gencnt != chain->gencnt &&
452 ((cfg = lookup_nat(&chain->nat, ptr->id)) != NULL))
453 LIST_REMOVE(cfg, _next);
454 LIST_INSERT_HEAD(&chain->nat, ptr, _next);
464 ipfw_nat_del(struct sockopt *sopt)
467 struct ip_fw_chain *chain = &V_layer3_chain;
470 sooptcopyin(sopt, &i, sizeof i, sizeof i);
473 ptr = lookup_nat(&chain->nat, i);
478 LIST_REMOVE(ptr, _next);
479 flush_nat_ptrs(chain, i);
481 del_redir_spool_cfg(ptr, &ptr->redir_chain);
482 LibAliasUninit(ptr->lib);
488 ipfw_nat_get_cfg(struct sockopt *sopt)
490 struct ip_fw_chain *chain = &V_layer3_chain;
495 int gencnt, nat_cnt, len, error;
498 len = sizeof(nat_cnt);
502 gencnt = chain->gencnt;
503 /* Estimate memory amount */
504 LIST_FOREACH(n, &chain->nat, _next) {
506 len += sizeof(struct cfg_nat);
507 LIST_FOREACH(r, &n->redir_chain, _next) {
508 len += sizeof(struct cfg_redir);
509 LIST_FOREACH(s, &r->spool_chain, _next)
510 len += sizeof(struct cfg_spool);
515 data = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
516 bcopy(&nat_cnt, data, sizeof(nat_cnt));
519 len = sizeof(nat_cnt);
522 if (gencnt != chain->gencnt) {
526 /* Serialize all the data. */
527 LIST_FOREACH(n, &chain->nat, _next) {
528 bcopy(n, &data[len], sizeof(struct cfg_nat));
529 len += sizeof(struct cfg_nat);
530 LIST_FOREACH(r, &n->redir_chain, _next) {
531 bcopy(r, &data[len], sizeof(struct cfg_redir));
532 len += sizeof(struct cfg_redir);
533 LIST_FOREACH(s, &r->spool_chain, _next) {
534 bcopy(s, &data[len], sizeof(struct cfg_spool));
535 len += sizeof(struct cfg_spool);
541 error = sooptcopyout(sopt, data, len);
548 ipfw_nat_get_log(struct sockopt *sopt)
553 struct ip_fw_chain *chain;
555 chain = &V_layer3_chain;
558 /* one pass to count, one to copy the data */
560 LIST_FOREACH(ptr, &chain->nat, _next) {
561 if (ptr->lib->logDesc == NULL)
565 size = i * (LIBALIAS_BUF_SIZE + sizeof(int));
566 data = malloc(size, M_IPFW, M_NOWAIT | M_ZERO);
572 LIST_FOREACH(ptr, &chain->nat, _next) {
573 if (ptr->lib->logDesc == NULL)
575 bcopy(&ptr->id, &data[i], sizeof(int));
577 bcopy(ptr->lib->logDesc, &data[i], LIBALIAS_BUF_SIZE);
578 i += LIBALIAS_BUF_SIZE;
581 sooptcopyout(sopt, data, size);
590 IPFW_WLOCK(&V_layer3_chain);
591 /* init ipfw hooks */
592 ipfw_nat_ptr = ipfw_nat;
593 lookup_nat_ptr = lookup_nat;
594 ipfw_nat_cfg_ptr = ipfw_nat_cfg;
595 ipfw_nat_del_ptr = ipfw_nat_del;
596 ipfw_nat_get_cfg_ptr = ipfw_nat_get_cfg;
597 ipfw_nat_get_log_ptr = ipfw_nat_get_log;
598 IPFW_WUNLOCK(&V_layer3_chain);
599 V_ifaddr_event_tag = EVENTHANDLER_REGISTER(
600 ifaddr_event, ifaddr_change,
601 NULL, EVENTHANDLER_PRI_ANY);
605 ipfw_nat_destroy(void)
607 struct cfg_nat *ptr, *ptr_temp;
608 struct ip_fw_chain *chain;
610 chain = &V_layer3_chain;
612 LIST_FOREACH_SAFE(ptr, &chain->nat, _next, ptr_temp) {
613 LIST_REMOVE(ptr, _next);
614 del_redir_spool_cfg(ptr, &ptr->redir_chain);
615 LibAliasUninit(ptr->lib);
618 EVENTHANDLER_DEREGISTER(ifaddr_event, V_ifaddr_event_tag);
619 flush_nat_ptrs(chain, -1 /* flush all */);
620 /* deregister ipfw_nat */
622 lookup_nat_ptr = NULL;
623 ipfw_nat_cfg_ptr = NULL;
624 ipfw_nat_del_ptr = NULL;
625 ipfw_nat_get_cfg_ptr = NULL;
626 ipfw_nat_get_log_ptr = NULL;
631 ipfw_nat_modevent(module_t mod, int type, void *unused)
651 static moduledata_t ipfw_nat_mod = {
657 DECLARE_MODULE(ipfw_nat, ipfw_nat_mod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
658 MODULE_DEPEND(ipfw_nat, libalias, 1, 1, 1);
659 MODULE_DEPEND(ipfw_nat, ipfw, 2, 2, 2);
660 MODULE_VERSION(ipfw_nat, 1);