2 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
3 * Copyright (c) 1994 Ugen J.S.Antsilevich
5 * Idea and grammar partially left from:
6 * Copyright (c) 1993 Daniel Boulet
8 * Redistribution and use in source forms, with and without modification,
9 * are permitted provided that this entire comment appears intact.
11 * Redistribution in binary form may occur without any restrictions.
12 * Obviously, it would be nice if you gave credit where credit is due
13 * but requiring it would be too onerous.
15 * This software is provided ``AS IS'' without any warranties of any kind.
17 * NEW command line interface for IP firewall facility
22 static const char rcsid[] =
23 "$FreeBSD: src/sbin/ipfw/ipfw.c,v 1.80.2.26 2003/01/14 19:15:58 dillon Exp $";
27 #include <sys/param.h>
29 #include <sys/socket.h>
30 #include <sys/sockio.h>
31 #include <sys/sysctl.h>
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip_icmp.h>
55 #include <netinet/ip_fw.h>
56 #include <net/route.h> /* def. of struct route */
57 #include <netinet/ip_dummynet.h>
58 #include <netinet/tcp.h>
59 #include <arpa/inet.h>
61 int s, /* main RAW socket */
62 do_resolv, /* Would try to resolve all */
63 do_acct, /* Show packet/byte count */
64 do_time, /* Show time stamps */
65 do_quiet, /* Be quiet in add and flush */
66 do_force, /* Don't ask for confirmation */
67 do_pipe, /* this cmd refers to a pipe */
68 do_sort, /* field to sort results (0 = no) */
69 do_dynamic, /* display dynamic rules */
70 do_expired, /* display expired dynamic rules */
78 static struct icmpcode icmpcodes[] = {
79 { ICMP_UNREACH_NET, "net" },
80 { ICMP_UNREACH_HOST, "host" },
81 { ICMP_UNREACH_PROTOCOL, "protocol" },
82 { ICMP_UNREACH_PORT, "port" },
83 { ICMP_UNREACH_NEEDFRAG, "needfrag" },
84 { ICMP_UNREACH_SRCFAIL, "srcfail" },
85 { ICMP_UNREACH_NET_UNKNOWN, "net-unknown" },
86 { ICMP_UNREACH_HOST_UNKNOWN, "host-unknown" },
87 { ICMP_UNREACH_ISOLATED, "isolated" },
88 { ICMP_UNREACH_NET_PROHIB, "net-prohib" },
89 { ICMP_UNREACH_HOST_PROHIB, "host-prohib" },
90 { ICMP_UNREACH_TOSNET, "tosnet" },
91 { ICMP_UNREACH_TOSHOST, "toshost" },
92 { ICMP_UNREACH_FILTER_PROHIB, "filter-prohib" },
93 { ICMP_UNREACH_HOST_PRECEDENCE, "host-precedence" },
94 { ICMP_UNREACH_PRECEDENCE_CUTOFF, "precedence-cutoff" },
98 static void show_usage(void);
101 mask_bits(struct in_addr m_ad)
103 int h_fnd = 0, h_num = 0, i;
106 mask = ntohl(m_ad.s_addr);
107 for (i = 0; i < sizeof(u_long)*CHAR_BIT; i++) {
121 print_port(u_char prot, u_short port, const char comma)
123 struct servent *se = NULL;
127 printf("%c0x%04x", comma, port);
131 pe = getprotobynumber(prot);
132 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
135 printf("%c%s", comma, se->s_name);
137 printf("%c%d", comma, port);
141 print_iface(char *key, union ip_fw_if *un, int byname)
143 char ifnb[FW_IFNLEN+1];
146 strncpy(ifnb, un->fu_via_if.name, FW_IFNLEN);
147 ifnb[FW_IFNLEN] = '\0';
148 if (un->fu_via_if.unit == -1)
149 printf(" %s %s*", key, ifnb);
151 printf(" %s %s%d", key, ifnb, un->fu_via_if.unit);
152 } else if (un->fu_via_ip.s_addr != 0) {
153 printf(" %s %s", key, inet_ntoa(un->fu_via_ip));
155 printf(" %s any", key);
159 print_reject_code(int code)
163 for (ic = icmpcodes; ic->str; ic++)
164 if (ic->code == code) {
165 printf("%s", ic->str);
172 * _s_x holds a string-int pair for various lookups.
173 * s=NULL terminates the struct.
175 struct _s_x { char *s; int x; };
176 static struct _s_x limit_masks[] = {
177 {"src-addr", DYN_SRC_ADDR},
178 {"src-port", DYN_SRC_PORT},
179 {"dst-addr", DYN_DST_ADDR},
180 {"dst-port", DYN_DST_PORT},
184 show_ipfw(struct ip_fw *chain, int pcwidth, int bcwidth)
186 static int twidth = 0;
192 int nsp = IP_FW_GETNSRCP(chain);
193 int ndp = IP_FW_GETNDSTP(chain);
196 setservent(1/*stay open*/);
198 printf("%05u ", chain->fw_number);
201 printf("%*qu %*qu ", pcwidth, chain->fw_pcnt, bcwidth, chain->fw_bcnt);
207 strcpy(timestr, ctime((time_t *)&twidth));
208 *strchr(timestr, '\n') = '\0';
209 twidth = strlen(timestr);
211 if (chain->timestamp) {
212 strcpy(timestr, ctime((time_t *)&chain->timestamp));
213 *strchr(timestr, '\n') = '\0';
214 printf("%s ", timestr);
216 printf("%*s ", twidth, " ");
219 if (chain->fw_flg == IP_FW_F_CHECK_S) {
220 printf("check-state\n");
224 if (chain->fw_flg & IP_FW_F_RND_MATCH) {
225 double d = 1.0 * chain->dont_match_prob;
226 d = 1 - (d / 0x7fffffff);
227 printf("prob %f ", d);
230 switch (chain->fw_flg & IP_FW_F_COMMAND) {
241 printf("divert %u", chain->fw_divert_port);
244 printf("tee %u", chain->fw_divert_port);
247 printf("skipto %u", chain->fw_skipto_rule);
250 printf("pipe %u", chain->fw_skipto_rule);
253 printf("queue %u", chain->fw_skipto_rule);
256 if (chain->fw_reject_code == IP_FW_REJECT_RST)
260 print_reject_code(chain->fw_reject_code);
264 printf("fwd %s", inet_ntoa(chain->fw_fwd_ip.sin_addr));
265 if(chain->fw_fwd_ip.sin_port)
266 printf(",%d", chain->fw_fwd_ip.sin_port);
269 errx(EX_OSERR, "impossible");
272 if (chain->fw_flg & IP_FW_F_PRN) {
274 if (chain->fw_logamount)
275 printf(" logamount %d", chain->fw_logamount);
278 pe = getprotobynumber(chain->fw_prot);
280 printf(" %s", pe->p_name);
282 printf(" %u", chain->fw_prot);
284 printf(" from %s", chain->fw_flg & IP_FW_F_INVSRC ? "not " : "");
286 if (chain->fw_flg & IP_FW_F_SME) {
290 adrt = ntohl(chain->fw_smsk.s_addr);
291 if (adrt == ULONG_MAX && do_resolv) {
292 adrt = (chain->fw_src.s_addr);
293 he = gethostbyaddr((char *)&adrt,
294 sizeof(u_long), AF_INET);
296 printf("%s", inet_ntoa(chain->fw_src));
298 printf("%s", he->h_name);
299 } else if (adrt != ULONG_MAX) {
300 mb = mask_bits(chain->fw_smsk);
304 printf("%s", inet_ntoa(chain->fw_src));
307 printf("%s", inet_ntoa(chain->fw_src));
309 printf("%s", inet_ntoa(chain->fw_smsk));
312 printf("%s", inet_ntoa(chain->fw_src));
316 if (chain->fw_prot == IPPROTO_TCP || chain->fw_prot == IPPROTO_UDP) {
318 for (i = 0; i < nsp; i++) {
319 print_port(chain->fw_prot,
320 chain->fw_uar.fw_pts[i], comma);
321 if (i == 0 && (chain->fw_flg & IP_FW_F_SRNG))
323 else if (i == 0 && (chain->fw_flg & IP_FW_F_SMSK))
330 printf(" to %s", chain->fw_flg & IP_FW_F_INVDST ? "not " : "");
332 if (chain->fw_flg & IP_FW_F_DME) {
335 adrt = ntohl(chain->fw_dmsk.s_addr);
336 if (adrt == ULONG_MAX && do_resolv) {
337 adrt = (chain->fw_dst.s_addr);
338 he = gethostbyaddr((char *)&adrt,
339 sizeof(u_long), AF_INET);
341 printf("%s", inet_ntoa(chain->fw_dst));
343 printf("%s", he->h_name);
344 } else if (adrt != ULONG_MAX) {
345 mb = mask_bits(chain->fw_dmsk);
349 printf("%s", inet_ntoa(chain->fw_dst));
352 printf("%s", inet_ntoa(chain->fw_dst));
354 printf("%s", inet_ntoa(chain->fw_dmsk));
357 printf("%s", inet_ntoa(chain->fw_dst));
361 if (chain->fw_prot == IPPROTO_TCP || chain->fw_prot == IPPROTO_UDP) {
363 for (i = 0; i < ndp; i++) {
364 print_port(chain->fw_prot,
365 chain->fw_uar.fw_pts[nsp+i], comma);
366 if (i == 0 && (chain->fw_flg & IP_FW_F_DRNG))
368 else if (i == 0 && (chain->fw_flg & IP_FW_F_DMSK))
375 if (chain->fw_flg & IP_FW_F_UID) {
376 struct passwd *pwd = getpwuid(chain->fw_uid);
379 printf(" uid %s", pwd->pw_name);
381 printf(" uid %u", chain->fw_uid);
384 if (chain->fw_flg & IP_FW_F_GID) {
385 struct group *grp = getgrgid(chain->fw_gid);
388 printf(" gid %s", grp->gr_name);
390 printf(" gid %u", chain->fw_gid);
393 if (chain->fw_flg & IP_FW_F_KEEP_S) {
394 struct _s_x *p = limit_masks;
396 switch(chain->dyn_type) {
398 printf(" *** unknown type ***");
401 printf(" keep-state");
405 for ( ; p->s != NULL ; p++)
406 if (chain->limit_mask & p->x)
408 printf(" %d", chain->conn_limit);
413 if (chain->fw_flg & IP_FW_BRIDGED)
415 if ((chain->fw_flg & IP_FW_F_IN) && !(chain->fw_flg & IP_FW_F_OUT))
417 if (!(chain->fw_flg & IP_FW_F_IN) && (chain->fw_flg & IP_FW_F_OUT))
420 /* Handle hack for "via" backwards compatibility */
421 if ((chain->fw_flg & IF_FW_F_VIAHACK) == IF_FW_F_VIAHACK) {
423 &chain->fw_in_if, chain->fw_flg & IP_FW_F_IIFNAME);
425 /* Receive interface specified */
426 if (chain->fw_flg & IP_FW_F_IIFACE)
427 print_iface("recv", &chain->fw_in_if,
428 chain->fw_flg & IP_FW_F_IIFNAME);
429 /* Transmit interface specified */
430 if (chain->fw_flg & IP_FW_F_OIFACE)
431 print_iface("xmit", &chain->fw_out_if,
432 chain->fw_flg & IP_FW_F_OIFNAME);
435 if (chain->fw_flg & IP_FW_F_FRAG)
438 if (chain->fw_ipopt || chain->fw_ipnopt) {
439 int _opt_printed = 0;
440 #define PRINTOPT(x) {if (_opt_printed) printf(",");\
441 printf(x); _opt_printed = 1;}
444 if (chain->fw_ipopt & IP_FW_IPOPT_SSRR)
446 if (chain->fw_ipnopt & IP_FW_IPOPT_SSRR)
448 if (chain->fw_ipopt & IP_FW_IPOPT_LSRR)
450 if (chain->fw_ipnopt & IP_FW_IPOPT_LSRR)
452 if (chain->fw_ipopt & IP_FW_IPOPT_RR)
454 if (chain->fw_ipnopt & IP_FW_IPOPT_RR)
456 if (chain->fw_ipopt & IP_FW_IPOPT_TS)
458 if (chain->fw_ipnopt & IP_FW_IPOPT_TS)
462 if (chain->fw_ipflg & IP_FW_IF_TCPEST)
463 printf(" established");
464 else if (chain->fw_tcpf == IP_FW_TCPF_SYN &&
465 chain->fw_tcpnf == IP_FW_TCPF_ACK)
467 else if (chain->fw_tcpf || chain->fw_tcpnf) {
468 int _flg_printed = 0;
469 #define PRINTFLG(x) {if (_flg_printed) printf(",");\
470 printf(x); _flg_printed = 1;}
472 printf(" tcpflags ");
473 if (chain->fw_tcpf & IP_FW_TCPF_FIN)
475 if (chain->fw_tcpnf & IP_FW_TCPF_FIN)
477 if (chain->fw_tcpf & IP_FW_TCPF_SYN)
479 if (chain->fw_tcpnf & IP_FW_TCPF_SYN)
481 if (chain->fw_tcpf & IP_FW_TCPF_RST)
483 if (chain->fw_tcpnf & IP_FW_TCPF_RST)
485 if (chain->fw_tcpf & IP_FW_TCPF_PSH)
487 if (chain->fw_tcpnf & IP_FW_TCPF_PSH)
489 if (chain->fw_tcpf & IP_FW_TCPF_ACK)
491 if (chain->fw_tcpnf & IP_FW_TCPF_ACK)
493 if (chain->fw_tcpf & IP_FW_TCPF_URG)
495 if (chain->fw_tcpnf & IP_FW_TCPF_URG)
498 if (chain->fw_tcpopt || chain->fw_tcpnopt) {
499 int _opt_printed = 0;
500 #define PRINTTOPT(x) {if (_opt_printed) printf(",");\
501 printf(x); _opt_printed = 1;}
503 printf(" tcpoptions ");
504 if (chain->fw_tcpopt & IP_FW_TCPOPT_MSS)
506 if (chain->fw_tcpnopt & IP_FW_TCPOPT_MSS)
508 if (chain->fw_tcpopt & IP_FW_TCPOPT_WINDOW)
510 if (chain->fw_tcpnopt & IP_FW_TCPOPT_WINDOW)
511 PRINTTOPT("!window");
512 if (chain->fw_tcpopt & IP_FW_TCPOPT_SACK)
514 if (chain->fw_tcpnopt & IP_FW_TCPOPT_SACK)
516 if (chain->fw_tcpopt & IP_FW_TCPOPT_TS)
518 if (chain->fw_tcpnopt & IP_FW_TCPOPT_TS)
520 if (chain->fw_tcpopt & IP_FW_TCPOPT_CC)
522 if (chain->fw_tcpnopt & IP_FW_TCPOPT_CC)
526 if (chain->fw_flg & IP_FW_F_ICMPBIT) {
532 for (type_index = 0; type_index < IP_FW_ICMPTYPES_DIM * sizeof(unsigned) * 8; ++type_index)
533 if (chain->fw_uar.fw_icmptypes[type_index / (sizeof(unsigned) * 8)] &
534 (1U << (type_index % (sizeof(unsigned) * 8)))) {
535 printf("%c%d", first == 1 ? ' ' : ',', type_index);
546 sort_q(const void *pa, const void *pb)
548 int rev = (do_sort < 0);
549 int field = rev ? -do_sort : do_sort;
551 const struct dn_flow_queue *a = pa;
552 const struct dn_flow_queue *b = pb;
556 res = a->len - b->len;
559 res = a->len_bytes - b->len_bytes;
562 case 3: /* tot pkts */
563 res = a->tot_pkts - b->tot_pkts;
566 case 4: /* tot bytes */
567 res = a->tot_bytes - b->tot_bytes;
574 return (int)(rev ? res : -res);
578 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
582 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
584 fs->flow_mask.src_ip, fs->flow_mask.src_port,
585 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
586 if (fs->rq_elements == 0)
589 printf("BKT Prot ___Source IP/port____ "
590 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
592 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
593 for (l = 0; l < fs->rq_elements; l++) {
597 ina.s_addr = htonl(q[l].id.src_ip);
598 printf("%3d ", q[l].hash_slot);
599 pe = getprotobynumber(q[l].id.proto);
601 printf("%-4s ", pe->p_name);
603 printf("%4u ", q[l].id.proto);
605 inet_ntoa(ina), q[l].id.src_port);
606 ina.s_addr = htonl(q[l].id.dst_ip);
608 inet_ntoa(ina), q[l].id.dst_port);
609 printf("%4qu %8qu %2u %4u %3u\n",
610 q[l].tot_pkts, q[l].tot_bytes,
611 q[l].len, q[l].len_bytes, q[l].drops);
613 printf(" S %20qd F %20qd\n",
619 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
624 char red[90]; /* Display RED parameters */
627 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
629 sprintf(qs, "%d KB", l / 1024);
631 sprintf(qs, "%d B", l);
633 sprintf(qs, "%3d sl.", l);
635 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
638 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
640 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
641 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
642 1.0 * fs->w_q / (double)(1 << SCALE_RED),
643 SCALE_VAL(fs->min_th),
644 SCALE_VAL(fs->max_th),
645 1.0 * fs->max_p / (double)(1 << SCALE_RED));
647 sprintf(red, "droptail");
649 printf("%s %s%s %d queues (%d buckets) %s\n",
650 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
654 sysctl_handler(int ac, char *av[], int which)
660 warnx("missing keyword to enable/disable\n");
661 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
662 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
663 &which, sizeof(which));
664 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
665 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
666 &which, sizeof(which));
667 } else if (strncmp(*av, "debug", strlen(*av)) == 0) {
668 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
669 &which, sizeof(which));
670 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
671 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
672 &which, sizeof(which));
674 warnx("unrecognize enable/disable keyword: %s\n", *av);
679 list(int ac, char *av[])
682 struct dn_pipe *pipes;
689 /* get rules or pipes from kernel, resizing array as necessary */
691 const int unit = do_pipe ? sizeof(*pipes) : sizeof(*rules);
692 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
696 while (nbytes >= nalloc) {
697 nalloc = nalloc * 2 + 200;
699 if ((data = realloc(data, nbytes)) == NULL)
700 err(EX_OSERR, "realloc");
701 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
702 err(EX_OSERR, "getsockopt(IP_%s_GET)",
703 do_pipe ? "DUMMYNET" : "FW");
707 /* display requested pipes */
711 struct dn_pipe *p = (struct dn_pipe *) data;
712 struct dn_flow_set *fs;
713 struct dn_flow_queue *q;
717 rulenum = strtoul(*av++, NULL, 10);
720 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
721 double b = p->bandwidth;
725 if (p->next != (struct dn_pipe *)DN_IS_PIPE)
727 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
728 next = (void *)p + l;
730 q = (struct dn_flow_queue *)(p+1);
732 if (rulenum != 0 && rulenum != p->pipe_nr)
734 if (p->if_name[0] != '\0')
735 sprintf(buf, "%s", p->if_name);
737 sprintf(buf, "unlimited");
738 else if (b >= 1000000)
739 sprintf(buf, "%7.3f Mbit/s", b/1000000);
741 sprintf(buf, "%7.3f Kbit/s", b/1000);
743 sprintf(buf, "%7.3f bit/s ", b);
745 sprintf(prefix, "%05d: %s %4d ms ",
746 p->pipe_nr, buf, p->delay);
747 print_flowset_parms(&(p->fs), prefix);
749 printf(" V %20qd\n", p->V >> MY_M);
750 list_queues(&(p->fs), q);
752 fs = (struct dn_flow_set *) next;
753 for (; nbytes >= sizeof *fs; fs = (struct dn_flow_set *)next) {
756 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
758 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
759 next = (void *)fs + l;
761 q = (struct dn_flow_queue *)(fs+1);
762 sprintf(prefix, "q%05d: weight %d pipe %d ",
763 fs->fs_nr, fs->weight, fs->parent_nr);
764 print_flowset_parms(fs, prefix);
771 rules = (struct ip_fw *)data;
772 /* determine num more accurately */
774 while (rules[num].fw_number < 65535)
776 num++; /* counting starts from 0 ... */
777 /* if showing stats, figure out column widths ahead of time */
779 for (n = 0; n < num; n++) {
780 struct ip_fw *const r = &rules[n];
785 width = sprintf(temp, "%qu", r->fw_pcnt);
790 width = sprintf(temp, "%qu", r->fw_bcnt);
796 /* display all rules */
797 for (n = 0; n < num; n++) {
798 struct ip_fw *const r = &rules[n];
800 show_ipfw(r, pcwidth, bcwidth);
803 /* display specific rules requested on command line */
811 /* convert command line rule # */
812 rnum = strtoul(*av++, &endptr, 10);
815 warnx("invalid rule number: %s", *(av - 1));
819 for (seen = n = 0; n < num; n++) {
820 struct ip_fw *const r = &rules[n];
822 if (r->fw_number > rnum)
824 if (r->fw_number == rnum) {
825 show_ipfw(r, pcwidth, bcwidth);
830 /* give precedence to other error(s) */
831 if (exitval == EX_OK)
832 exitval = EX_UNAVAILABLE;
833 warnx("rule %lu does not exist", rnum);
836 if (exitval != EX_OK)
842 if (do_dynamic && num * sizeof (rules[0]) != nbytes) {
843 struct ipfw_dyn_rule *d =
844 (struct ipfw_dyn_rule *)&rules[num];
848 printf("## Dynamic rules:\n");
850 if (d->expire == 0 && !do_expired) {
856 printf("%05d %qu %qu (T %d, slot %d)",
861 switch (d->dyn_type) {
862 case DYN_LIMIT_PARENT:
863 printf(" PARENT %d", d->count);
868 case DYN_KEEP_STATE: /* bidir, no mask */
873 pe = getprotobynumber(d->id.proto);
875 printf(" %s,", pe->p_name);
877 printf(" %u,", d->id.proto);
878 a.s_addr = htonl(d->id.src_ip);
879 printf(" %s %d", inet_ntoa(a), d->id.src_port);
880 a.s_addr = htonl(d->id.dst_ip);
881 printf("<-> %s %d", inet_ntoa(a), d->id.dst_port);
894 fprintf(stderr, "usage: ipfw [options]\n"
896 " add [number] rule\n"
897 " [pipe] delete number ...\n"
898 " [pipe] list [number ...]\n"
899 " [pipe] show [number ...]\n"
900 " zero [number ...]\n"
901 " resetlog [number ...]\n"
902 " pipe number config [pipeconfig]\n"
903 " rule: [prob <match_probability>] action proto src dst extras...\n"
905 " {allow|permit|accept|pass|deny|drop|reject|unreach code|\n"
906 " reset|count|skipto num|divert port|tee port|fwd ip|\n"
907 " pipe num} [log [logamount count]]\n"
908 " proto: {ip|tcp|udp|icmp|<number>}\n"
909 " src: from [not] {me|any|ip[{/bits|:mask}]} [{port[-port]}, [port], ...]\n"
910 " dst: to [not] {me|any|ip[{/bits|:mask}]} [{port[-port]}, [port], ...]\n"
914 " fragment (may not be used with ports or tcpflags)\n"
917 " {xmit|recv|via} {iface|ip|any}\n"
918 " {established|setup}\n"
919 " tcpflags [!]{syn|fin|rst|ack|psh|urg}, ...\n"
920 " ipoptions [!]{ssrr|lsrr|rr|ts}, ...\n"
921 " tcpoptions [!]{mss|window|sack|ts|cc}, ...\n"
922 " icmptypes {type[, type]}...\n"
923 " keep-state [method]\n"
925 " {bw|bandwidth} <number>{bit/s|Kbit/s|Mbit/s|Bytes/s|KBytes/s|MBytes/s}\n"
926 " {bw|bandwidth} interface_name\n"
927 " delay <milliseconds>\n"
928 " queue <size>{packets|Bytes|KBytes}\n"
930 " mask {all| [dst-ip|src-ip|dst-port|src-port|proto] <number>}\n"
931 " buckets <number>}\n"
932 " {red|gred} <fraction>/<number>/<number>/<fraction>\n"
940 lookup_host (char *host, struct in_addr *ipaddr)
944 if (!inet_aton(host, ipaddr)) {
945 if ((he = gethostbyname(host)) == NULL)
947 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
953 fill_ip(struct in_addr *ipno, struct in_addr *mask, int *acp, char ***avp)
959 if (ac && !strncmp(*av, "any", strlen(*av))) {
960 ipno->s_addr = mask->s_addr = 0; av++; ac--;
962 p = strchr(*av, '/');
964 p = strchr(*av, ':');
970 if (lookup_host(*av, ipno) != 0)
971 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
974 if (!inet_aton(p, mask))
975 errx(EX_DATAERR, "bad netmask ``%s''", p);
980 } else if (atoi(p) > 32) {
981 errx(EX_DATAERR, "bad width ``%s''", p);
984 htonl(~0 << (32 - atoi(p)));
988 mask->s_addr = htonl(~0);
991 ipno->s_addr &= mask->s_addr;
1000 fill_reject_code(u_short *codep, char *str)
1002 struct icmpcode *ic;
1007 errx(EX_DATAERR, "missing unreachable code");
1008 val = strtoul(str, &s, 0);
1009 if (s != str && *s == '\0' && val < 0x100) {
1013 for (ic = icmpcodes; ic->str; ic++)
1014 if (!strcasecmp(str, ic->str)) {
1018 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1022 add_port(u_short *cnt, u_short *ptr, u_short off, u_short port)
1024 if (off + *cnt >= IP_FW_MAX_PORTS)
1025 errx(EX_USAGE, "too many ports (max is %d)", IP_FW_MAX_PORTS);
1026 ptr[off+*cnt] = port;
1031 lookup_port(const char *arg, int proto, int test, int nodash)
1034 char *earg, buf[32];
1038 snprintf(buf, sizeof(buf), "%s", arg);
1040 for (p = q = buf; *p; *q++ = *p++) {
1045 if (*p == ',' || (nodash && *p == '-'))
1051 val = (int) strtoul(buf, &earg, 0);
1052 if (!*buf || *earg) {
1053 char *protocol = NULL;
1056 struct protoent *pe = getprotobynumber(proto);
1059 protocol = pe->p_name;
1063 if ((s = getservbyname(buf, protocol))) {
1064 val = htons(s->s_port);
1067 errx(EX_DATAERR, "unknown port ``%s''", buf);
1071 if (val < 0 || val > 0xffff) {
1074 "port ``%s'' out of range", buf);
1082 * return: 0 normally, 1 if first pair is a range,
1083 * 2 if first pair is a port+mask
1086 fill_port(u_short *cnt, u_short *ptr, u_short off, char *arg, int proto)
1089 int initial_range = 0;
1091 for (s = arg; *s && *s != ',' && *s != '-' && *s != ':'; s++) {
1092 if (*s == '\\' && *(s+1))
1097 if (strchr(arg, ','))
1098 errx(EX_USAGE, "port/mask must be first in list");
1099 add_port(cnt, ptr, off,
1100 *arg ? lookup_port(arg, proto, 0, 0) : 0x0000);
1102 s = strchr(arg, ',');
1105 add_port(cnt, ptr, off,
1106 *arg ? lookup_port(arg, proto, 0, 0) : 0xffff);
1112 if (strchr(arg, ','))
1113 errx(EX_USAGE, "port range must be first in list");
1114 add_port(cnt, ptr, off,
1115 *arg ? lookup_port(arg, proto, 0, 0) : 0x0000);
1117 s = strchr(arg, ',');
1120 add_port(cnt, ptr, off,
1121 *arg ? lookup_port(arg, proto, 0, 0) : 0xffff);
1125 while (arg != NULL) {
1126 s = strchr(arg, ',');
1129 add_port(cnt, ptr, off, lookup_port(arg, proto, 0, 0));
1132 return initial_range;
1136 fill_tcpflag(u_char *set, u_char *reset, char **vp)
1146 { "syn", IP_FW_TCPF_SYN },
1147 { "fin", IP_FW_TCPF_FIN },
1148 { "ack", IP_FW_TCPF_ACK },
1149 { "psh", IP_FW_TCPF_PSH },
1150 { "rst", IP_FW_TCPF_RST },
1151 { "urg", IP_FW_TCPF_URG }
1164 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i)
1165 if (!strncmp(p, flags[i].name, strlen(p))) {
1166 *d |= flags[i].value;
1169 if (i == sizeof(flags) / sizeof(flags[0]))
1170 errx(EX_DATAERR, "invalid tcp flag ``%s''", p);
1176 fill_tcpopts(u_char *set, u_char *reset, char **vp)
1186 { "mss", IP_FW_TCPOPT_MSS },
1187 { "window", IP_FW_TCPOPT_WINDOW },
1188 { "sack", IP_FW_TCPOPT_SACK },
1189 { "ts", IP_FW_TCPOPT_TS },
1190 { "cc", IP_FW_TCPOPT_CC },
1203 for (i = 0; i < sizeof(opts) / sizeof(opts[0]); ++i)
1204 if (!strncmp(p, opts[i].name, strlen(p))) {
1205 *d |= opts[i].value;
1208 if (i == sizeof(opts) / sizeof(opts[0]))
1209 errx(EX_DATAERR, "invalid tcp option ``%s''", p);
1215 fill_ipopt(u_char *set, u_char *reset, char **vp)
1230 if (!strncmp(p, "ssrr", strlen(p))) *d |= IP_FW_IPOPT_SSRR;
1231 if (!strncmp(p, "lsrr", strlen(p))) *d |= IP_FW_IPOPT_LSRR;
1232 if (!strncmp(p, "rr", strlen(p))) *d |= IP_FW_IPOPT_RR;
1233 if (!strncmp(p, "ts", strlen(p))) *d |= IP_FW_IPOPT_TS;
1239 fill_icmptypes(unsigned *types, char **vp, u_int *fw_flg)
1241 unsigned long icmptype;
1248 icmptype = strtoul(c, &c, 0);
1250 if (*c != ',' && *c != '\0')
1251 errx(EX_DATAERR, "invalid ICMP type");
1253 if (icmptype >= IP_FW_ICMPTYPES_DIM * sizeof(unsigned) * 8)
1254 errx(EX_DATAERR, "ICMP type out of range");
1256 types[icmptype / (sizeof(unsigned) * 8)] |=
1257 1 << (icmptype % (sizeof(unsigned) * 8));
1258 *fw_flg |= IP_FW_F_ICMPBIT;
1263 delete(int ac, char *av[])
1266 struct dn_pipe pipe;
1268 int exitval = EX_OK;
1270 memset(&rule, 0, sizeof rule);
1271 memset(&pipe, 0, sizeof pipe);
1276 while (ac && isdigit(**av)) {
1277 i = atoi(*av); av++; ac--;
1283 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1284 &pipe, sizeof pipe);
1287 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1288 do_pipe == 1 ? pipe.pipe_nr :
1293 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rule,
1296 exitval = EX_UNAVAILABLE;
1297 warn("rule %u: setsockopt(IP_FW_DEL)",
1302 if (exitval != EX_OK)
1307 verify_interface(union ip_fw_if *ifu)
1312 * If a unit was specified, check for that exact interface.
1313 * If a wildcard was specified, check for unit 0.
1315 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d",
1316 ifu->fu_via_if.name,
1317 ifu->fu_via_if.unit == -1 ? 0 : ifu->fu_via_if.unit);
1319 if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0)
1320 warnx("warning: interface ``%s'' does not exist",
1325 fill_iface(char *which, union ip_fw_if *ifu, int *byname, int ac, char *arg)
1328 errx(EX_USAGE, "missing argument for ``%s''", which);
1330 /* Parse the interface or address */
1331 if (!strcmp(arg, "any")) {
1332 ifu->fu_via_ip.s_addr = 0;
1334 } else if (!isdigit(*arg)) {
1338 strncpy(ifu->fu_via_if.name, arg,
1339 sizeof(ifu->fu_via_if.name));
1340 ifu->fu_via_if.name[sizeof(ifu->fu_via_if.name) - 1] = '\0';
1341 for (q = ifu->fu_via_if.name;
1342 *q && !isdigit(*q) && *q != '*'; q++)
1344 ifu->fu_via_if.unit = (*q == '*') ? -1 : atoi(q);
1346 verify_interface(ifu);
1347 } else if (!inet_aton(arg, &ifu->fu_via_ip)) {
1348 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1354 config_pipe(int ac, char **av)
1356 struct dn_pipe pipe;
1360 memset(&pipe, 0, sizeof pipe);
1364 if (ac && isdigit(**av)) {
1365 i = atoi(*av); av++; ac--;
1372 if (!strncmp(*av, "plr", strlen(*av))) {
1374 double d = strtod(av[1], NULL);
1379 pipe.fs.plr = (int)(d*0x7fffffff);
1382 } else if (!strncmp(*av, "queue", strlen(*av))) {
1384 pipe.fs.qsize = strtoul(av[1], &end, 0);
1385 if (*end == 'K' || *end == 'k') {
1386 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1387 pipe.fs.qsize *= 1024;
1388 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
1389 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1393 } else if (!strncmp(*av, "buckets", strlen(*av))) {
1394 pipe.fs.rq_size = strtoul(av[1], NULL, 0);
1397 } else if (!strncmp(*av, "mask", strlen(*av))) {
1398 /* per-flow queue, mask is dst_ip, dst_port,
1399 * src_ip, src_port, proto measured in bits
1404 pipe.fs.flow_mask.dst_ip = 0;
1405 pipe.fs.flow_mask.src_ip = 0;
1406 pipe.fs.flow_mask.dst_port = 0;
1407 pipe.fs.flow_mask.src_port = 0;
1408 pipe.fs.flow_mask.proto = 0;
1411 if (ac >= 1 && !strncmp(*av, "all", strlen(*av))) {
1412 /* special case -- all bits are significant */
1413 pipe.fs.flow_mask.dst_ip = ~0;
1414 pipe.fs.flow_mask.src_ip = ~0;
1415 pipe.fs.flow_mask.dst_port = ~0;
1416 pipe.fs.flow_mask.src_port = ~0;
1417 pipe.fs.flow_mask.proto = ~0;
1418 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1424 int len = strlen(*av);
1426 if (!strncmp(*av, "dst-ip", len))
1427 par = &pipe.fs.flow_mask.dst_ip;
1428 else if (!strncmp(*av, "src-ip", len))
1429 par = &pipe.fs.flow_mask.src_ip;
1430 else if (!strncmp(*av, "dst-port", len))
1431 par = &pipe.fs.flow_mask.dst_port;
1432 else if (!strncmp(*av, "src-port", len))
1433 par = &pipe.fs.flow_mask.src_port;
1434 else if (!strncmp(*av, "proto", len))
1435 par = &pipe.fs.flow_mask.proto;
1439 errx(EX_USAGE, "mask: %s value"
1441 if (*av[1] == '/') {
1442 a = strtoul(av[1]+1, &end, 0);
1443 if (a == 32) /* special case... */
1447 fprintf(stderr, " mask is 0x%08x\n", a);
1449 a = strtoul(av[1], &end, 0);
1451 if (par == &pipe.fs.flow_mask.src_port
1452 || par == &pipe.fs.flow_mask.dst_port) {
1454 errx(EX_DATAERR, "mask: %s"
1455 " must be 16 bit, not"
1457 *((u_int16_t *)par) = (u_int16_t)a;
1458 } else if (par == &pipe.fs.flow_mask.proto) {
1460 errx(EX_DATAERR, "mask: %s"
1462 " 8 bit, not 0x%08x",
1464 *((u_int8_t *)par) = (u_int8_t)a;
1466 *((u_int32_t *)par) = a;
1468 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1472 } else if (!strncmp(*av, "red", strlen(*av))
1473 || !strncmp(*av, "gred", strlen(*av))) {
1475 pipe.fs.flags_fs |= DN_IS_RED;
1477 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
1478 if ((end = strsep(&av[1], "/"))) {
1479 double w_q = strtod(end, NULL);
1480 if (w_q > 1 || w_q <= 0)
1481 errx(EX_DATAERR, "w_q %f must be "
1483 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
1485 if ((end = strsep(&av[1], "/"))) {
1486 pipe.fs.min_th = strtoul(end, &end, 0);
1487 if (*end == 'K' || *end == 'k')
1488 pipe.fs.min_th *= 1024;
1490 if ((end = strsep(&av[1], "/"))) {
1491 pipe.fs.max_th = strtoul(end, &end, 0);
1492 if (*end == 'K' || *end == 'k')
1493 pipe.fs.max_th *= 1024;
1495 if ((end = strsep(&av[1], "/"))) {
1496 double max_p = strtod(end, NULL);
1497 if (max_p > 1 || max_p <= 0)
1498 errx(EX_DATAERR, "max_p %f must be "
1499 "0 < x <= 1", max_p);
1501 (int)(max_p * (1 << SCALE_RED));
1505 } else if (!strncmp(*av, "droptail", strlen(*av))) {
1507 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1511 int len = strlen(*av);
1513 /* some commands are only good for pipes. */
1514 if (!strncmp(*av, "bw", len)
1515 || !strncmp(*av, "bandwidth", len)) {
1517 && av[1][0] <= 'z') {
1518 int l = sizeof(pipe.if_name)-1;
1519 /* interface name */
1520 strncpy(pipe.if_name, av[1], l);
1521 pipe.if_name[l] = '\0';
1524 pipe.if_name[0] = '\0';
1526 strtoul(av[1], &end, 0);
1532 } else if (*end == 'M') {
1538 || !strncmp(end, "by", 2))
1539 pipe.bandwidth *= 8;
1541 if (pipe.bandwidth < 0)
1543 "bandwidth too large");
1546 } else if (!strncmp(*av, "delay", len)) {
1547 pipe.delay = strtoul(av[1], NULL, 0);
1551 errx(EX_DATAERR, "unrecognised pipe"
1552 " option ``%s''", *av);
1554 } else { /* this refers to a queue */
1555 if (!strncmp(*av, "weight", len)) {
1557 strtoul(av[1], &end, 0);
1560 } else if (!strncmp(*av, "pipe", len)) {
1562 strtoul(av[1], &end, 0);
1566 errx(EX_DATAERR, "unrecognised option "
1573 if (pipe.pipe_nr == 0)
1574 errx(EX_DATAERR, "pipe_nr %d must be > 0",
1576 if (pipe.delay > 10000)
1577 errx(EX_DATAERR, "delay %d must be < 10000",
1579 } else { /* do_pipe == 2, queue */
1580 if (pipe.fs.parent_nr == 0)
1581 errx(EX_DATAERR, "pipe %d must be > 0",
1583 if (pipe.fs.weight >100)
1584 errx(EX_DATAERR, "weight %d must be <= 100",
1587 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
1588 if (pipe.fs.qsize > 1024*1024)
1589 errx(EX_DATAERR, "queue size %d, must be < 1MB",
1592 if (pipe.fs.qsize > 100)
1593 errx(EX_DATAERR, "queue size %d, must be"
1594 " 2 <= x <= 100", pipe.fs.qsize);
1596 if (pipe.fs.flags_fs & DN_IS_RED) {
1598 int lookup_depth, avg_pkt_size;
1599 double s, idle, weight, w_q;
1600 struct clockinfo clock;
1603 if (pipe.fs.min_th >= pipe.fs.max_th)
1604 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1605 pipe.fs.min_th, pipe.fs.max_th);
1606 if (pipe.fs.max_th == 0)
1607 errx(EX_DATAERR, "max_th must be > 0");
1610 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1611 &lookup_depth, &len, NULL, 0) == -1)
1613 errx(1, "sysctlbyname(\"%s\")",
1614 "net.inet.ip.dummynet.red_lookup_depth");
1615 if (lookup_depth == 0)
1616 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1617 " must be greater than zero");
1620 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1621 &avg_pkt_size, &len, NULL, 0) == -1)
1623 errx(1, "sysctlbyname(\"%s\")",
1624 "net.inet.ip.dummynet.red_avg_pkt_size");
1625 if (avg_pkt_size == 0)
1627 "net.inet.ip.dummynet.red_avg_pkt_size must"
1628 " be greater than zero");
1630 len = sizeof(struct clockinfo);
1631 if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
1632 errx(1, "sysctlbyname(\"%s\")",
1636 * Ticks needed for sending a medium-sized packet.
1637 * Unfortunately, when we are configuring a WF2Q+ queue, we
1638 * do not have bandwidth information, because that is stored
1639 * in the parent pipe, and also we have multiple queues
1640 * competing for it. So we set s=0, which is not very
1641 * correct. But on the other hand, why do we want RED with
1644 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
1647 s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
1650 * max idle time (in ticks) before avg queue size
1652 * NOTA: (3/w_q) is approx the value x so that
1653 * (1-w_q)^x < 10^-3.
1655 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
1656 idle = s * 3. / w_q;
1657 pipe.fs.lookup_step = (int)idle / lookup_depth;
1658 if (!pipe.fs.lookup_step)
1659 pipe.fs.lookup_step = 1;
1661 for (t = pipe.fs.lookup_step; t > 0; --t)
1663 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
1665 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
1668 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
1672 add(int ac, char *av[])
1677 struct protoent *pe;
1678 int saw_xmrc = 0, saw_via = 0;
1680 memset(&rule, 0, sizeof rule);
1685 if (ac && isdigit(**av)) {
1686 rule.fw_number = atoi(*av); av++; ac--;
1690 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
1691 double d = strtod(av[1], NULL);
1692 if (d <= 0 || d > 1)
1693 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
1694 if (d != 1) { /* 1 means always match */
1695 rule.fw_flg |= IP_FW_F_RND_MATCH;
1696 rule.dont_match_prob = (long)((1 - d) * 0x7fffffff);
1702 errx(EX_USAGE, "missing action");
1703 if (!strncmp(*av, "accept", strlen(*av))
1704 || !strncmp(*av, "pass", strlen(*av))
1705 || !strncmp(*av, "allow", strlen(*av))
1706 || !strncmp(*av, "permit", strlen(*av))) {
1707 rule.fw_flg |= IP_FW_F_ACCEPT; av++; ac--;
1708 } else if (!strncmp(*av, "count", strlen(*av))) {
1709 rule.fw_flg |= IP_FW_F_COUNT; av++; ac--;
1710 } else if (!strncmp(*av, "pipe", strlen(*av))) {
1711 rule.fw_flg |= IP_FW_F_PIPE; av++; ac--;
1713 errx(EX_USAGE, "missing pipe number");
1714 rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
1715 } else if (!strncmp(*av, "queue", strlen(*av))) {
1716 rule.fw_flg |= IP_FW_F_QUEUE; av++; ac--;
1718 errx(EX_USAGE, "missing queue number");
1719 rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
1720 } else if (!strncmp(*av, "divert", strlen(*av))) {
1721 rule.fw_flg |= IP_FW_F_DIVERT; av++; ac--;
1723 errx(EX_USAGE, "missing %s port", "divert");
1724 rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
1725 if (rule.fw_divert_port == 0) {
1728 s = getservbyname(av[-1], "divert");
1730 rule.fw_divert_port = ntohs(s->s_port);
1732 errx(EX_DATAERR, "illegal %s port", "divert");
1734 } else if (!strncmp(*av, "tee", strlen(*av))) {
1735 rule.fw_flg |= IP_FW_F_TEE; av++; ac--;
1737 errx(EX_USAGE, "missing %s port", "tee divert");
1738 rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
1739 if (rule.fw_divert_port == 0) {
1742 s = getservbyname(av[-1], "divert");
1744 rule.fw_divert_port = ntohs(s->s_port);
1746 errx(EX_DATAERR, "illegal %s port",
1749 } else if (!strncmp(*av, "fwd", strlen(*av))
1750 || !strncmp(*av, "forward", strlen(*av))) {
1751 struct in_addr dummyip;
1753 rule.fw_flg |= IP_FW_F_FWD; av++; ac--;
1755 errx(EX_USAGE, "missing forwarding IP address");
1756 rule.fw_fwd_ip.sin_len = sizeof(struct sockaddr_in);
1757 rule.fw_fwd_ip.sin_family = AF_INET;
1758 rule.fw_fwd_ip.sin_port = 0;
1759 pp = strchr(*av, ':');
1761 pp = strchr(*av, ',');
1765 i = lookup_port(pp, 0, 1, 0);
1767 errx(EX_DATAERR, "illegal forwarding"
1768 " port ``%s''", pp);
1770 rule.fw_fwd_ip.sin_port = (u_short)i;
1772 fill_ip(&(rule.fw_fwd_ip.sin_addr), &dummyip, &ac, &av);
1773 if (rule.fw_fwd_ip.sin_addr.s_addr == 0)
1774 errx(EX_DATAERR, "illegal forwarding IP address");
1776 } else if (!strncmp(*av, "skipto", strlen(*av))) {
1777 rule.fw_flg |= IP_FW_F_SKIPTO; av++; ac--;
1779 errx(EX_USAGE, "missing skipto rule number");
1780 rule.fw_skipto_rule = strtoul(*av, NULL, 10); av++; ac--;
1781 } else if ((!strncmp(*av, "deny", strlen(*av))
1782 || !strncmp(*av, "drop", strlen(*av)))) {
1783 rule.fw_flg |= IP_FW_F_DENY; av++; ac--;
1784 } else if (!strncmp(*av, "reject", strlen(*av))) {
1785 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
1786 rule.fw_reject_code = ICMP_UNREACH_HOST;
1787 } else if (!strncmp(*av, "reset", strlen(*av))) {
1788 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
1789 rule.fw_reject_code = IP_FW_REJECT_RST; /* check TCP later */
1790 } else if (!strncmp(*av, "unreach", strlen(*av))) {
1791 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
1792 fill_reject_code(&rule.fw_reject_code, *av); av++; ac--;
1793 } else if (!strncmp(*av, "check-state", strlen(*av))) {
1794 rule.fw_flg |= IP_FW_F_CHECK_S; av++; ac--;
1797 errx(EX_DATAERR, "invalid action ``%s''", *av);
1801 if (ac && !strncmp(*av, "log", strlen(*av))) {
1802 rule.fw_flg |= IP_FW_F_PRN; av++; ac--;
1804 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
1805 if (!(rule.fw_flg & IP_FW_F_PRN))
1806 errx(EX_USAGE, "``logamount'' not valid without"
1810 errx(EX_USAGE, "``logamount'' requires argument");
1811 rule.fw_logamount = atoi(*av);
1812 if (rule.fw_logamount < 0)
1813 errx(EX_DATAERR, "``logamount'' argument must be"
1815 if (rule.fw_logamount == 0)
1816 rule.fw_logamount = -1;
1822 errx(EX_USAGE, "missing protocol");
1823 if ((proto = atoi(*av)) > 0) {
1824 rule.fw_prot = proto; av++; ac--;
1825 } else if (!strncmp(*av, "all", strlen(*av))) {
1826 rule.fw_prot = IPPROTO_IP; av++; ac--;
1827 } else if ((pe = getprotobyname(*av)) != NULL) {
1828 rule.fw_prot = pe->p_proto; av++; ac--;
1830 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
1833 if (rule.fw_prot != IPPROTO_TCP
1834 && (rule.fw_flg & IP_FW_F_COMMAND) == IP_FW_F_REJECT
1835 && rule.fw_reject_code == IP_FW_REJECT_RST)
1836 errx(EX_DATAERR, "``reset'' is only valid for tcp packets");
1839 if (ac && !strncmp(*av, "from", strlen(*av))) { av++; ac--; }
1841 errx(EX_USAGE, "missing ``from''");
1843 if (ac && !strncmp(*av, "not", strlen(*av))) {
1844 rule.fw_flg |= IP_FW_F_INVSRC;
1848 errx(EX_USAGE, "missing arguments");
1850 if (ac && !strncmp(*av, "me", strlen(*av))) {
1851 rule.fw_flg |= IP_FW_F_SME;
1854 fill_ip(&rule.fw_src, &rule.fw_smsk, &ac, &av);
1857 if (ac && (isdigit(**av)
1858 || lookup_port(*av, rule.fw_prot, 1, 1) >= 0)) {
1862 retval = fill_port(&nports, rule.fw_uar.fw_pts,
1863 0, *av, rule.fw_prot);
1865 rule.fw_flg |= IP_FW_F_SRNG;
1866 else if (retval == 2)
1867 rule.fw_flg |= IP_FW_F_SMSK;
1868 IP_FW_SETNSRCP(&rule, nports);
1873 if (ac && !strncmp(*av, "to", strlen(*av))) { av++; ac--; }
1875 errx(EX_USAGE, "missing ``to''");
1877 if (ac && !strncmp(*av, "not", strlen(*av))) {
1878 rule.fw_flg |= IP_FW_F_INVDST;
1882 errx(EX_USAGE, "missing arguments");
1885 if (ac && !strncmp(*av, "me", strlen(*av))) {
1886 rule.fw_flg |= IP_FW_F_DME;
1889 fill_ip(&rule.fw_dst, &rule.fw_dmsk, &ac, &av);
1892 if (ac && (isdigit(**av)
1893 || lookup_port(*av, rule.fw_prot, 1, 1) >= 0)) {
1897 retval = fill_port(&nports, rule.fw_uar.fw_pts,
1898 IP_FW_GETNSRCP(&rule), *av, rule.fw_prot);
1900 rule.fw_flg |= IP_FW_F_DRNG;
1901 else if (retval == 2)
1902 rule.fw_flg |= IP_FW_F_DMSK;
1903 IP_FW_SETNDSTP(&rule, nports);
1907 if ((rule.fw_prot != IPPROTO_TCP) && (rule.fw_prot != IPPROTO_UDP)
1908 && (IP_FW_GETNSRCP(&rule) || IP_FW_GETNDSTP(&rule))) {
1909 errx(EX_USAGE, "only TCP and UDP protocols are valid"
1910 " with port specifications");
1914 if (!strncmp(*av, "uid", strlen(*av))) {
1919 rule.fw_flg |= IP_FW_F_UID;
1922 errx(EX_USAGE, "``uid'' requires argument");
1924 uid = strtoul(*av, &end, 0);
1926 pwd = getpwuid(uid);
1928 pwd = getpwnam(*av);
1930 errx(EX_DATAERR, "uid \"%s\" is"
1931 " nonexistent", *av);
1932 rule.fw_uid = pwd->pw_uid;
1934 } else if (!strncmp(*av, "gid", strlen(*av))) {
1939 rule.fw_flg |= IP_FW_F_GID;
1942 errx(EX_USAGE, "``gid'' requires argument");
1944 gid = strtoul(*av, &end, 0);
1946 grp = getgrgid(gid);
1948 grp = getgrnam(*av);
1950 errx(EX_DATAERR, "gid \"%s\" is"
1951 " nonexistent", *av);
1952 rule.fw_gid = grp->gr_gid;
1954 } else if (!strncmp(*av, "in", strlen(*av))) {
1955 rule.fw_flg |= IP_FW_F_IN;
1957 } else if (!strncmp(*av,"limit",strlen(*av))) {
1958 /* dyn. rule used to limit number of connections. */
1959 rule.fw_flg |= IP_FW_F_KEEP_S;
1960 rule.dyn_type = DYN_LIMIT ;
1961 rule.limit_mask = 0 ;
1964 struct _s_x *p = limit_masks;
1965 for ( ; p->s != NULL ; p++)
1966 if (!strncmp(*av, p->s, strlen(*av))) {
1967 rule.limit_mask |= p->x ;
1976 "limit needs mask and # of connections");
1977 rule.conn_limit = atoi(*av);
1978 if (rule.conn_limit == 0)
1979 errx(EX_USAGE, "limit: limit must be >0");
1980 if (rule.limit_mask == 0)
1981 errx(EX_USAGE, "missing limit mask");
1983 } else if (!strncmp(*av, "keep-state", strlen(*av))) {
1985 rule.fw_flg |= IP_FW_F_KEEP_S;
1988 if (ac > 0 && (type = atoi(*av)) != 0) {
1989 rule.dyn_type = type;
1992 } else if (!strncmp(*av, "bridged", strlen(*av))) {
1993 rule.fw_flg |= IP_FW_BRIDGED;
1995 } else if (!strncmp(*av, "out", strlen(*av))) {
1996 rule.fw_flg |= IP_FW_F_OUT;
1998 } else if (ac && !strncmp(*av, "xmit", strlen(*av))) {
2004 errx(EX_USAGE, "``via'' is incompatible"
2005 " with ``xmit'' and ``recv''");
2009 fill_iface("xmit", &ifu, &byname, ac, *av);
2010 rule.fw_out_if = ifu;
2011 rule.fw_flg |= IP_FW_F_OIFACE;
2013 rule.fw_flg |= IP_FW_F_OIFNAME;
2015 } else if (ac && !strncmp(*av, "recv", strlen(*av))) {
2023 fill_iface("recv", &ifu, &byname, ac, *av);
2024 rule.fw_in_if = ifu;
2025 rule.fw_flg |= IP_FW_F_IIFACE;
2027 rule.fw_flg |= IP_FW_F_IIFNAME;
2029 } else if (ac && !strncmp(*av, "via", strlen(*av))) {
2037 fill_iface("via", &ifu, &byname, ac, *av);
2038 rule.fw_out_if = rule.fw_in_if = ifu;
2041 (IP_FW_F_IIFNAME | IP_FW_F_OIFNAME);
2043 } else if (!strncmp(*av, "fragment", strlen(*av))) {
2044 rule.fw_flg |= IP_FW_F_FRAG;
2046 } else if (!strncmp(*av, "ipoptions", strlen(*av))) {
2049 errx(EX_USAGE, "missing argument"
2050 " for ``ipoptions''");
2051 fill_ipopt(&rule.fw_ipopt, &rule.fw_ipnopt, av);
2053 } else if (rule.fw_prot == IPPROTO_TCP) {
2054 if (!strncmp(*av, "established", strlen(*av))) {
2055 rule.fw_ipflg |= IP_FW_IF_TCPEST;
2057 } else if (!strncmp(*av, "setup", strlen(*av))) {
2058 rule.fw_tcpf |= IP_FW_TCPF_SYN;
2059 rule.fw_tcpnf |= IP_FW_TCPF_ACK;
2061 } else if (!strncmp(*av, "tcpflags", strlen(*av))
2062 || !strncmp(*av, "tcpflgs", strlen(*av))) {
2065 errx(EX_USAGE, "missing argument"
2066 " for ``tcpflags''");
2067 fill_tcpflag(&rule.fw_tcpf,
2068 &rule.fw_tcpnf, av);
2070 } else if (!strncmp(*av, "tcpoptions", strlen(*av))
2071 || !strncmp(*av, "tcpopts", strlen(*av))) {
2074 errx(EX_USAGE, "missing argument"
2075 " for ``tcpoptions''");
2076 fill_tcpopts(&rule.fw_tcpopt,
2077 &rule.fw_tcpnopt, av);
2080 errx(EX_USAGE, "unknown or out of order"
2081 " argument ``%s''", *av);
2083 } else if (rule.fw_prot == IPPROTO_ICMP) {
2084 if (!strncmp(*av, "icmptypes", strlen(*av))) {
2087 errx(EX_USAGE, "missing argument"
2088 " for ``icmptypes''");
2089 fill_icmptypes(rule.fw_uar.fw_icmptypes,
2093 errx(EX_USAGE, "unknown or out of order"
2094 " argument ``%s''", *av);
2097 errx(EX_USAGE, "unknown argument ``%s''", *av);
2101 /* No direction specified -> do both directions */
2102 if (!(rule.fw_flg & (IP_FW_F_OUT|IP_FW_F_IN)))
2103 rule.fw_flg |= (IP_FW_F_OUT|IP_FW_F_IN);
2105 /* Sanity check interface check, but handle "via" case separately */
2107 if (rule.fw_flg & IP_FW_F_IN)
2108 rule.fw_flg |= IP_FW_F_IIFACE;
2109 if (rule.fw_flg & IP_FW_F_OUT)
2110 rule.fw_flg |= IP_FW_F_OIFACE;
2111 } else if ((rule.fw_flg & IP_FW_F_OIFACE)
2112 && (rule.fw_flg & IP_FW_F_IN)) {
2113 errx(EX_DATAERR, "can't check xmit interface of incoming"
2117 /* frag may not be used in conjunction with ports or TCP flags */
2118 if (rule.fw_flg & IP_FW_F_FRAG) {
2119 if (rule.fw_tcpf || rule.fw_tcpnf)
2120 errx(EX_DATAERR, "can't mix 'frag' and tcpflags");
2123 errx(EX_DATAERR, "can't mix 'frag' and port"
2126 if (rule.fw_flg & IP_FW_F_PRN) {
2127 if (!rule.fw_logamount) {
2128 size_t len = sizeof(int);
2130 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2131 &rule.fw_logamount, &len, NULL, 0) == -1)
2132 errx(1, "sysctlbyname(\"%s\")",
2133 "net.inet.ip.fw.verbose_limit");
2134 } else if (rule.fw_logamount == -1)
2135 rule.fw_logamount = 0;
2136 rule.fw_loghighest = rule.fw_logamount;
2140 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, &rule, &i) == -1)
2141 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2143 show_ipfw(&rule, 10, 10);
2147 zero (int ac, char *av[])
2155 /* clear all entries */
2156 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2157 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2159 printf("Accounting cleared.\n");
2164 memset(&rule, 0, sizeof rule);
2167 if (isdigit(**av)) {
2168 rule.fw_number = atoi(*av); av++; ac--;
2169 if (setsockopt(s, IPPROTO_IP,
2170 IP_FW_ZERO, &rule, sizeof rule)) {
2171 warn("rule %u: setsockopt(IP_FW_ZERO)",
2173 failed = EX_UNAVAILABLE;
2174 } else if (!do_quiet)
2175 printf("Entry %d cleared\n",
2178 errx(EX_USAGE, "invalid rule number ``%s''", *av);
2181 if (failed != EX_OK)
2186 resetlog (int ac, char *av[])
2194 /* clear all entries */
2195 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2196 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2198 printf("Logging counts reset.\n");
2203 memset(&rule, 0, sizeof rule);
2206 if (isdigit(**av)) {
2207 rule.fw_number = atoi(*av); av++; ac--;
2208 if (setsockopt(s, IPPROTO_IP,
2209 IP_FW_RESETLOG, &rule, sizeof rule)) {
2210 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2212 failed = EX_UNAVAILABLE;
2213 } else if (!do_quiet)
2214 printf("Entry %d logging count reset\n",
2217 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2220 if (failed != EX_OK)
2225 ipfw_main(int ac, char **av)
2232 /* Initialize globals. */
2233 do_resolv = do_acct = do_time = do_quiet =
2234 do_pipe = do_sort = verbose = 0;
2236 /* Set the force flag for non-interactive processes */
2237 do_force = !isatty(STDIN_FILENO);
2239 optind = optreset = 1;
2240 while ((ch = getopt(ac, av, "s:adefNqtv")) != -1)
2242 case 's': /* sort */
2243 do_sort = atoi(optarg);
2266 case 'v': /* verbose */
2274 if (*(av += optind) == NULL)
2275 errx(EX_USAGE, "bad arguments, for usage summary ``ipfw''");
2277 if (!strncmp(*av, "pipe", strlen(*av))) {
2281 } else if (!strncmp(*av, "queue", strlen(*av))) {
2287 errx(EX_USAGE, "pipe requires arguments");
2289 /* allow argument swapping */
2290 if (ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2295 if (!strncmp(*av, "add", strlen(*av))) {
2297 } else if (do_pipe && !strncmp(*av, "config", strlen(*av))) {
2298 config_pipe(ac, av);
2299 } else if (!strncmp(*av, "delete", strlen(*av))) {
2301 } else if (!strncmp(*av, "flush", strlen(*av))) {
2304 if (do_force || do_quiet)
2310 printf("Are you sure? [yn] ");
2313 c = toupper(getc(stdin));
2314 while (c != '\n' && getc(stdin) != '\n')
2317 } while (c != 'Y' && c != 'N');
2323 if (setsockopt(s, IPPROTO_IP,
2324 do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH,
2326 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2327 do_pipe ? "DUMMYNET" : "FW");
2329 printf("Flushed all %s.\n",
2330 do_pipe ? "pipes" : "rules");
2332 } else if (!strncmp(*av, "zero", strlen(*av))) {
2334 } else if (!strncmp(*av, "resetlog", strlen(*av))) {
2336 } else if (!strncmp(*av, "print", strlen(*av))) {
2338 } else if (!strncmp(*av, "enable", strlen(*av))) {
2339 sysctl_handler(ac, av, 1);
2340 } else if (!strncmp(*av, "disable", strlen(*av))) {
2341 sysctl_handler(ac, av, 0);
2342 } else if (!strncmp(*av, "list", strlen(*av))) {
2344 } else if (!strncmp(*av, "show", strlen(*av))) {
2348 errx(EX_USAGE, "bad arguments, for usage summary ``ipfw''");
2354 main(int ac, char *av[])
2357 #define WHITESP " \t\f\v\n\r"
2359 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
2361 int i, c, lineno, qflag, pflag, status;
2365 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
2367 err(EX_UNAVAILABLE, "socket");
2372 * Only interpret the last command line argument as a file to
2373 * be preprocessed if it is specified as an absolute pathname.
2376 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) {
2377 qflag = pflag = i = 0;
2380 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
2384 errx(EX_USAGE, "-D requires -p");
2385 if (i > MAX_ARGS - 2)
2387 "too many -D or -U options");
2394 errx(EX_USAGE, "-U requires -p");
2395 if (i > MAX_ARGS - 2)
2397 "too many -D or -U options");
2414 errx(EX_USAGE, "bad arguments, for usage"
2415 " summary ``ipfw''");
2421 errx(EX_USAGE, "extraneous filename arguments");
2423 if ((f = fopen(av[0], "r")) == NULL)
2424 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
2427 /* pipe through preprocessor (cpp or m4) */
2432 if (pipe(pipedes) == -1)
2433 err(EX_OSERR, "cannot create pipe");
2435 switch((preproc = fork())) {
2437 err(EX_OSERR, "cannot fork");
2441 if (dup2(fileno(f), 0) == -1
2442 || dup2(pipedes[1], 1) == -1)
2443 err(EX_OSERR, "dup2()");
2448 err(EX_OSERR, "execvp(%s) failed", cmd);
2454 if ((f = fdopen(pipedes[0], "r")) == NULL) {
2455 int savederrno = errno;
2457 (void)kill(preproc, SIGTERM);
2459 err(EX_OSERR, "fdopen()");
2464 while (fgets(buf, BUFSIZ, f)) {
2466 sprintf(linename, "Line %d", lineno);
2471 if ((p = strchr(buf, '#')) != NULL)
2476 for (a = strtok(buf, WHITESP);
2477 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
2479 if (i == (qflag? 2: 1))
2482 errx(EX_USAGE, "%s: too many arguments",
2490 if (waitpid(preproc, &status, 0) == -1)
2491 errx(EX_OSERR, "waitpid()");
2492 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
2493 errx(EX_UNAVAILABLE,
2494 "preprocessor exited with status %d",
2495 WEXITSTATUS(status));
2496 else if (WIFSIGNALED(status))
2497 errx(EX_UNAVAILABLE,
2498 "preprocessor exited with signal %d",