1 /* Code to take an iptables-style command line and do it. */
4 * Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
6 * (C) 2000-2002 by the netfilter coreteam <coreteam@netfilter.org>:
7 * Paul 'Rusty' Russell <rusty@rustcorp.com.au>
8 * Marc Boucher <marc+nf@mbsi.ca>
9 * James Morris <jmorris@intercode.com.au>
10 * Harald Welte <laforge@gnumonks.org>
11 * Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42 #include <sys/utsname.h>
51 #ifndef PROC_SYS_MODPROBE
52 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
55 #define FMT_NUMERIC 0x0001
56 #define FMT_NOCOUNTS 0x0002
57 #define FMT_KILOMEGAGIGA 0x0004
58 #define FMT_OPTIONS 0x0008
59 #define FMT_NOTABLE 0x0010
60 #define FMT_NOTARGET 0x0020
61 #define FMT_VIA 0x0040
62 #define FMT_NONEWLINE 0x0080
63 #define FMT_LINENUMBERS 0x0100
65 #define FMT_PRINT_RULE (FMT_NOCOUNTS | FMT_OPTIONS | FMT_VIA \
66 | FMT_NUMERIC | FMT_NOTABLE)
67 #define FMT(tab,notab) ((format) & FMT_NOTABLE ? (notab) : (tab))
70 #define CMD_NONE 0x0000U
71 #define CMD_INSERT 0x0001U
72 #define CMD_DELETE 0x0002U
73 #define CMD_DELETE_NUM 0x0004U
74 #define CMD_REPLACE 0x0008U
75 #define CMD_APPEND 0x0010U
76 #define CMD_LIST 0x0020U
77 #define CMD_FLUSH 0x0040U
78 #define CMD_ZERO 0x0080U
79 #define CMD_NEW_CHAIN 0x0100U
80 #define CMD_DELETE_CHAIN 0x0200U
81 #define CMD_SET_POLICY 0x0400U
82 #define CMD_CHECK 0x0800U
83 #define CMD_RENAME_CHAIN 0x1000U
84 #define NUMBER_OF_CMD 13
85 static const char cmdflags[] = { 'I', 'D', 'D', 'R', 'A', 'L', 'F', 'Z',
88 #define OPTION_OFFSET 256
90 #define OPT_NONE 0x00000U
91 #define OPT_NUMERIC 0x00001U
92 #define OPT_SOURCE 0x00002U
93 #define OPT_DESTINATION 0x00004U
94 #define OPT_PROTOCOL 0x00008U
95 #define OPT_JUMP 0x00010U
96 #define OPT_VERBOSE 0x00020U
97 #define OPT_EXPANDED 0x00040U
98 #define OPT_VIANAMEIN 0x00080U
99 #define OPT_VIANAMEOUT 0x00100U
100 #define OPT_FRAGMENT 0x00200U
101 #define OPT_LINENUMBERS 0x00400U
102 #define OPT_COUNTERS 0x00800U
103 #define NUMBER_OF_OPT 12
104 static const char optflags[NUMBER_OF_OPT]
105 = { 'n', 's', 'd', 'p', 'j', 'v', 'x', 'i', 'o', 'f', '0', 'c'};
107 static struct option original_opts[] = {
108 { "append", 1, 0, 'A' },
109 { "delete", 1, 0, 'D' },
110 { "insert", 1, 0, 'I' },
111 { "replace", 1, 0, 'R' },
112 { "list", 2, 0, 'L' },
113 { "flush", 2, 0, 'F' },
114 { "zero", 2, 0, 'Z' },
115 { "new-chain", 1, 0, 'N' },
116 { "delete-chain", 2, 0, 'X' },
117 { "rename-chain", 1, 0, 'E' },
118 { "policy", 1, 0, 'P' },
119 { "source", 1, 0, 's' },
120 { "destination", 1, 0, 'd' },
121 { "src", 1, 0, 's' }, /* synonym */
122 { "dst", 1, 0, 'd' }, /* synonym */
123 { "protocol", 1, 0, 'p' },
124 { "in-interface", 1, 0, 'i' },
125 { "jump", 1, 0, 'j' },
126 { "table", 1, 0, 't' },
127 { "match", 1, 0, 'm' },
128 { "numeric", 0, 0, 'n' },
129 { "out-interface", 1, 0, 'o' },
130 { "verbose", 0, 0, 'v' },
131 { "exact", 0, 0, 'x' },
132 { "fragments", 0, 0, 'f' },
133 { "version", 0, 0, 'V' },
134 { "help", 2, 0, 'h' },
135 { "line-numbers", 0, 0, '0' },
136 { "modprobe", 1, 0, 'M' },
137 { "set-counters", 1, 0, 'c' },
138 { "goto", 1, 0, 'g' },
142 /* we need this for iptables-restore. iptables-restore.c sets line to the
143 * current line of the input file, in order to give a more precise error
144 * message. iptables itself doesn't need this, so it is initialized to the
145 * magic number of -1 */
148 static struct option *opts = original_opts;
149 static unsigned int global_option_offset = 0;
151 /* Table of legal combinations of commands and options. If any of the
152 * given commands make an option legal, that option is legal (applies to
153 * CMD_LIST and CMD_ZERO only).
160 static char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
161 /* Well, it's better than "Re: Linux vs FreeBSD" */
163 /* -n -s -d -p -j -v -x -i -o -f --line */
164 /*INSERT*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x'},
165 /*DELETE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x'},
166 /*DELETE_NUM*/{'x','x','x','x','x',' ','x','x','x','x','x'},
167 /*REPLACE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x'},
168 /*APPEND*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x'},
169 /*LIST*/ {' ','x','x','x','x',' ',' ','x','x','x',' '},
170 /*FLUSH*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
171 /*ZERO*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
172 /*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
173 /*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
174 /*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x','x'},
175 /*CHECK*/ {'x','+','+','+','x',' ','x',' ',' ',' ','x'},
176 /*RENAME*/ {'x','x','x','x','x',' ','x','x','x','x','x'}
179 static int inverse_for_options[NUMBER_OF_OPT] =
182 /* -s */ IPT_INV_SRCIP,
183 /* -d */ IPT_INV_DSTIP,
184 /* -p */ IPT_INV_PROTO,
188 /* -i */ IPT_INV_VIA_IN,
189 /* -o */ IPT_INV_VIA_OUT,
190 /* -f */ IPT_INV_FRAG,
194 const char *program_version;
195 const char *program_name;
200 /* Keeping track of external matches and targets: linked lists. */
201 struct iptables_match *iptables_matches = NULL;
202 struct iptables_target *iptables_targets = NULL;
204 /* Extra debugging from libiptc */
205 extern void dump_entries(const iptc_handle_t handle);
207 /* A few hardcoded protocols for 'all' and in case the user has no
214 /* Primitive headers... */
215 /* defined in netinet/in.h */
218 #define IPPROTO_ESP 50
221 #define IPPROTO_AH 51
225 static const struct pprot chain_protos[] = {
226 { "tcp", IPPROTO_TCP },
227 { "udp", IPPROTO_UDP },
228 { "icmp", IPPROTO_ICMP },
229 { "esp", IPPROTO_ESP },
230 { "ah", IPPROTO_AH },
231 { "sctp", IPPROTO_SCTP },
236 proto_to_name(u_int8_t proto, int nolookup)
240 if (proto && !nolookup) {
241 struct protoent *pent = getprotobynumber(proto);
246 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
247 if (chain_protos[i].num == proto)
248 return chain_protos[i].name;
254 dotted_to_addr(const char *dotted)
256 static struct in_addr addr;
257 unsigned char *addrp;
259 unsigned int onebyte;
263 /* copy dotted string, because we need to modify it */
264 strncpy(buf, dotted, sizeof(buf) - 1);
265 buf[sizeof(buf) - 1] = '\0';
266 addrp = (unsigned char *) &(addr.s_addr);
269 for (i = 0; i < 3; i++) {
270 if ((q = strchr(p, '.')) == NULL)
271 return (struct in_addr *) NULL;
274 if (string_to_number(p, 0, 255, &onebyte) == -1)
275 return (struct in_addr *) NULL;
277 addrp[i] = (unsigned char) onebyte;
281 /* we've checked 3 bytes, now we check the last one */
282 if (string_to_number(p, 0, 255, &onebyte) == -1)
283 return (struct in_addr *) NULL;
285 addrp[3] = (unsigned char) onebyte;
290 static struct in_addr *
291 network_to_addr(const char *name)
294 static struct in_addr addr;
296 if ((net = getnetbyname(name)) != NULL) {
297 if (net->n_addrtype != AF_INET)
298 return (struct in_addr *) NULL;
299 addr.s_addr = htonl((unsigned long) net->n_net);
303 return (struct in_addr *) NULL;
307 inaddrcpy(struct in_addr *dst, struct in_addr *src)
309 /* memcpy(dst, src, sizeof(struct in_addr)); */
310 dst->s_addr = src->s_addr;
313 static void free_opts(int reset_offset)
315 if (opts != original_opts) {
317 opts = original_opts;
319 global_option_offset = 0;
324 exit_error(enum exittype status, char *msg, ...)
329 fprintf(stderr, "%s v%s: ", program_name, program_version);
330 vfprintf(stderr, msg, args);
332 fprintf(stderr, "\n");
333 if (status == PARAMETER_PROBLEM)
334 exit_tryhelp(status);
335 if (status == VERSION_PROBLEM)
337 "Perhaps iptables or your kernel needs to be upgraded.\n");
338 /* On error paths, make sure that we don't leak memory */
344 exit_tryhelp(int status)
347 fprintf(stderr, "Error occurred at line: %d\n", line);
348 fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
349 program_name, program_name );
355 exit_printhelp(struct iptables_rule_match *matches)
357 struct iptables_rule_match *matchp = NULL;
358 struct iptables_target *t = NULL;
361 "Usage: %s -[AD] chain rule-specification [options]\n"
362 " %s -[RI] chain rulenum rule-specification [options]\n"
363 " %s -D chain rulenum [options]\n"
364 " %s -[LFZ] [chain] [options]\n"
366 " %s -E old-chain-name new-chain-name\n"
367 " %s -P chain target [options]\n"
368 " %s -h (print this help information)\n\n",
369 program_name, program_version, program_name, program_name,
370 program_name, program_name, program_name, program_name,
371 program_name, program_name);
375 "Either long or short options are allowed.\n"
376 " --append -A chain Append to chain\n"
377 " --delete -D chain Delete matching rule from chain\n"
378 " --delete -D chain rulenum\n"
379 " Delete rule rulenum (1 = first) from chain\n"
380 " --insert -I chain [rulenum]\n"
381 " Insert in chain as rulenum (default 1=first)\n"
382 " --replace -R chain rulenum\n"
383 " Replace rule rulenum (1 = first) in chain\n"
384 " --list -L [chain] List the rules in a chain or all chains\n"
385 " --flush -F [chain] Delete all rules in chain or all chains\n"
386 " --zero -Z [chain] Zero counters in chain or all chains\n"
387 " --new -N chain Create a new user-defined chain\n"
389 " -X [chain] Delete a user-defined chain\n"
390 " --policy -P chain target\n"
391 " Change policy on chain to target\n"
393 " -E old-chain new-chain\n"
394 " Change chain name, (moving any references)\n"
397 " --proto -p [!] proto protocol: by number or name, eg. `tcp'\n"
398 " --source -s [!] address[/mask]\n"
399 " source specification\n"
400 " --destination -d [!] address[/mask]\n"
401 " destination specification\n"
402 " --in-interface -i [!] input name[+]\n"
403 " network interface name ([+] for wildcard)\n"
404 " --jump -j target\n"
405 " target for rule (may load target extension)\n"
408 " jump to chain with no return\n"
410 " --match -m match\n"
411 " extended match (may load extension)\n"
412 " --numeric -n numeric output of addresses and ports\n"
413 " --out-interface -o [!] output name[+]\n"
414 " network interface name ([+] for wildcard)\n"
415 " --table -t table table to manipulate (default: `filter')\n"
416 " --verbose -v verbose mode\n"
417 " --line-numbers print line numbers when listing\n"
418 " --exact -x expand numbers (display exact values)\n"
419 "[!] --fragment -f match second or further fragments only\n"
420 " --modprobe=<command> try to insert modules using this command\n"
421 " --set-counters PKTS BYTES set the counter during insert/append\n"
422 "[!] --version -V print package version.\n");
424 /* Print out any special helps. A user might like to be able
425 to add a --help to the commandline, and see expected
426 results. So we call help for all specified matches & targets */
427 for (t = iptables_targets; t ;t = t->next) {
433 for (matchp = matches; matchp; matchp = matchp->next) {
435 matchp->match->help();
441 generic_opt_check(int command, int options)
445 /* Check that commands are valid with options. Complicated by the
446 * fact that if an option is legal with *any* command given, it is
447 * legal overall (ie. -z and -l).
449 for (i = 0; i < NUMBER_OF_OPT; i++) {
450 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
452 for (j = 0; j < NUMBER_OF_CMD; j++) {
453 if (!(command & (1<<j)))
456 if (!(options & (1<<i))) {
457 if (commands_v_options[j][i] == '+')
458 exit_error(PARAMETER_PROBLEM,
459 "You need to supply the `-%c' "
460 "option for this command\n",
463 if (commands_v_options[j][i] != 'x')
470 exit_error(PARAMETER_PROBLEM,
471 "Illegal option `-%c' with this command\n",
480 for (ptr = optflags; option > 1; option >>= 1, ptr++);
489 for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
495 add_command(unsigned int *cmd, const int newcmd, const int othercmds,
499 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
500 if (*cmd & (~othercmds))
501 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
502 cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
507 check_inverse(const char option[], int *invert, int *optind, int argc)
509 if (option && strcmp(option, "!") == 0) {
511 exit_error(PARAMETER_PROBLEM,
512 "Multiple `!' flags not allowed");
516 if (argc && *optind > argc)
517 exit_error(PARAMETER_PROBLEM,
518 "no argument following `!'");
527 fw_calloc(size_t count, size_t size)
531 if ((p = calloc(count, size)) == NULL) {
532 perror("iptables: calloc failed");
539 fw_malloc(size_t size)
543 if ((p = malloc(size)) == NULL) {
544 perror("iptables: malloc failed");
550 static struct in_addr *
551 host_to_addr(const char *name, unsigned int *naddr)
553 struct hostent *host;
554 struct in_addr *addr;
558 if ((host = gethostbyname(name)) != NULL) {
559 if (host->h_addrtype != AF_INET ||
560 host->h_length != sizeof(struct in_addr))
561 return (struct in_addr *) NULL;
563 while (host->h_addr_list[*naddr] != (char *) NULL)
565 addr = fw_calloc(*naddr, sizeof(struct in_addr) * *naddr);
566 for (i = 0; i < *naddr; i++)
567 inaddrcpy(&(addr[i]),
568 (struct in_addr *) host->h_addr_list[i]);
572 return (struct in_addr *) NULL;
576 addr_to_host(const struct in_addr *addr)
578 struct hostent *host;
580 if ((host = gethostbyaddr((char *) addr,
581 sizeof(struct in_addr), AF_INET)) != NULL)
582 return (char *) host->h_name;
584 return (char *) NULL;
588 * All functions starting with "parse" should succeed, otherwise
590 * Most routines return pointers to static data that may change
591 * between calls to the same or other routines with a few exceptions:
592 * "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
593 * return global static data.
596 static struct in_addr *
597 parse_hostnetwork(const char *name, unsigned int *naddrs)
599 struct in_addr *addrp, *addrptmp;
601 if ((addrptmp = dotted_to_addr(name)) != NULL ||
602 (addrptmp = network_to_addr(name)) != NULL) {
603 addrp = fw_malloc(sizeof(struct in_addr));
604 inaddrcpy(addrp, addrptmp);
608 if ((addrp = host_to_addr(name, naddrs)) != NULL)
611 exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
614 static struct in_addr *
615 parse_mask(char *mask)
617 static struct in_addr maskaddr;
618 struct in_addr *addrp;
622 /* no mask at all defaults to 32 bits */
623 maskaddr.s_addr = 0xFFFFFFFF;
626 if ((addrp = dotted_to_addr(mask)) != NULL)
627 /* dotted_to_addr already returns a network byte order addr */
629 if (string_to_number(mask, 0, 32, &bits) == -1)
630 exit_error(PARAMETER_PROBLEM,
631 "invalid mask `%s' specified", mask);
633 maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
637 maskaddr.s_addr = 0L;
642 parse_hostnetworkmask(const char *name, struct in_addr **addrpp,
643 struct in_addr *maskp, unsigned int *naddrs)
645 struct in_addr *addrp;
650 strncpy(buf, name, sizeof(buf) - 1);
651 buf[sizeof(buf) - 1] = '\0';
652 if ((p = strrchr(buf, '/')) != NULL) {
654 addrp = parse_mask(p + 1);
656 addrp = parse_mask(NULL);
657 inaddrcpy(maskp, addrp);
659 /* if a null mask is given, the name is ignored, like in "any/0" */
660 if (maskp->s_addr == 0L)
661 strcpy(buf, "0.0.0.0");
663 addrp = *addrpp = parse_hostnetwork(buf, naddrs);
665 for (i = 0, j = 0; i < n; i++) {
666 addrp[j++].s_addr &= maskp->s_addr;
667 for (k = 0; k < j - 1; k++) {
668 if (addrp[k].s_addr == addrp[j - 1].s_addr) {
677 struct iptables_match *
678 find_match(const char *name, enum ipt_tryload tryload, struct iptables_rule_match **matches)
680 struct iptables_match *ptr;
682 for (ptr = iptables_matches; ptr; ptr = ptr->next) {
683 if (strcmp(name, ptr->name) == 0)
687 #ifndef NO_SHARED_LIBS
688 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
689 char path[strlen(lib_dir) + sizeof("/libipt_.so")
691 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
692 if (dlopen(path, RTLD_NOW)) {
693 /* Found library. If it didn't register itself,
694 maybe they specified target as match. */
695 ptr = find_match(name, DONT_LOAD, NULL);
698 exit_error(PARAMETER_PROBLEM,
699 "Couldn't load match `%s'\n",
701 } else if (tryload == LOAD_MUST_SUCCEED)
702 exit_error(PARAMETER_PROBLEM,
703 "Couldn't load match `%s':%s\n",
707 if (ptr && !ptr->loaded) {
708 if (tryload != DONT_LOAD)
713 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
714 exit_error(PARAMETER_PROBLEM,
715 "Couldn't find match `%s'\n", name);
719 if (ptr && matches) {
720 struct iptables_rule_match **i;
721 struct iptables_rule_match *newentry;
723 newentry = fw_malloc(sizeof(struct iptables_rule_match));
725 for (i = matches; *i; i = &(*i)->next);
726 newentry->match = ptr;
727 newentry->next = NULL;
734 /* Christophe Burki wants `-p 6' to imply `-m tcp'. */
735 static struct iptables_match *
736 find_proto(const char *pname, enum ipt_tryload tryload, int nolookup, struct iptables_rule_match **matches)
740 if (string_to_number(pname, 0, 255, &proto) != -1) {
741 char *protoname = proto_to_name(proto, nolookup);
744 return find_match(protoname, tryload, matches);
746 return find_match(pname, tryload, matches);
752 parse_protocol(const char *s)
756 if (string_to_number(s, 0, 255, &proto) == -1) {
757 struct protoent *pent;
759 if ((pent = getprotobyname(s)))
760 proto = pent->p_proto;
764 i < sizeof(chain_protos)/sizeof(struct pprot);
766 if (strcmp(s, chain_protos[i].name) == 0) {
767 proto = chain_protos[i].num;
771 if (i == sizeof(chain_protos)/sizeof(struct pprot))
772 exit_error(PARAMETER_PROBLEM,
773 "unknown protocol `%s' specified",
778 return (u_int16_t)proto;
781 void parse_interface(const char *arg, char *vianame, unsigned char *mask)
783 int vialen = strlen(arg);
786 memset(mask, 0, IFNAMSIZ);
787 memset(vianame, 0, IFNAMSIZ);
789 if (vialen + 1 > IFNAMSIZ)
790 exit_error(PARAMETER_PROBLEM,
791 "interface name `%s' must be shorter than IFNAMSIZ"
792 " (%i)", arg, IFNAMSIZ-1);
794 strcpy(vianame, arg);
795 if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
796 memset(mask, 0, IFNAMSIZ);
797 else if (vianame[vialen - 1] == '+') {
798 memset(mask, 0xFF, vialen - 1);
799 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
800 /* Don't remove `+' here! -HW */
802 /* Include nul-terminator in match */
803 memset(mask, 0xFF, vialen + 1);
804 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
805 for (i = 0; vianame[i]; i++) {
806 if (!isalnum(vianame[i])
808 && vianame[i] != '.') {
809 printf("Warning: wierd character in interface"
810 " `%s' (No aliases, :, ! or *).\n",
820 parse_rulenumber(const char *rule)
822 unsigned int rulenum;
824 if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
825 exit_error(PARAMETER_PROBLEM,
826 "Invalid rule number `%s'", rule);
832 parse_target(const char *targetname)
836 if (strlen(targetname) < 1)
837 exit_error(PARAMETER_PROBLEM,
838 "Invalid target name (too short)");
840 if (strlen(targetname)+1 > sizeof(ipt_chainlabel))
841 exit_error(PARAMETER_PROBLEM,
842 "Invalid target name `%s' (%u chars max)",
843 targetname, (unsigned int)sizeof(ipt_chainlabel)-1);
845 for (ptr = targetname; *ptr; ptr++)
847 exit_error(PARAMETER_PROBLEM,
848 "Invalid target name `%s'", targetname);
853 addr_to_network(const struct in_addr *addr)
857 if ((net = getnetbyaddr((long) ntohl(addr->s_addr), AF_INET)) != NULL)
858 return (char *) net->n_name;
860 return (char *) NULL;
864 addr_to_dotted(const struct in_addr *addrp)
867 const unsigned char *bytep;
869 bytep = (const unsigned char *) &(addrp->s_addr);
870 sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]);
875 addr_to_anyname(const struct in_addr *addr)
879 if ((name = addr_to_host(addr)) != NULL ||
880 (name = addr_to_network(addr)) != NULL)
883 return addr_to_dotted(addr);
887 mask_to_dotted(const struct in_addr *mask)
891 u_int32_t maskaddr, bits;
893 maskaddr = ntohl(mask->s_addr);
895 if (maskaddr == 0xFFFFFFFFL)
896 /* we don't want to see "/32" */
901 while (--i >= 0 && maskaddr != bits)
904 sprintf(buf, "/%d", i);
906 /* mask was not a decent combination of 1's and 0's */
907 sprintf(buf, "/%s", addr_to_dotted(mask));
913 string_to_number_ll(const char *s, unsigned long long min, unsigned long long max,
914 unsigned long long *ret)
916 unsigned long long number;
919 /* Handle hex, octal, etc. */
921 number = strtoull(s, &end, 0);
922 if (*end == '\0' && end != s) {
923 /* we parsed a number, let's see if we want this */
924 if (errno != ERANGE && min <= number && (!max || number <= max)) {
933 string_to_number_l(const char *s, unsigned long min, unsigned long max,
937 unsigned long long number;
939 result = string_to_number_ll(s, min, max, &number);
940 *ret = (unsigned long)number;
945 int string_to_number(const char *s, unsigned int min, unsigned int max,
949 unsigned long number;
951 result = string_to_number_l(s, min, max, &number);
952 *ret = (unsigned int)number;
958 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
961 if (*options & option)
962 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
968 for (i = 0; 1 << i != option; i++);
970 if (!inverse_for_options[i])
971 exit_error(PARAMETER_PROBLEM,
972 "cannot have ! before -%c",
974 *invflg |= inverse_for_options[i];
978 struct iptables_target *
979 find_target(const char *name, enum ipt_tryload tryload)
981 struct iptables_target *ptr;
983 /* Standard target? */
984 if (strcmp(name, "") == 0
985 || strcmp(name, IPTC_LABEL_ACCEPT) == 0
986 || strcmp(name, IPTC_LABEL_DROP) == 0
987 || strcmp(name, IPTC_LABEL_QUEUE) == 0
988 || strcmp(name, IPTC_LABEL_RETURN) == 0)
991 for (ptr = iptables_targets; ptr; ptr = ptr->next) {
992 if (strcmp(name, ptr->name) == 0)
996 #ifndef NO_SHARED_LIBS
997 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
998 char path[strlen(lib_dir) + sizeof("/libipt_.so")
1000 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
1001 if (dlopen(path, RTLD_NOW)) {
1002 /* Found library. If it didn't register itself,
1003 maybe they specified match as a target. */
1004 ptr = find_target(name, DONT_LOAD);
1006 exit_error(PARAMETER_PROBLEM,
1007 "Couldn't load target `%s'\n",
1009 } else if (tryload == LOAD_MUST_SUCCEED)
1010 exit_error(PARAMETER_PROBLEM,
1011 "Couldn't load target `%s':%s\n",
1015 if (ptr && !ptr->loaded) {
1016 if (tryload != DONT_LOAD)
1021 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
1022 exit_error(PARAMETER_PROBLEM,
1023 "Couldn't find target `%s'\n", name);
1033 static struct option *
1034 merge_options(struct option *oldopts, const struct option *newopts,
1035 unsigned int *option_offset)
1037 unsigned int num_old, num_new, i;
1038 struct option *merge;
1040 for (num_old = 0; oldopts[num_old].name; num_old++);
1041 for (num_new = 0; newopts[num_new].name; num_new++);
1043 global_option_offset += OPTION_OFFSET;
1044 *option_offset = global_option_offset;
1046 merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
1047 memcpy(merge, oldopts, num_old * sizeof(struct option));
1048 free_opts(0); /* Release previous options merged if any */
1049 for (i = 0; i < num_new; i++) {
1050 merge[num_old + i] = newopts[i];
1051 merge[num_old + i].val += *option_offset;
1053 memset(merge + num_old + num_new, 0, sizeof(struct option));
1058 static int compatible_revision(const char *name, u_int8_t revision, int opt)
1060 struct ipt_get_revision rev;
1061 socklen_t s = sizeof(rev);
1062 int max_rev, sockfd;
1064 sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
1066 fprintf(stderr, "Could not open socket to kernel: %s\n",
1071 strcpy(rev.name, name);
1072 rev.revision = revision;
1074 max_rev = getsockopt(sockfd, IPPROTO_IP, opt, &rev, &s);
1076 /* Definitely don't support this? */
1077 if (errno == EPROTONOSUPPORT) {
1080 } else if (errno == ENOPROTOOPT) {
1082 /* Assume only revision 0 support (old kernel) */
1083 return (revision == 0);
1085 fprintf(stderr, "getsockopt failed strangely: %s\n",
1094 static int compatible_match_revision(const char *name, u_int8_t revision)
1096 return compatible_revision(name, revision, IPT_SO_GET_REVISION_MATCH);
1099 static int compatible_target_revision(const char *name, u_int8_t revision)
1101 return compatible_revision(name, revision, IPT_SO_GET_REVISION_TARGET);
1105 register_match(struct iptables_match *me)
1107 struct iptables_match **i, *old;
1109 if (strcmp(me->version, program_version) != 0) {
1110 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
1111 program_name, me->name, me->version, program_version);
1115 /* Revision field stole a char from name. */
1116 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1117 fprintf(stderr, "%s: target `%s' has invalid name\n",
1118 program_name, me->name);
1122 old = find_match(me->name, DURING_LOAD, NULL);
1124 if (old->revision == me->revision) {
1126 "%s: match `%s' already registered.\n",
1127 program_name, me->name);
1131 /* Now we have two (or more) options, check compatibility. */
1132 if (compatible_match_revision(old->name, old->revision)
1133 && old->revision > me->revision)
1136 /* Replace if compatible. */
1137 if (!compatible_match_revision(me->name, me->revision))
1140 /* Delete old one. */
1141 for (i = &iptables_matches; *i!=old; i = &(*i)->next);
1145 if (me->size != IPT_ALIGN(me->size)) {
1146 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
1147 program_name, me->name, (unsigned int)me->size);
1151 /* Append to list. */
1152 for (i = &iptables_matches; *i; i = &(*i)->next);
1161 register_target(struct iptables_target *me)
1163 struct iptables_target *old;
1165 if (strcmp(me->version, program_version) != 0) {
1166 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
1167 program_name, me->name, me->version, program_version);
1171 /* Revision field stole a char from name. */
1172 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1173 fprintf(stderr, "%s: target `%s' has invalid name\n",
1174 program_name, me->name);
1178 old = find_target(me->name, DURING_LOAD);
1180 struct iptables_target **i;
1182 if (old->revision == me->revision) {
1184 "%s: target `%s' already registered.\n",
1185 program_name, me->name);
1189 /* Now we have two (or more) options, check compatibility. */
1190 if (compatible_target_revision(old->name, old->revision)
1191 && old->revision > me->revision)
1194 /* Replace if compatible. */
1195 if (!compatible_target_revision(me->name, me->revision))
1198 /* Delete old one. */
1199 for (i = &iptables_targets; *i!=old; i = &(*i)->next);
1203 if (me->size != IPT_ALIGN(me->size)) {
1204 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
1205 program_name, me->name, (unsigned int)me->size);
1209 /* Prepend to list. */
1210 me->next = iptables_targets;
1211 iptables_targets = me;
1217 print_num(u_int64_t number, unsigned int format)
1219 if (format & FMT_KILOMEGAGIGA) {
1220 if (number > 99999) {
1221 number = (number + 500) / 1000;
1222 if (number > 9999) {
1223 number = (number + 500) / 1000;
1224 if (number > 9999) {
1225 number = (number + 500) / 1000;
1226 if (number > 9999) {
1227 number = (number + 500) / 1000;
1228 printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
1230 else printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
1232 else printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
1234 printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
1236 printf(FMT("%5llu ","%llu "), (unsigned long long)number);
1238 printf(FMT("%8llu ","%llu "), (unsigned long long)number);
1243 print_header(unsigned int format, const char *chain, iptc_handle_t *handle)
1245 struct ipt_counters counters;
1246 const char *pol = iptc_get_policy(chain, &counters, handle);
1247 printf("Chain %s", chain);
1249 printf(" (policy %s", pol);
1250 if (!(format & FMT_NOCOUNTS)) {
1252 print_num(counters.pcnt, (format|FMT_NOTABLE));
1253 fputs("packets, ", stdout);
1254 print_num(counters.bcnt, (format|FMT_NOTABLE));
1255 fputs("bytes", stdout);
1260 if (!iptc_get_references(&refs, chain, handle))
1261 printf(" (ERROR obtaining refs)\n");
1263 printf(" (%u references)\n", refs);
1266 if (format & FMT_LINENUMBERS)
1267 printf(FMT("%-4s ", "%s "), "num");
1268 if (!(format & FMT_NOCOUNTS)) {
1269 if (format & FMT_KILOMEGAGIGA) {
1270 printf(FMT("%5s ","%s "), "pkts");
1271 printf(FMT("%5s ","%s "), "bytes");
1273 printf(FMT("%8s ","%s "), "pkts");
1274 printf(FMT("%10s ","%s "), "bytes");
1277 if (!(format & FMT_NOTARGET))
1278 printf(FMT("%-9s ","%s "), "target");
1279 fputs(" prot ", stdout);
1280 if (format & FMT_OPTIONS)
1281 fputs("opt", stdout);
1282 if (format & FMT_VIA) {
1283 printf(FMT(" %-6s ","%s "), "in");
1284 printf(FMT("%-6s ","%s "), "out");
1286 printf(FMT(" %-19s ","%s "), "source");
1287 printf(FMT(" %-19s "," %s "), "destination");
1293 print_match(const struct ipt_entry_match *m,
1294 const struct ipt_ip *ip,
1297 struct iptables_match *match = find_match(m->u.user.name, TRY_LOAD, NULL);
1301 match->print(ip, m, numeric);
1303 printf("%s ", match->name);
1305 if (m->u.user.name[0])
1306 printf("UNKNOWN match `%s' ", m->u.user.name);
1308 /* Don't stop iterating. */
1312 /* e is called `fw' here for hysterical raisins */
1314 print_firewall(const struct ipt_entry *fw,
1315 const char *targname,
1317 unsigned int format,
1318 const iptc_handle_t handle)
1320 struct iptables_target *target = NULL;
1321 const struct ipt_entry_target *t;
1325 if (!iptc_is_chain(targname, handle))
1326 target = find_target(targname, TRY_LOAD);
1328 target = find_target(IPT_STANDARD_TARGET, LOAD_MUST_SUCCEED);
1330 t = ipt_get_target((struct ipt_entry *)fw);
1331 flags = fw->ip.flags;
1333 if (format & FMT_LINENUMBERS)
1334 printf(FMT("%-4u ", "%u "), num+1);
1336 if (!(format & FMT_NOCOUNTS)) {
1337 print_num(fw->counters.pcnt, format);
1338 print_num(fw->counters.bcnt, format);
1341 if (!(format & FMT_NOTARGET))
1342 printf(FMT("%-9s ", "%s "), targname);
1344 fputc(fw->ip.invflags & IPT_INV_PROTO ? '!' : ' ', stdout);
1346 char *pname = proto_to_name(fw->ip.proto, format&FMT_NUMERIC);
1348 printf(FMT("%-5s", "%s "), pname);
1350 printf(FMT("%-5hu", "%hu "), fw->ip.proto);
1353 if (format & FMT_OPTIONS) {
1354 if (format & FMT_NOTABLE)
1355 fputs("opt ", stdout);
1356 fputc(fw->ip.invflags & IPT_INV_FRAG ? '!' : '-', stdout);
1357 fputc(flags & IPT_F_FRAG ? 'f' : '-', stdout);
1361 if (format & FMT_VIA) {
1362 char iface[IFNAMSIZ+2];
1364 if (fw->ip.invflags & IPT_INV_VIA_IN) {
1368 else iface[0] = '\0';
1370 if (fw->ip.iniface[0] != '\0') {
1371 strcat(iface, fw->ip.iniface);
1373 else if (format & FMT_NUMERIC) strcat(iface, "*");
1374 else strcat(iface, "any");
1375 printf(FMT(" %-6s ","in %s "), iface);
1377 if (fw->ip.invflags & IPT_INV_VIA_OUT) {
1381 else iface[0] = '\0';
1383 if (fw->ip.outiface[0] != '\0') {
1384 strcat(iface, fw->ip.outiface);
1386 else if (format & FMT_NUMERIC) strcat(iface, "*");
1387 else strcat(iface, "any");
1388 printf(FMT("%-6s ","out %s "), iface);
1391 fputc(fw->ip.invflags & IPT_INV_SRCIP ? '!' : ' ', stdout);
1392 if (fw->ip.smsk.s_addr == 0L && !(format & FMT_NUMERIC))
1393 printf(FMT("%-19s ","%s "), "anywhere");
1395 if (format & FMT_NUMERIC)
1396 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.src)));
1398 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.src)));
1399 strcat(buf, mask_to_dotted(&(fw->ip.smsk)));
1400 printf(FMT("%-19s ","%s "), buf);
1403 fputc(fw->ip.invflags & IPT_INV_DSTIP ? '!' : ' ', stdout);
1404 if (fw->ip.dmsk.s_addr == 0L && !(format & FMT_NUMERIC))
1405 printf(FMT("%-19s ","-> %s"), "anywhere");
1407 if (format & FMT_NUMERIC)
1408 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.dst)));
1410 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.dst)));
1411 strcat(buf, mask_to_dotted(&(fw->ip.dmsk)));
1412 printf(FMT("%-19s ","-> %s"), buf);
1415 if (format & FMT_NOTABLE)
1419 if(fw->ip.flags & IPT_F_GOTO)
1423 IPT_MATCH_ITERATE(fw, print_match, &fw->ip, format & FMT_NUMERIC);
1427 /* Print the target information. */
1428 target->print(&fw->ip, t, format & FMT_NUMERIC);
1429 } else if (t->u.target_size != sizeof(*t))
1430 printf("[%u bytes of unknown target data] ",
1431 (unsigned int)(t->u.target_size - sizeof(*t)));
1433 if (!(format & FMT_NONEWLINE))
1434 fputc('\n', stdout);
1438 print_firewall_line(const struct ipt_entry *fw,
1439 const iptc_handle_t h)
1441 struct ipt_entry_target *t;
1443 t = ipt_get_target((struct ipt_entry *)fw);
1444 print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
1448 append_entry(const ipt_chainlabel chain,
1449 struct ipt_entry *fw,
1450 unsigned int nsaddrs,
1451 const struct in_addr saddrs[],
1452 unsigned int ndaddrs,
1453 const struct in_addr daddrs[],
1455 iptc_handle_t *handle)
1460 for (i = 0; i < nsaddrs; i++) {
1461 fw->ip.src.s_addr = saddrs[i].s_addr;
1462 for (j = 0; j < ndaddrs; j++) {
1463 fw->ip.dst.s_addr = daddrs[j].s_addr;
1465 print_firewall_line(fw, *handle);
1466 ret &= iptc_append_entry(chain, fw, handle);
1474 replace_entry(const ipt_chainlabel chain,
1475 struct ipt_entry *fw,
1476 unsigned int rulenum,
1477 const struct in_addr *saddr,
1478 const struct in_addr *daddr,
1480 iptc_handle_t *handle)
1482 fw->ip.src.s_addr = saddr->s_addr;
1483 fw->ip.dst.s_addr = daddr->s_addr;
1486 print_firewall_line(fw, *handle);
1487 return iptc_replace_entry(chain, fw, rulenum, handle);
1491 insert_entry(const ipt_chainlabel chain,
1492 struct ipt_entry *fw,
1493 unsigned int rulenum,
1494 unsigned int nsaddrs,
1495 const struct in_addr saddrs[],
1496 unsigned int ndaddrs,
1497 const struct in_addr daddrs[],
1499 iptc_handle_t *handle)
1504 for (i = 0; i < nsaddrs; i++) {
1505 fw->ip.src.s_addr = saddrs[i].s_addr;
1506 for (j = 0; j < ndaddrs; j++) {
1507 fw->ip.dst.s_addr = daddrs[j].s_addr;
1509 print_firewall_line(fw, *handle);
1510 ret &= iptc_insert_entry(chain, fw, rulenum, handle);
1517 static unsigned char *
1518 make_delete_mask(struct ipt_entry *fw, struct iptables_rule_match *matches)
1520 /* Establish mask for comparison */
1522 struct iptables_rule_match *matchp;
1523 unsigned char *mask, *mptr;
1525 size = sizeof(struct ipt_entry);
1526 for (matchp = matches; matchp; matchp = matchp->next)
1527 size += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1529 mask = fw_calloc(1, size
1530 + IPT_ALIGN(sizeof(struct ipt_entry_target))
1531 + iptables_targets->size);
1533 memset(mask, 0xFF, sizeof(struct ipt_entry));
1534 mptr = mask + sizeof(struct ipt_entry);
1536 for (matchp = matches; matchp; matchp = matchp->next) {
1538 IPT_ALIGN(sizeof(struct ipt_entry_match))
1539 + matchp->match->userspacesize);
1540 mptr += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1544 IPT_ALIGN(sizeof(struct ipt_entry_target))
1545 + iptables_targets->userspacesize);
1551 delete_entry(const ipt_chainlabel chain,
1552 struct ipt_entry *fw,
1553 unsigned int nsaddrs,
1554 const struct in_addr saddrs[],
1555 unsigned int ndaddrs,
1556 const struct in_addr daddrs[],
1558 iptc_handle_t *handle,
1559 struct iptables_rule_match *matches)
1563 unsigned char *mask;
1565 mask = make_delete_mask(fw, matches);
1566 for (i = 0; i < nsaddrs; i++) {
1567 fw->ip.src.s_addr = saddrs[i].s_addr;
1568 for (j = 0; j < ndaddrs; j++) {
1569 fw->ip.dst.s_addr = daddrs[j].s_addr;
1571 print_firewall_line(fw, *handle);
1572 ret &= iptc_delete_entry(chain, fw, mask, handle);
1581 for_each_chain(int (*fn)(const ipt_chainlabel, int, iptc_handle_t *),
1582 int verbose, int builtinstoo, iptc_handle_t *handle)
1587 unsigned int i, chaincount = 0;
1589 chain = iptc_first_chain(handle);
1592 chain = iptc_next_chain(handle);
1595 chains = fw_malloc(sizeof(ipt_chainlabel) * chaincount);
1597 chain = iptc_first_chain(handle);
1599 strcpy(chains + i*sizeof(ipt_chainlabel), chain);
1601 chain = iptc_next_chain(handle);
1604 for (i = 0; i < chaincount; i++) {
1606 && iptc_builtin(chains + i*sizeof(ipt_chainlabel),
1609 ret &= fn(chains + i*sizeof(ipt_chainlabel), verbose, handle);
1617 flush_entries(const ipt_chainlabel chain, int verbose,
1618 iptc_handle_t *handle)
1621 return for_each_chain(flush_entries, verbose, 1, handle);
1624 fprintf(stdout, "Flushing chain `%s'\n", chain);
1625 return iptc_flush_entries(chain, handle);
1629 zero_entries(const ipt_chainlabel chain, int verbose,
1630 iptc_handle_t *handle)
1633 return for_each_chain(zero_entries, verbose, 1, handle);
1636 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1637 return iptc_zero_entries(chain, handle);
1641 delete_chain(const ipt_chainlabel chain, int verbose,
1642 iptc_handle_t *handle)
1645 return for_each_chain(delete_chain, verbose, 0, handle);
1648 fprintf(stdout, "Deleting chain `%s'\n", chain);
1649 return iptc_delete_chain(chain, handle);
1653 list_entries(const ipt_chainlabel chain, int verbose, int numeric,
1654 int expanded, int linenumbers, iptc_handle_t *handle)
1657 unsigned int format;
1660 format = FMT_OPTIONS;
1662 format |= FMT_NOCOUNTS;
1667 format |= FMT_NUMERIC;
1670 format |= FMT_KILOMEGAGIGA;
1673 format |= FMT_LINENUMBERS;
1675 for (this = iptc_first_chain(handle);
1677 this = iptc_next_chain(handle)) {
1678 const struct ipt_entry *i;
1681 if (chain && strcmp(chain, this) != 0)
1684 if (found) printf("\n");
1686 print_header(format, this, handle);
1687 i = iptc_first_rule(this, handle);
1692 iptc_get_target(i, handle),
1696 i = iptc_next_rule(i, handle);
1705 static char *get_modprobe(void)
1710 #define PROCFILE_BUFSIZ 1024
1711 procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
1715 ret = (char *) malloc(PROCFILE_BUFSIZ);
1717 memset(ret, 0, PROCFILE_BUFSIZ);
1718 switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
1720 case PROCFILE_BUFSIZ: goto fail; /* Partial read. Wierd */
1722 if (ret[strlen(ret)-1]=='\n')
1723 ret[strlen(ret)-1]=0;
1733 int iptables_insmod(const char *modname, const char *modprobe)
1739 /* If they don't explicitly set it, read out of kernel */
1741 buf = get_modprobe();
1749 argv[0] = (char *)modprobe;
1750 argv[1] = (char *)modname;
1752 execv(argv[0], argv);
1754 /* not usually reached */
1759 default: /* parent */
1764 if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
1769 static struct ipt_entry *
1770 generate_entry(const struct ipt_entry *fw,
1771 struct iptables_rule_match *matches,
1772 struct ipt_entry_target *target)
1775 struct iptables_rule_match *matchp;
1776 struct ipt_entry *e;
1778 size = sizeof(struct ipt_entry);
1779 for (matchp = matches; matchp; matchp = matchp->next)
1780 size += matchp->match->m->u.match_size;
1782 e = fw_malloc(size + target->u.target_size);
1784 e->target_offset = size;
1785 e->next_offset = size + target->u.target_size;
1788 for (matchp = matches; matchp; matchp = matchp->next) {
1789 memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1790 size += matchp->match->m->u.match_size;
1792 memcpy(e->elems + size, target, target->u.target_size);
1797 void clear_rule_matches(struct iptables_rule_match **matches)
1799 struct iptables_rule_match *matchp, *tmp;
1801 for (matchp = *matches; matchp;) {
1803 if (matchp->match->m)
1804 free(matchp->match->m);
1812 static void set_revision(char *name, u_int8_t revision)
1814 /* Old kernel sources don't have ".revision" field,
1815 but we stole a byte from name. */
1816 name[IPT_FUNCTION_MAXNAMELEN - 2] = '\0';
1817 name[IPT_FUNCTION_MAXNAMELEN - 1] = revision;
1821 get_kernel_version(void) {
1822 static struct utsname uts;
1823 int x = 0, y = 0, z = 0;
1825 if (uname(&uts) == -1) {
1826 fprintf(stderr, "Unable to retrieve kernel version.\n");
1831 sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
1832 kernel_version = LINUX_VERSION(x, y, z);
1835 int do_command(int argc, char *argv[], char **table, iptc_handle_t *handle)
1837 struct ipt_entry fw, *e = NULL;
1839 unsigned int nsaddrs = 0, ndaddrs = 0;
1840 struct in_addr *saddrs = NULL, *daddrs = NULL;
1843 const char *chain = NULL;
1844 const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1845 const char *policy = NULL, *newname = NULL;
1846 unsigned int rulenum = 0, options = 0, command = 0;
1847 const char *pcnt = NULL, *bcnt = NULL;
1849 struct iptables_match *m;
1850 struct iptables_rule_match *matches = NULL;
1851 struct iptables_rule_match *matchp;
1852 struct iptables_target *target = NULL;
1853 struct iptables_target *t;
1854 const char *jumpto = "";
1855 char *protocol = NULL;
1856 const char *modprobe = NULL;
1859 memset(&fw, 0, sizeof(fw));
1861 /* re-set optind to 0 in case do_command gets called
1865 /* clear mflags in case do_command gets called a second time
1866 * (we clear the global list of all matches for security)*/
1867 for (m = iptables_matches; m; m = m->next)
1870 for (t = iptables_targets; t; t = t->next) {
1875 /* Suppress error messages: we may add new options if we
1876 demand-load a protocol. */
1879 while ((c = getopt_long(argc, argv,
1880 "-A:D:R:I:L::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:fbvnt:m:xc:g:",
1881 opts, NULL)) != -1) {
1887 add_command(&command, CMD_APPEND, CMD_NONE,
1893 add_command(&command, CMD_DELETE, CMD_NONE,
1896 if (optind < argc && argv[optind][0] != '-'
1897 && argv[optind][0] != '!') {
1898 rulenum = parse_rulenumber(argv[optind++]);
1899 command = CMD_DELETE_NUM;
1904 add_command(&command, CMD_REPLACE, CMD_NONE,
1907 if (optind < argc && argv[optind][0] != '-'
1908 && argv[optind][0] != '!')
1909 rulenum = parse_rulenumber(argv[optind++]);
1911 exit_error(PARAMETER_PROBLEM,
1912 "-%c requires a rule number",
1913 cmd2char(CMD_REPLACE));
1917 add_command(&command, CMD_INSERT, CMD_NONE,
1920 if (optind < argc && argv[optind][0] != '-'
1921 && argv[optind][0] != '!')
1922 rulenum = parse_rulenumber(argv[optind++]);
1927 add_command(&command, CMD_LIST, CMD_ZERO,
1929 if (optarg) chain = optarg;
1930 else if (optind < argc && argv[optind][0] != '-'
1931 && argv[optind][0] != '!')
1932 chain = argv[optind++];
1936 add_command(&command, CMD_FLUSH, CMD_NONE,
1938 if (optarg) chain = optarg;
1939 else if (optind < argc && argv[optind][0] != '-'
1940 && argv[optind][0] != '!')
1941 chain = argv[optind++];
1945 add_command(&command, CMD_ZERO, CMD_LIST,
1947 if (optarg) chain = optarg;
1948 else if (optind < argc && argv[optind][0] != '-'
1949 && argv[optind][0] != '!')
1950 chain = argv[optind++];
1954 if (optarg && (*optarg == '-' || *optarg == '!'))
1955 exit_error(PARAMETER_PROBLEM,
1956 "chain name not allowed to start "
1957 "with `%c'\n", *optarg);
1958 if (find_target(optarg, TRY_LOAD))
1959 exit_error(PARAMETER_PROBLEM,
1960 "chain name may not clash "
1961 "with target name\n");
1962 add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
1968 add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
1970 if (optarg) chain = optarg;
1971 else if (optind < argc && argv[optind][0] != '-'
1972 && argv[optind][0] != '!')
1973 chain = argv[optind++];
1977 add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
1980 if (optind < argc && argv[optind][0] != '-'
1981 && argv[optind][0] != '!')
1982 newname = argv[optind++];
1984 exit_error(PARAMETER_PROBLEM,
1985 "-%c requires old-chain-name and "
1987 cmd2char(CMD_RENAME_CHAIN));
1991 add_command(&command, CMD_SET_POLICY, CMD_NONE,
1994 if (optind < argc && argv[optind][0] != '-'
1995 && argv[optind][0] != '!')
1996 policy = argv[optind++];
1998 exit_error(PARAMETER_PROBLEM,
1999 "-%c requires a chain and a policy",
2000 cmd2char(CMD_SET_POLICY));
2005 optarg = argv[optind];
2007 /* iptables -p icmp -h */
2008 if (!matches && protocol)
2009 find_match(protocol, TRY_LOAD, &matches);
2011 exit_printhelp(matches);
2017 check_inverse(optarg, &invert, &optind, argc);
2018 set_option(&options, OPT_PROTOCOL, &fw.ip.invflags,
2021 /* Canonicalize into lower case */
2022 for (protocol = argv[optind-1]; *protocol; protocol++)
2023 *protocol = tolower(*protocol);
2025 protocol = argv[optind-1];
2026 fw.ip.proto = parse_protocol(protocol);
2028 if (fw.ip.proto == 0
2029 && (fw.ip.invflags & IPT_INV_PROTO))
2030 exit_error(PARAMETER_PROBLEM,
2031 "rule would never match protocol");
2035 check_inverse(optarg, &invert, &optind, argc);
2036 set_option(&options, OPT_SOURCE, &fw.ip.invflags,
2038 shostnetworkmask = argv[optind-1];
2042 check_inverse(optarg, &invert, &optind, argc);
2043 set_option(&options, OPT_DESTINATION, &fw.ip.invflags,
2045 dhostnetworkmask = argv[optind-1];
2050 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2052 fw.ip.flags |= IPT_F_GOTO;
2053 jumpto = parse_target(optarg);
2058 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2060 jumpto = parse_target(optarg);
2061 /* TRY_LOAD (may be chain name) */
2062 target = find_target(jumpto, TRY_LOAD);
2067 size = IPT_ALIGN(sizeof(struct ipt_entry_target))
2070 target->t = fw_calloc(1, size);
2071 target->t->u.target_size = size;
2072 strcpy(target->t->u.user.name, jumpto);
2073 set_revision(target->t->u.user.name,
2075 if (target->init != NULL)
2076 target->init(target->t, &fw.nfcache);
2077 opts = merge_options(opts, target->extra_opts, &target->option_offset);
2083 check_inverse(optarg, &invert, &optind, argc);
2084 set_option(&options, OPT_VIANAMEIN, &fw.ip.invflags,
2086 parse_interface(argv[optind-1],
2088 fw.ip.iniface_mask);
2092 check_inverse(optarg, &invert, &optind, argc);
2093 set_option(&options, OPT_VIANAMEOUT, &fw.ip.invflags,
2095 parse_interface(argv[optind-1],
2097 fw.ip.outiface_mask);
2101 set_option(&options, OPT_FRAGMENT, &fw.ip.invflags,
2103 fw.ip.flags |= IPT_F_FRAG;
2108 set_option(&options, OPT_VERBOSE,
2109 &fw.ip.invflags, invert);
2117 exit_error(PARAMETER_PROBLEM,
2118 "unexpected ! flag before --match");
2120 m = find_match(optarg, LOAD_MUST_SUCCEED, &matches);
2121 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2123 m->m = fw_calloc(1, size);
2124 m->m->u.match_size = size;
2125 strcpy(m->m->u.user.name, m->name);
2126 set_revision(m->m->u.user.name, m->revision);
2127 if (m->init != NULL)
2128 m->init(m->m, &fw.nfcache);
2129 opts = merge_options(opts, m->extra_opts, &m->option_offset);
2134 set_option(&options, OPT_NUMERIC, &fw.ip.invflags,
2140 exit_error(PARAMETER_PROBLEM,
2141 "unexpected ! flag before --table");
2142 *table = argv[optind-1];
2146 set_option(&options, OPT_EXPANDED, &fw.ip.invflags,
2152 printf("Not %s ;-)\n", program_version);
2155 program_name, program_version);
2159 set_option(&options, OPT_LINENUMBERS, &fw.ip.invflags,
2169 set_option(&options, OPT_COUNTERS, &fw.ip.invflags,
2172 if (optind < argc && argv[optind][0] != '-'
2173 && argv[optind][0] != '!')
2174 bcnt = argv[optind++];
2176 exit_error(PARAMETER_PROBLEM,
2177 "-%c requires packet and byte counter",
2178 opt2char(OPT_COUNTERS));
2180 if (sscanf(pcnt, "%llu", (unsigned long long *)&fw.counters.pcnt) != 1)
2181 exit_error(PARAMETER_PROBLEM,
2182 "-%c packet counter not numeric",
2183 opt2char(OPT_COUNTERS));
2185 if (sscanf(bcnt, "%llu", (unsigned long long *)&fw.counters.bcnt) != 1)
2186 exit_error(PARAMETER_PROBLEM,
2187 "-%c byte counter not numeric",
2188 opt2char(OPT_COUNTERS));
2193 case 1: /* non option */
2194 if (optarg[0] == '!' && optarg[1] == '\0') {
2196 exit_error(PARAMETER_PROBLEM,
2197 "multiple consecutive ! not"
2203 printf("Bad argument `%s'\n", optarg);
2207 /* FIXME: This scheme doesn't allow two of the same
2210 || !(target->parse(c - target->option_offset,
2213 &fw, &target->t))) {
2214 for (matchp = matches; matchp; matchp = matchp->next) {
2215 if (matchp->match->parse(c - matchp->match->option_offset,
2217 &matchp->match->mflags,
2223 m = matchp ? matchp->match : NULL;
2225 /* If you listen carefully, you can
2226 actually hear this code suck. */
2228 /* some explanations (after four different bugs
2229 * in 3 different releases): If we encountere a
2230 * parameter, that has not been parsed yet,
2231 * it's not an option of an explicitly loaded
2232 * match or a target. However, we support
2233 * implicit loading of the protocol match
2234 * extension. '-p tcp' means 'l4 proto 6' and
2235 * at the same time 'load tcp protocol match on
2236 * demand if we specify --dport'.
2238 * To make this work, we need to make sure:
2239 * - the parameter has not been parsed by
2241 * - a protocol has been specified
2242 * - the protocol extension has not been
2243 * loaded yet, or is loaded and unused
2244 * [think of iptables-restore!]
2245 * - the protocol extension can be successively
2250 && (!find_proto(protocol, DONT_LOAD,
2251 options&OPT_NUMERIC, NULL)
2252 || (find_proto(protocol, DONT_LOAD,
2253 options&OPT_NUMERIC, NULL)
2254 && (proto_used == 0))
2256 && (m = find_proto(protocol, TRY_LOAD,
2257 options&OPT_NUMERIC, &matches))) {
2258 /* Try loading protocol */
2263 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2266 m->m = fw_calloc(1, size);
2267 m->m->u.match_size = size;
2268 strcpy(m->m->u.user.name, m->name);
2269 set_revision(m->m->u.user.name,
2271 if (m->init != NULL)
2272 m->init(m->m, &fw.nfcache);
2274 opts = merge_options(opts,
2275 m->extra_opts, &m->option_offset);
2281 exit_error(PARAMETER_PROBLEM,
2289 for (matchp = matches; matchp; matchp = matchp->next)
2290 matchp->match->final_check(matchp->match->mflags);
2293 target->final_check(target->tflags);
2295 /* Fix me: must put inverse options checking here --MN */
2298 exit_error(PARAMETER_PROBLEM,
2299 "unknown arguments found on commandline");
2301 exit_error(PARAMETER_PROBLEM, "no command specified");
2303 exit_error(PARAMETER_PROBLEM,
2304 "nothing appropriate following !");
2306 if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
2307 if (!(options & OPT_DESTINATION))
2308 dhostnetworkmask = "0.0.0.0/0";
2309 if (!(options & OPT_SOURCE))
2310 shostnetworkmask = "0.0.0.0/0";
2313 if (shostnetworkmask)
2314 parse_hostnetworkmask(shostnetworkmask, &saddrs,
2315 &(fw.ip.smsk), &nsaddrs);
2317 if (dhostnetworkmask)
2318 parse_hostnetworkmask(dhostnetworkmask, &daddrs,
2319 &(fw.ip.dmsk), &ndaddrs);
2321 if ((nsaddrs > 1 || ndaddrs > 1) &&
2322 (fw.ip.invflags & (IPT_INV_SRCIP | IPT_INV_DSTIP)))
2323 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
2324 " source or destination IP addresses");
2326 if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
2327 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
2328 "specify a unique address");
2330 generic_opt_check(command, options);
2332 if (chain && strlen(chain) > IPT_FUNCTION_MAXNAMELEN)
2333 exit_error(PARAMETER_PROBLEM,
2334 "chain name `%s' too long (must be under %i chars)",
2335 chain, IPT_FUNCTION_MAXNAMELEN);
2337 /* only allocate handle if we weren't called with a handle */
2339 *handle = iptc_init(*table);
2341 /* try to insmod the module if iptc_init failed */
2342 if (!*handle && iptables_insmod("ip_tables", modprobe) != -1)
2343 *handle = iptc_init(*table);
2346 exit_error(VERSION_PROBLEM,
2347 "can't initialize iptables table `%s': %s",
2348 *table, iptc_strerror(errno));
2350 if (command == CMD_APPEND
2351 || command == CMD_DELETE
2352 || command == CMD_INSERT
2353 || command == CMD_REPLACE) {
2354 if (strcmp(chain, "PREROUTING") == 0
2355 || strcmp(chain, "INPUT") == 0) {
2356 /* -o not valid with incoming packets. */
2357 if (options & OPT_VIANAMEOUT)
2358 exit_error(PARAMETER_PROBLEM,
2359 "Can't use -%c with %s\n",
2360 opt2char(OPT_VIANAMEOUT),
2364 if (strcmp(chain, "POSTROUTING") == 0
2365 || strcmp(chain, "OUTPUT") == 0) {
2366 /* -i not valid with outgoing packets */
2367 if (options & OPT_VIANAMEIN)
2368 exit_error(PARAMETER_PROBLEM,
2369 "Can't use -%c with %s\n",
2370 opt2char(OPT_VIANAMEIN),
2374 if (target && iptc_is_chain(jumpto, *handle)) {
2375 printf("Warning: using chain %s, not extension\n",
2384 /* If they didn't specify a target, or it's a chain
2385 name, use standard. */
2387 && (strlen(jumpto) == 0
2388 || iptc_is_chain(jumpto, *handle))) {
2391 target = find_target(IPT_STANDARD_TARGET,
2394 size = sizeof(struct ipt_entry_target)
2396 target->t = fw_calloc(1, size);
2397 target->t->u.target_size = size;
2398 strcpy(target->t->u.user.name, jumpto);
2399 if (!iptc_is_chain(jumpto, *handle))
2400 set_revision(target->t->u.user.name,
2402 if (target->init != NULL)
2403 target->init(target->t, &fw.nfcache);
2407 /* it is no chain, and we can't load a plugin.
2408 * We cannot know if the plugin is corrupt, non
2409 * existant OR if the user just misspelled a
2412 if (fw.ip.flags & IPT_F_GOTO)
2413 exit_error(PARAMETER_PROBLEM,
2414 "goto '%s' is not a chain\n", jumpto);
2416 find_target(jumpto, LOAD_MUST_SUCCEED);
2418 e = generate_entry(&fw, matches, target->t);
2425 ret = append_entry(chain, e,
2426 nsaddrs, saddrs, ndaddrs, daddrs,
2427 options&OPT_VERBOSE,
2431 ret = delete_entry(chain, e,
2432 nsaddrs, saddrs, ndaddrs, daddrs,
2433 options&OPT_VERBOSE,
2436 case CMD_DELETE_NUM:
2437 ret = iptc_delete_num_entry(chain, rulenum - 1, handle);
2440 ret = replace_entry(chain, e, rulenum - 1,
2441 saddrs, daddrs, options&OPT_VERBOSE,
2445 ret = insert_entry(chain, e, rulenum - 1,
2446 nsaddrs, saddrs, ndaddrs, daddrs,
2447 options&OPT_VERBOSE,
2451 ret = list_entries(chain,
2452 options&OPT_VERBOSE,
2453 options&OPT_NUMERIC,
2454 options&OPT_EXPANDED,
2455 options&OPT_LINENUMBERS,
2459 ret = flush_entries(chain, options&OPT_VERBOSE, handle);
2462 ret = zero_entries(chain, options&OPT_VERBOSE, handle);
2464 case CMD_LIST|CMD_ZERO:
2465 ret = list_entries(chain,
2466 options&OPT_VERBOSE,
2467 options&OPT_NUMERIC,
2468 options&OPT_EXPANDED,
2469 options&OPT_LINENUMBERS,
2472 ret = zero_entries(chain,
2473 options&OPT_VERBOSE, handle);
2476 ret = iptc_create_chain(chain, handle);
2478 case CMD_DELETE_CHAIN:
2479 ret = delete_chain(chain, options&OPT_VERBOSE, handle);
2481 case CMD_RENAME_CHAIN:
2482 ret = iptc_rename_chain(chain, newname, handle);
2484 case CMD_SET_POLICY:
2485 ret = iptc_set_policy(chain, policy, NULL, handle);
2488 /* We should never reach this... */
2493 dump_entries(*handle);
2495 clear_rule_matches(&matches);