1 /*-
2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
5 *
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
8 *
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
11 *
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
15 *
16 * This software is provided ``AS IS'' without any warranties of any kind.
17 *
18 * NEW command line interface for IP firewall facility
19 *
20 * In-kernel nat support
21 */
22
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/sysctl.h>
26
27 #include "ipfw2.h"
28
29 #include <ctype.h>
30 #include <err.h>
31 #include <errno.h>
32 #include <netdb.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sysexits.h>
37
38 #include <net/if.h>
39 #include <net/if_dl.h>
40 #include <net/route.h> /* def. of struct route */
41 #include <netinet/in.h>
42 #include <netinet/ip_fw.h>
43 #include <arpa/inet.h>
44 #include <alias.h>
45
46 typedef int (nat_cb_t)(struct nat44_cfg_nat *cfg, void *arg);
47 static void nat_show_cfg(struct nat44_cfg_nat *n, void *arg);
48 static void nat_show_log(struct nat44_cfg_nat *n, void *arg);
49 static int nat_show_data(struct nat44_cfg_nat *cfg, void *arg);
50 static int natname_cmp(const void *a, const void *b);
51 static int nat_foreach(nat_cb_t *f, void *arg, int sort);
52 static int nat_get_cmd(char *name, uint16_t cmd, ipfw_obj_header **ooh);
53
54 static struct _s_x nat_params[] = {
55 { "ip", TOK_IP },
56 { "if", TOK_IF },
57 { "log", TOK_ALOG },
58 { "deny_in", TOK_DENY_INC },
59 { "same_ports", TOK_SAME_PORTS },
60 { "unreg_only", TOK_UNREG_ONLY },
61 { "unreg_cgn", TOK_UNREG_CGN },
62 { "skip_global", TOK_SKIP_GLOBAL },
63 { "reset", TOK_RESET_ADDR },
64 { "reverse", TOK_ALIAS_REV },
65 { "proxy_only", TOK_PROXY_ONLY },
66 { "port_range", TOK_PORT_ALIAS },
67 { "redirect_addr", TOK_REDIR_ADDR },
68 { "redirect_port", TOK_REDIR_PORT },
69 { "redirect_proto", TOK_REDIR_PROTO },
70 { NULL, 0 } /* terminator */
71 };
72
73
74 /*
75 * Search for interface with name "ifn", and fill n accordingly:
76 *
77 * n->ip ip address of interface "ifn"
78 * n->if_name copy of interface name "ifn"
79 */
80 static void
set_addr_dynamic(const char * ifn,struct nat44_cfg_nat * n)81 set_addr_dynamic(const char *ifn, struct nat44_cfg_nat *n)
82 {
83 size_t needed;
84 int mib[6];
85 char *buf, *lim, *next;
86 struct if_msghdr *ifm;
87 struct ifa_msghdr *ifam;
88 struct sockaddr_dl *sdl;
89 struct sockaddr_in *sin;
90 int ifIndex;
91
92 mib[0] = CTL_NET;
93 mib[1] = PF_ROUTE;
94 mib[2] = 0;
95 mib[3] = AF_INET;
96 mib[4] = NET_RT_IFLIST;
97 mib[5] = 0;
98 /*
99 * Get interface data.
100 */
101 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
102 err(1, "iflist-sysctl-estimate");
103 buf = safe_calloc(1, needed);
104 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
105 err(1, "iflist-sysctl-get");
106 lim = buf + needed;
107 /*
108 * Loop through interfaces until one with
109 * given name is found. This is done to
110 * find correct interface index for routing
111 * message processing.
112 */
113 ifIndex = 0;
114 next = buf;
115 while (next < lim) {
116 ifm = (struct if_msghdr *)next;
117 next += ifm->ifm_msglen;
118 if (ifm->ifm_version != RTM_VERSION) {
119 if (g_co.verbose)
120 warnx("routing message version %d "
121 "not understood", ifm->ifm_version);
122 continue;
123 }
124 if (ifm->ifm_type == RTM_IFINFO) {
125 sdl = (struct sockaddr_dl *)(ifm + 1);
126 if (strlen(ifn) == sdl->sdl_nlen &&
127 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
128 ifIndex = ifm->ifm_index;
129 break;
130 }
131 }
132 }
133 if (!ifIndex)
134 errx(1, "unknown interface name %s", ifn);
135 /*
136 * Get interface address.
137 */
138 sin = NULL;
139 while (next < lim) {
140 ifam = (struct ifa_msghdr *)next;
141 next += ifam->ifam_msglen;
142 if (ifam->ifam_version != RTM_VERSION) {
143 if (g_co.verbose)
144 warnx("routing message version %d "
145 "not understood", ifam->ifam_version);
146 continue;
147 }
148 if (ifam->ifam_type != RTM_NEWADDR)
149 break;
150 if (ifam->ifam_addrs & RTA_IFA) {
151 int i;
152 char *cp = (char *)(ifam + 1);
153
154 for (i = 1; i < RTA_IFA; i <<= 1) {
155 if (ifam->ifam_addrs & i)
156 cp += SA_SIZE((struct sockaddr *)cp);
157 }
158 if (((struct sockaddr *)cp)->sa_family == AF_INET) {
159 sin = (struct sockaddr_in *)cp;
160 break;
161 }
162 }
163 }
164 if (sin == NULL)
165 n->ip.s_addr = htonl(INADDR_ANY);
166 else
167 n->ip = sin->sin_addr;
168 strncpy(n->if_name, ifn, IF_NAMESIZE);
169
170 free(buf);
171 }
172
173 /*
174 * XXX - The following functions, macros and definitions come from natd.c:
175 * it would be better to move them outside natd.c, in a file
176 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
177 * with it.
178 */
179
180 /*
181 * Definition of a port range, and macros to deal with values.
182 * FORMAT: HI 16-bits == first port in range, 0 == all ports.
183 * LO 16-bits == number of ports in range
184 * NOTES: - Port values are not stored in network byte order.
185 */
186
187 #define port_range u_long
188
189 #define GETLOPORT(x) ((x) >> 0x10)
190 #define GETNUMPORTS(x) ((x) & 0x0000ffff)
191 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x)))
192
193 /* Set y to be the low-port value in port_range variable x. */
194 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
195
196 /* Set y to be the number of ports in port_range variable x. */
197 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
198
199 static void
StrToAddr(const char * str,struct in_addr * addr)200 StrToAddr (const char* str, struct in_addr* addr)
201 {
202 struct hostent* hp;
203
204 if (inet_aton (str, addr))
205 return;
206
207 hp = gethostbyname (str);
208 if (!hp)
209 errx (1, "unknown host %s", str);
210
211 memcpy (addr, hp->h_addr, sizeof (struct in_addr));
212 }
213
214 static int
StrToPortRange(const char * str,const char * proto,port_range * portRange)215 StrToPortRange (const char* str, const char* proto, port_range *portRange)
216 {
217 char* sep;
218 struct servent* sp;
219 char* end;
220 u_short loPort;
221 u_short hiPort;
222
223 /* First see if this is a service, return corresponding port if so. */
224 sp = getservbyname (str,proto);
225 if (sp) {
226 SETLOPORT(*portRange, ntohs(sp->s_port));
227 SETNUMPORTS(*portRange, 1);
228 return 0;
229 }
230
231 /* Not a service, see if it's a single port or port range. */
232 sep = strchr (str, '-');
233 if (sep == NULL) {
234 SETLOPORT(*portRange, strtol(str, &end, 10));
235 if (end != str) {
236 /* Single port. */
237 SETNUMPORTS(*portRange, 1);
238 return 0;
239 }
240
241 /* Error in port range field. */
242 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
243 }
244
245 /* Port range, get the values and sanity check. */
246 sscanf (str, "%hu-%hu", &loPort, &hiPort);
247 SETLOPORT(*portRange, loPort);
248 SETNUMPORTS(*portRange, 0); /* Error by default */
249 if (loPort <= hiPort)
250 SETNUMPORTS(*portRange, hiPort - loPort + 1);
251
252 if (GETNUMPORTS(*portRange) == 0)
253 errx (EX_DATAERR, "invalid port range %s", str);
254
255 return 0;
256 }
257
258 static int
StrToProto(const char * str)259 StrToProto (const char* str)
260 {
261 if (!strcmp (str, "tcp"))
262 return IPPROTO_TCP;
263
264 if (!strcmp (str, "udp"))
265 return IPPROTO_UDP;
266
267 if (!strcmp (str, "sctp"))
268 return IPPROTO_SCTP;
269 errx (EX_DATAERR, "unknown protocol %s. Expected sctp, tcp or udp", str);
270 }
271
272 static int
StrToAddrAndPortRange(const char * str,struct in_addr * addr,char * proto,port_range * portRange)273 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
274 port_range *portRange)
275 {
276 char* ptr;
277
278 ptr = strchr (str, ':');
279 if (!ptr)
280 errx (EX_DATAERR, "%s is missing port number", str);
281
282 *ptr = '\0';
283 ++ptr;
284
285 StrToAddr (str, addr);
286 return StrToPortRange (ptr, proto, portRange);
287 }
288
289 /* End of stuff taken from natd.c. */
290
291 /*
292 * The next 3 functions add support for the addr, port and proto redirect and
293 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
294 * and SetupProtoRedirect() from natd.c.
295 *
296 * Every setup_* function fills at least one redirect entry
297 * (struct nat44_cfg_redir) and zero or more server pool entry
298 * (struct nat44_cfg_spool) in buf.
299 *
300 * The format of data in buf is:
301 *
302 * nat44_cfg_nat nat44_cfg_redir nat44_cfg_spool ...... nat44_cfg_spool
303 *
304 * ------------------------------------- ------------
305 * | | .....X ..... | | | | .....
306 * ------------------------------------- ...... ------------
307 * ^
308 * spool_cnt n=0 ...... n=(X-1)
309 *
310 * len points to the amount of available space in buf
311 * space counts the memory consumed by every function
312 *
313 * XXX - Every function get all the argv params so it
314 * has to check, in optional parameters, that the next
315 * args is a valid option for the redir entry and not
316 * another token. Only redir_port and redir_proto are
317 * affected by this.
318 */
319
320 static int
estimate_redir_addr(int * ac,char *** av)321 estimate_redir_addr(int *ac, char ***av)
322 {
323 size_t space = sizeof(struct nat44_cfg_redir);
324 char *sep = **av;
325 u_int c = 0;
326
327 (void)ac; /* UNUSED */
328 while ((sep = strchr(sep, ',')) != NULL) {
329 c++;
330 sep++;
331 }
332
333 if (c > 0)
334 c++;
335
336 space += c * sizeof(struct nat44_cfg_spool);
337
338 return (space);
339 }
340
341 static int
setup_redir_addr(char * buf,int * ac,char *** av)342 setup_redir_addr(char *buf, int *ac, char ***av)
343 {
344 struct nat44_cfg_redir *r;
345 char *sep;
346 size_t space;
347
348 r = (struct nat44_cfg_redir *)buf;
349 r->mode = REDIR_ADDR;
350 /* Skip nat44_cfg_redir at beginning of buf. */
351 buf = &buf[sizeof(struct nat44_cfg_redir)];
352 space = sizeof(struct nat44_cfg_redir);
353
354 /* Extract local address. */
355 if (strchr(**av, ',') != NULL) {
356 struct nat44_cfg_spool *spool;
357
358 /* Setup LSNAT server pool. */
359 r->laddr.s_addr = INADDR_NONE;
360 sep = strtok(**av, ",");
361 while (sep != NULL) {
362 spool = (struct nat44_cfg_spool *)buf;
363 space += sizeof(struct nat44_cfg_spool);
364 StrToAddr(sep, &spool->addr);
365 spool->port = ~0;
366 r->spool_cnt++;
367 /* Point to the next possible nat44_cfg_spool. */
368 buf = &buf[sizeof(struct nat44_cfg_spool)];
369 sep = strtok(NULL, ",");
370 }
371 } else
372 StrToAddr(**av, &r->laddr);
373 (*av)++; (*ac)--;
374
375 /* Extract public address. */
376 StrToAddr(**av, &r->paddr);
377 (*av)++; (*ac)--;
378
379 return (space);
380 }
381
382 static int
estimate_redir_port(int * ac,char *** av)383 estimate_redir_port(int *ac, char ***av)
384 {
385 size_t space = sizeof(struct nat44_cfg_redir);
386 char *sep = **av;
387 u_int c = 0;
388
389 (void)ac; /* UNUSED */
390 while ((sep = strchr(sep, ',')) != NULL) {
391 c++;
392 sep++;
393 }
394
395 if (c > 0)
396 c++;
397
398 space += c * sizeof(struct nat44_cfg_spool);
399
400 return (space);
401 }
402
403 static int
setup_redir_port(char * buf,int * ac,char *** av)404 setup_redir_port(char *buf, int *ac, char ***av)
405 {
406 struct nat44_cfg_redir *r;
407 char *sep, *protoName, *lsnat = NULL;
408 size_t space;
409 u_short numLocalPorts;
410 port_range portRange;
411
412 numLocalPorts = 0;
413
414 r = (struct nat44_cfg_redir *)buf;
415 r->mode = REDIR_PORT;
416 /* Skip nat44_cfg_redir at beginning of buf. */
417 buf = &buf[sizeof(struct nat44_cfg_redir)];
418 space = sizeof(struct nat44_cfg_redir);
419
420 /*
421 * Extract protocol.
422 */
423 r->proto = StrToProto(**av);
424 protoName = **av;
425 (*av)++; (*ac)--;
426
427 /*
428 * Extract local address.
429 */
430 if (strchr(**av, ',') != NULL) {
431 r->laddr.s_addr = INADDR_NONE;
432 r->lport = ~0;
433 numLocalPorts = 1;
434 lsnat = **av;
435 } else {
436 /*
437 * The sctp nat does not allow the port numbers to be mapped to
438 * new port numbers. Therefore, no ports are to be specified
439 * in the target port field.
440 */
441 if (r->proto == IPPROTO_SCTP) {
442 if (strchr(**av, ':'))
443 errx(EX_DATAERR, "redirect_port:"
444 "port numbers do not change in sctp, so do "
445 "not specify them as part of the target");
446 else
447 StrToAddr(**av, &r->laddr);
448 } else {
449 if (StrToAddrAndPortRange(**av, &r->laddr, protoName,
450 &portRange) != 0)
451 errx(EX_DATAERR, "redirect_port: "
452 "invalid local port range");
453
454 r->lport = GETLOPORT(portRange);
455 numLocalPorts = GETNUMPORTS(portRange);
456 }
457 }
458 (*av)++; (*ac)--;
459
460 /*
461 * Extract public port and optionally address.
462 */
463 if (strchr(**av, ':') != NULL) {
464 if (StrToAddrAndPortRange(**av, &r->paddr, protoName,
465 &portRange) != 0)
466 errx(EX_DATAERR, "redirect_port: "
467 "invalid public port range");
468 } else {
469 r->paddr.s_addr = INADDR_ANY;
470 if (StrToPortRange(**av, protoName, &portRange) != 0)
471 errx(EX_DATAERR, "redirect_port: "
472 "invalid public port range");
473 }
474
475 r->pport = GETLOPORT(portRange);
476 if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
477 numLocalPorts = GETNUMPORTS(portRange);
478 r->lport = r->pport;
479 }
480 r->pport_cnt = GETNUMPORTS(portRange);
481 (*av)++; (*ac)--;
482
483 /*
484 * Extract remote address and optionally port.
485 */
486 /*
487 * NB: isdigit(**av) => we've to check that next parameter is really an
488 * option for this redirect entry, else stop here processing arg[cv].
489 */
490 if (*ac != 0 && isdigit(***av)) {
491 if (strchr(**av, ':') != NULL) {
492 if (StrToAddrAndPortRange(**av, &r->raddr, protoName,
493 &portRange) != 0)
494 errx(EX_DATAERR, "redirect_port: "
495 "invalid remote port range");
496 } else {
497 SETLOPORT(portRange, 0);
498 SETNUMPORTS(portRange, 1);
499 StrToAddr(**av, &r->raddr);
500 }
501 (*av)++; (*ac)--;
502 } else {
503 SETLOPORT(portRange, 0);
504 SETNUMPORTS(portRange, 1);
505 r->raddr.s_addr = INADDR_ANY;
506 }
507 r->rport = GETLOPORT(portRange);
508 r->rport_cnt = GETNUMPORTS(portRange);
509
510 /*
511 * Make sure port ranges match up, then add the redirect ports.
512 */
513 if (numLocalPorts != r->pport_cnt)
514 errx(EX_DATAERR, "redirect_port: "
515 "port ranges must be equal in size");
516
517 /* Remote port range is allowed to be '0' which means all ports. */
518 if (r->rport_cnt != numLocalPorts &&
519 (r->rport_cnt != 1 || r->rport != 0))
520 errx(EX_DATAERR, "redirect_port: remote port must"
521 "be 0 or equal to local port range in size");
522
523 /* Setup LSNAT server pool. */
524 if (lsnat != NULL) {
525 struct nat44_cfg_spool *spool;
526
527 sep = strtok(lsnat, ",");
528 while (sep != NULL) {
529 spool = (struct nat44_cfg_spool *)buf;
530 space += sizeof(struct nat44_cfg_spool);
531 /*
532 * The sctp nat does not allow the port numbers to
533 * be mapped to new port numbers. Therefore, no ports
534 * are to be specified in the target port field.
535 */
536 if (r->proto == IPPROTO_SCTP) {
537 if (strchr (sep, ':')) {
538 errx(EX_DATAERR, "redirect_port:"
539 "port numbers do not change in "
540 "sctp, so do not specify them as "
541 "part of the target");
542 } else {
543 StrToAddr(sep, &spool->addr);
544 spool->port = r->pport;
545 }
546 } else {
547 if (StrToAddrAndPortRange(sep, &spool->addr,
548 protoName, &portRange) != 0)
549 errx(EX_DATAERR, "redirect_port:"
550 "invalid local port range");
551 if (GETNUMPORTS(portRange) != 1)
552 errx(EX_DATAERR, "redirect_port: "
553 "local port must be single in "
554 "this context");
555 spool->port = GETLOPORT(portRange);
556 }
557 r->spool_cnt++;
558 /* Point to the next possible nat44_cfg_spool. */
559 buf = &buf[sizeof(struct nat44_cfg_spool)];
560 sep = strtok(NULL, ",");
561 }
562 }
563
564 return (space);
565 }
566
567 static int
setup_redir_proto(char * buf,int * ac,char *** av)568 setup_redir_proto(char *buf, int *ac, char ***av)
569 {
570 struct nat44_cfg_redir *r;
571 struct protoent *protoent;
572 size_t space;
573
574 r = (struct nat44_cfg_redir *)buf;
575 r->mode = REDIR_PROTO;
576 /* Skip nat44_cfg_redir at beginning of buf. */
577 buf = &buf[sizeof(struct nat44_cfg_redir)];
578 space = sizeof(struct nat44_cfg_redir);
579
580 /*
581 * Extract protocol.
582 */
583 protoent = getprotobyname(**av);
584 if (protoent == NULL)
585 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", **av);
586 else
587 r->proto = protoent->p_proto;
588
589 (*av)++; (*ac)--;
590
591 /*
592 * Extract local address.
593 */
594 StrToAddr(**av, &r->laddr);
595
596 (*av)++; (*ac)--;
597
598 /*
599 * Extract optional public address.
600 */
601 if (*ac == 0) {
602 r->paddr.s_addr = INADDR_ANY;
603 r->raddr.s_addr = INADDR_ANY;
604 } else {
605 /* see above in setup_redir_port() */
606 if (isdigit(***av)) {
607 StrToAddr(**av, &r->paddr);
608 (*av)++; (*ac)--;
609
610 /*
611 * Extract optional remote address.
612 */
613 /* see above in setup_redir_port() */
614 if (*ac != 0 && isdigit(***av)) {
615 StrToAddr(**av, &r->raddr);
616 (*av)++; (*ac)--;
617 }
618 }
619 }
620
621 return (space);
622 }
623
624 static void
nat_show_log(struct nat44_cfg_nat * n,void * arg __unused)625 nat_show_log(struct nat44_cfg_nat *n, void *arg __unused)
626 {
627 char *buf;
628
629 buf = (char *)(n + 1);
630 if (buf[0] != '\0')
631 printf("nat %s: %s\n", n->name, buf);
632 }
633
634 static void
nat_show_cfg(struct nat44_cfg_nat * n,void * arg __unused)635 nat_show_cfg(struct nat44_cfg_nat *n, void *arg __unused)
636 {
637 struct nat44_cfg_redir *t;
638 struct nat44_cfg_spool *s;
639 caddr_t buf;
640 struct protoent *p;
641 uint32_t cnt;
642 int i, off;
643
644 buf = (caddr_t)n;
645 off = sizeof(*n);
646 printf("ipfw nat %s config", n->name);
647 if (strlen(n->if_name) != 0)
648 printf(" if %s", n->if_name);
649 else if (n->ip.s_addr != 0)
650 printf(" ip %s", inet_ntoa(n->ip));
651 while (n->mode != 0) {
652 if (n->mode & PKT_ALIAS_LOG) {
653 printf(" log");
654 n->mode &= ~PKT_ALIAS_LOG;
655 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
656 printf(" deny_in");
657 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
658 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
659 printf(" same_ports");
660 n->mode &= ~PKT_ALIAS_SAME_PORTS;
661 } else if (n->mode & PKT_ALIAS_SKIP_GLOBAL) {
662 printf(" skip_global");
663 n->mode &= ~PKT_ALIAS_SKIP_GLOBAL;
664 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
665 printf(" unreg_only");
666 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
667 } else if (n->mode & PKT_ALIAS_UNREGISTERED_CGN) {
668 printf(" unreg_cgn");
669 n->mode &= ~PKT_ALIAS_UNREGISTERED_CGN;
670 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
671 printf(" reset");
672 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
673 } else if (n->mode & PKT_ALIAS_REVERSE) {
674 printf(" reverse");
675 n->mode &= ~PKT_ALIAS_REVERSE;
676 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
677 printf(" proxy_only");
678 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
679 }
680 }
681 /* Print all the redirect's data configuration. */
682 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
683 t = (struct nat44_cfg_redir *)&buf[off];
684 off += sizeof(struct nat44_cfg_redir);
685 switch (t->mode) {
686 case REDIR_ADDR:
687 printf(" redirect_addr");
688 if (t->spool_cnt == 0)
689 printf(" %s", inet_ntoa(t->laddr));
690 else
691 for (i = 0; i < t->spool_cnt; i++) {
692 s = (struct nat44_cfg_spool *)&buf[off];
693 if (i)
694 printf(",");
695 else
696 printf(" ");
697 printf("%s", inet_ntoa(s->addr));
698 off += sizeof(struct nat44_cfg_spool);
699 }
700 printf(" %s", inet_ntoa(t->paddr));
701 break;
702 case REDIR_PORT:
703 p = getprotobynumber(t->proto);
704 printf(" redirect_port %s ", p->p_name);
705 if (!t->spool_cnt) {
706 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
707 if (t->pport_cnt > 1)
708 printf("-%u", t->lport +
709 t->pport_cnt - 1);
710 } else
711 for (i=0; i < t->spool_cnt; i++) {
712 s = (struct nat44_cfg_spool *)&buf[off];
713 if (i)
714 printf(",");
715 printf("%s:%u", inet_ntoa(s->addr),
716 s->port);
717 off += sizeof(struct nat44_cfg_spool);
718 }
719
720 printf(" ");
721 if (t->paddr.s_addr)
722 printf("%s:", inet_ntoa(t->paddr));
723 printf("%u", t->pport);
724 if (!t->spool_cnt && t->pport_cnt > 1)
725 printf("-%u", t->pport + t->pport_cnt - 1);
726
727 if (t->raddr.s_addr) {
728 printf(" %s", inet_ntoa(t->raddr));
729 if (t->rport) {
730 printf(":%u", t->rport);
731 if (!t->spool_cnt && t->rport_cnt > 1)
732 printf("-%u", t->rport +
733 t->rport_cnt - 1);
734 }
735 }
736 break;
737 case REDIR_PROTO:
738 p = getprotobynumber(t->proto);
739 printf(" redirect_proto %s %s", p->p_name,
740 inet_ntoa(t->laddr));
741 if (t->paddr.s_addr != 0) {
742 printf(" %s", inet_ntoa(t->paddr));
743 if (t->raddr.s_addr)
744 printf(" %s", inet_ntoa(t->raddr));
745 }
746 break;
747 default:
748 errx(EX_DATAERR, "unknown redir mode");
749 break;
750 }
751 }
752 printf("\n");
753 }
754
755 static int
nat_port_alias_parse(char * str,u_short * lpout,u_short * hpout)756 nat_port_alias_parse(char *str, u_short *lpout, u_short *hpout) {
757 long lp, hp;
758 char *ptr;
759 /* Lower port parsing */
760 lp = (long) strtol(str, &ptr, 10);
761 if (lp < 1024 || lp > 65535)
762 return 0;
763 if (!ptr || *ptr != '-')
764 return 0;
765 /* Upper port parsing */
766 hp = (long) strtol(ptr, &ptr, 10);
767 if (hp < 1024 || hp > 65535)
768 return 0;
769 if (ptr)
770 return 0;
771
772 *lpout = (u_short) lp;
773 *hpout = (u_short) hp;
774 return 1;
775 }
776
777 void
ipfw_config_nat(int ac,char ** av)778 ipfw_config_nat(int ac, char **av)
779 {
780 ipfw_obj_header *oh;
781 struct nat44_cfg_nat *n; /* Nat instance configuration. */
782 int i, off, tok, ac1;
783 u_short lp, hp;
784 char *id, *buf, **av1, *end;
785 size_t len;
786
787 av++;
788 ac--;
789 /* Nat id. */
790 if (ac == 0)
791 errx(EX_DATAERR, "missing nat id");
792 id = *av;
793 i = (int)strtol(id, &end, 0);
794 if (i <= 0 || *end != '\0')
795 errx(EX_DATAERR, "illegal nat id: %s", id);
796 av++;
797 ac--;
798 if (ac == 0)
799 errx(EX_DATAERR, "missing option");
800
801 len = sizeof(*oh) + sizeof(*n);
802 ac1 = ac;
803 av1 = av;
804 while (ac1 > 0) {
805 tok = match_token(nat_params, *av1);
806 ac1--;
807 av1++;
808 switch (tok) {
809 case TOK_IP:
810 case TOK_IF:
811 case TOK_PORT_ALIAS:
812 ac1--;
813 av1++;
814 break;
815 case TOK_ALOG:
816 case TOK_DENY_INC:
817 case TOK_SAME_PORTS:
818 case TOK_SKIP_GLOBAL:
819 case TOK_UNREG_ONLY:
820 case TOK_UNREG_CGN:
821 case TOK_RESET_ADDR:
822 case TOK_ALIAS_REV:
823 case TOK_PROXY_ONLY:
824 break;
825 case TOK_REDIR_ADDR:
826 if (ac1 < 2)
827 errx(EX_DATAERR, "redirect_addr: "
828 "not enough arguments");
829 len += estimate_redir_addr(&ac1, &av1);
830 av1 += 2;
831 ac1 -= 2;
832 break;
833 case TOK_REDIR_PORT:
834 if (ac1 < 3)
835 errx(EX_DATAERR, "redirect_port: "
836 "not enough arguments");
837 av1++;
838 ac1--;
839 len += estimate_redir_port(&ac1, &av1);
840 av1 += 2;
841 ac1 -= 2;
842 /* Skip optional remoteIP/port */
843 if (ac1 != 0 && isdigit(**av1)) {
844 av1++;
845 ac1--;
846 }
847 break;
848 case TOK_REDIR_PROTO:
849 if (ac1 < 2)
850 errx(EX_DATAERR, "redirect_proto: "
851 "not enough arguments");
852 len += sizeof(struct nat44_cfg_redir);
853 av1 += 2;
854 ac1 -= 2;
855 /* Skip optional remoteIP/port */
856 if (ac1 != 0 && isdigit(**av1)) {
857 av1++;
858 ac1--;
859 }
860 if (ac1 != 0 && isdigit(**av1)) {
861 av1++;
862 ac1--;
863 }
864 break;
865 default:
866 errx(EX_DATAERR, "unrecognised option ``%s''", av1[-1]);
867 }
868 }
869
870 if ((buf = malloc(len)) == NULL)
871 errx(EX_OSERR, "malloc failed");
872
873 /* Offset in buf: save space for header at the beginning. */
874 off = sizeof(*oh) + sizeof(*n);
875 memset(buf, 0, len);
876 oh = (ipfw_obj_header *)buf;
877 n = (struct nat44_cfg_nat *)(oh + 1);
878 oh->ntlv.head.length = sizeof(oh->ntlv);
879 snprintf(oh->ntlv.name, sizeof(oh->ntlv.name), "%d", i);
880 snprintf(n->name, sizeof(n->name), "%d", i);
881
882 while (ac > 0) {
883 tok = match_token(nat_params, *av);
884 ac--;
885 av++;
886 switch (tok) {
887 case TOK_IP:
888 if (ac == 0)
889 errx(EX_DATAERR, "missing option");
890 if (!inet_aton(av[0], &(n->ip)))
891 errx(EX_DATAERR, "bad ip address ``%s''",
892 av[0]);
893 ac--;
894 av++;
895 break;
896 case TOK_IF:
897 if (ac == 0)
898 errx(EX_DATAERR, "missing option");
899 set_addr_dynamic(av[0], n);
900 ac--;
901 av++;
902 break;
903 case TOK_ALOG:
904 n->mode |= PKT_ALIAS_LOG;
905 break;
906 case TOK_DENY_INC:
907 n->mode |= PKT_ALIAS_DENY_INCOMING;
908 break;
909 case TOK_SAME_PORTS:
910 n->mode |= PKT_ALIAS_SAME_PORTS;
911 break;
912 case TOK_UNREG_ONLY:
913 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
914 break;
915 case TOK_UNREG_CGN:
916 n->mode |= PKT_ALIAS_UNREGISTERED_CGN;
917 break;
918 case TOK_SKIP_GLOBAL:
919 n->mode |= PKT_ALIAS_SKIP_GLOBAL;
920 break;
921 case TOK_RESET_ADDR:
922 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
923 break;
924 case TOK_ALIAS_REV:
925 n->mode |= PKT_ALIAS_REVERSE;
926 break;
927 case TOK_PROXY_ONLY:
928 n->mode |= PKT_ALIAS_PROXY_ONLY;
929 break;
930 /*
931 * All the setup_redir_* functions work directly in
932 * the final buffer, see above for details.
933 */
934 case TOK_REDIR_ADDR:
935 case TOK_REDIR_PORT:
936 case TOK_REDIR_PROTO:
937 switch (tok) {
938 case TOK_REDIR_ADDR:
939 i = setup_redir_addr(&buf[off], &ac, &av);
940 break;
941 case TOK_REDIR_PORT:
942 i = setup_redir_port(&buf[off], &ac, &av);
943 break;
944 case TOK_REDIR_PROTO:
945 i = setup_redir_proto(&buf[off], &ac, &av);
946 break;
947 }
948 n->redir_cnt++;
949 off += i;
950 break;
951 case TOK_PORT_ALIAS:
952 if (ac == 0)
953 errx(EX_DATAERR, "missing option");
954 if (!nat_port_alias_parse(av[0], &lp, &hp))
955 errx(EX_DATAERR,
956 "You need a range of port(s) from 1024 <= x < 65536");
957 if (lp >= hp)
958 errx(EX_DATAERR,
959 "Upper port has to be greater than lower port");
960 n->alias_port_lo = lp;
961 n->alias_port_hi = hp;
962 ac--;
963 av++;
964 break;
965 }
966 }
967 if (n->mode & PKT_ALIAS_SAME_PORTS && n->alias_port_lo)
968 errx(EX_DATAERR, "same_ports and port_range cannot both be selected");
969
970 i = do_set3(IP_FW_NAT44_XCONFIG, &oh->opheader, len);
971 if (i != 0)
972 err(1, "setsockopt(%s)", "IP_FW_NAT44_XCONFIG");
973
974 if (!g_co.do_quiet) {
975 /* After every modification, we show the resultant rule. */
976 int _ac = 3;
977 const char *_av[] = {"show", "config", id};
978 ipfw_show_nat(_ac, (char **)(void *)_av);
979 }
980 }
981
982 static void
nat_fill_ntlv(ipfw_obj_ntlv * ntlv,int i)983 nat_fill_ntlv(ipfw_obj_ntlv *ntlv, int i)
984 {
985
986 ntlv->head.type = IPFW_TLV_EACTION_NAME(1); /* it doesn't matter */
987 ntlv->head.length = sizeof(ipfw_obj_ntlv);
988 ntlv->idx = 1;
989 ntlv->set = 0; /* not yet */
990 snprintf(ntlv->name, sizeof(ntlv->name), "%d", i);
991 }
992
993 int
ipfw_delete_nat(int i)994 ipfw_delete_nat(int i)
995 {
996 ipfw_obj_header oh;
997 int ret;
998
999 memset(&oh, 0, sizeof(oh));
1000 nat_fill_ntlv(&oh.ntlv, i);
1001 ret = do_set3(IP_FW_NAT44_DESTROY, &oh.opheader, sizeof(oh));
1002 if (ret == -1) {
1003 if (!g_co.do_quiet)
1004 warn("nat %u not available", i);
1005 return (EX_UNAVAILABLE);
1006 }
1007 return (EX_OK);
1008 }
1009
1010 struct nat_list_arg {
1011 uint16_t cmd;
1012 int is_all;
1013 };
1014
1015 static int
nat_show_data(struct nat44_cfg_nat * cfg,void * arg)1016 nat_show_data(struct nat44_cfg_nat *cfg, void *arg)
1017 {
1018 struct nat_list_arg *nla;
1019 ipfw_obj_header *oh;
1020
1021 nla = (struct nat_list_arg *)arg;
1022
1023 switch (nla->cmd) {
1024 case IP_FW_NAT44_XGETCONFIG:
1025 if (nat_get_cmd(cfg->name, nla->cmd, &oh) != 0) {
1026 warnx("Error getting nat instance %s info", cfg->name);
1027 break;
1028 }
1029 nat_show_cfg((struct nat44_cfg_nat *)(oh + 1), NULL);
1030 free(oh);
1031 break;
1032 case IP_FW_NAT44_XGETLOG:
1033 if (nat_get_cmd(cfg->name, nla->cmd, &oh) == 0) {
1034 nat_show_log((struct nat44_cfg_nat *)(oh + 1), NULL);
1035 free(oh);
1036 break;
1037 }
1038 /* Handle error */
1039 if (nla->is_all != 0 && errno == ENOENT)
1040 break;
1041 warn("Error getting nat instance %s info", cfg->name);
1042 break;
1043 }
1044
1045 return (0);
1046 }
1047
1048 /*
1049 * Compare nat names.
1050 * Honor number comparison.
1051 */
1052 static int
natname_cmp(const void * a,const void * b)1053 natname_cmp(const void *a, const void *b)
1054 {
1055 const struct nat44_cfg_nat *ia, *ib;
1056
1057 ia = (const struct nat44_cfg_nat *)a;
1058 ib = (const struct nat44_cfg_nat *)b;
1059
1060 return (stringnum_cmp(ia->name, ib->name));
1061 }
1062
1063 /*
1064 * Retrieves nat list from kernel,
1065 * optionally sorts it and calls requested function for each table.
1066 * Returns 0 on success.
1067 */
1068 static int
nat_foreach(nat_cb_t * f,void * arg,int sort)1069 nat_foreach(nat_cb_t *f, void *arg, int sort)
1070 {
1071 ipfw_obj_lheader *olh;
1072 struct nat44_cfg_nat *cfg;
1073 size_t sz;
1074 uint32_t i;
1075
1076 /* Start with reasonable default */
1077 sz = sizeof(*olh) + 16 * sizeof(struct nat44_cfg_nat);
1078
1079 for (;;) {
1080 if ((olh = calloc(1, sz)) == NULL)
1081 return (ENOMEM);
1082
1083 olh->size = sz;
1084 if (do_get3(IP_FW_NAT44_LIST_NAT, &olh->opheader, &sz) != 0) {
1085 sz = olh->size;
1086 free(olh);
1087 if (errno == ENOMEM)
1088 continue;
1089 return (errno);
1090 }
1091
1092 if (sort != 0)
1093 qsort(olh + 1, olh->count, olh->objsize, natname_cmp);
1094
1095 cfg = (struct nat44_cfg_nat*)(olh + 1);
1096 for (i = 0; i < olh->count; i++) {
1097 (void)f(cfg, arg); /* Ignore errors for now */
1098 cfg = (struct nat44_cfg_nat *)((caddr_t)cfg +
1099 olh->objsize);
1100 }
1101
1102 free(olh);
1103 break;
1104 }
1105
1106 return (0);
1107 }
1108
1109 static int
nat_get_cmd(char * name,uint16_t cmd,ipfw_obj_header ** ooh)1110 nat_get_cmd(char *name, uint16_t cmd, ipfw_obj_header **ooh)
1111 {
1112 ipfw_obj_header *oh;
1113 struct nat44_cfg_nat *cfg;
1114 size_t sz;
1115
1116 /* Start with reasonable default */
1117 sz = sizeof(*oh) + sizeof(*cfg) + 128;
1118
1119 for (;;) {
1120 if ((oh = calloc(1, sz)) == NULL)
1121 return (ENOMEM);
1122 cfg = (struct nat44_cfg_nat *)(oh + 1);
1123 oh->ntlv.head.length = sizeof(oh->ntlv);
1124 strlcpy(oh->ntlv.name, name, sizeof(oh->ntlv.name));
1125 strlcpy(cfg->name, name, sizeof(cfg->name));
1126
1127 if (do_get3(cmd, &oh->opheader, &sz) != 0) {
1128 sz = cfg->size;
1129 free(oh);
1130 if (errno == ENOMEM)
1131 continue;
1132 return (errno);
1133 }
1134
1135 *ooh = oh;
1136 break;
1137 }
1138
1139 return (0);
1140 }
1141
1142 void
ipfw_show_nat(int ac,char ** av)1143 ipfw_show_nat(int ac, char **av)
1144 {
1145 ipfw_obj_header *oh;
1146 char *name;
1147 int cmd;
1148 struct nat_list_arg nla;
1149
1150 ac--;
1151 av++;
1152
1153 if (g_co.test_only)
1154 return;
1155
1156 /* Parse parameters. */
1157 cmd = 0; /* XXX: Change to IP_FW_NAT44_XGETLOG @ MFC */
1158 name = NULL;
1159 for ( ; ac != 0; ac--, av++) {
1160 if (!strncmp(av[0], "config", strlen(av[0]))) {
1161 cmd = IP_FW_NAT44_XGETCONFIG;
1162 continue;
1163 }
1164 if (strcmp(av[0], "log") == 0) {
1165 cmd = IP_FW_NAT44_XGETLOG;
1166 continue;
1167 }
1168 if (name != NULL)
1169 err(EX_USAGE,"only one instance name may be specified");
1170 name = av[0];
1171 }
1172
1173 if (cmd == 0)
1174 errx(EX_USAGE, "Please specify action. Available: config,log");
1175
1176 if (name == NULL) {
1177 memset(&nla, 0, sizeof(nla));
1178 nla.cmd = cmd;
1179 nla.is_all = 1;
1180 nat_foreach(nat_show_data, &nla, 1);
1181 } else {
1182 if (nat_get_cmd(name, cmd, &oh) != 0)
1183 err(EX_OSERR, "Error getting nat %s instance info", name);
1184 nat_show_cfg((struct nat44_cfg_nat *)(oh + 1), NULL);
1185 free(oh);
1186 }
1187 }
1188
1189