• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * (C) 2000-2006 by the netfilter coreteam <coreteam@netfilter.org>:
3  *
4  *	This program is free software; you can redistribute it and/or modify
5  *	it under the terms of the GNU General Public License as published by
6  *	the Free Software Foundation; either version 2 of the License, or
7  *	(at your option) any later version.
8  *
9  *	This program is distributed in the hope that it will be useful,
10  *	but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *	GNU General Public License for more details.
13  *
14  *	You should have received a copy of the GNU General Public License
15  *	along with this program; if not, write to the Free Software
16  *	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  */
18 #include "config.h"
19 #include <ctype.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <netdb.h>
24 #include <spawn.h>
25 #include <stdarg.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/statfs.h>
34 #include <sys/types.h>
35 #include <sys/utsname.h>
36 #include <sys/wait.h>
37 #include <arpa/inet.h>
38 #if defined(HAVE_LINUX_MAGIC_H)
39 #	include <linux/magic.h> /* for PROC_SUPER_MAGIC */
40 #elif defined(HAVE_LINUX_PROC_FS_H)
41 #	include <linux/proc_fs.h>	/* Linux 2.4 */
42 #else
43 #	define PROC_SUPER_MAGIC	0x9fa0
44 #endif
45 
46 #include <xtables.h>
47 #include <limits.h> /* INT_MAX in ip_tables.h/ip6_tables.h */
48 #include <linux/netfilter_ipv4/ip_tables.h>
49 #include <linux/netfilter_ipv6/ip6_tables.h>
50 #include <libiptc/libxtc.h>
51 
52 #ifndef NO_SHARED_LIBS
53 #include <dlfcn.h>
54 #endif
55 #ifndef IPT_SO_GET_REVISION_MATCH /* Old kernel source. */
56 #	define IPT_SO_GET_REVISION_MATCH	(IPT_BASE_CTL + 2)
57 #	define IPT_SO_GET_REVISION_TARGET	(IPT_BASE_CTL + 3)
58 #endif
59 #ifndef IP6T_SO_GET_REVISION_MATCH /* Old kernel source. */
60 #	define IP6T_SO_GET_REVISION_MATCH	68
61 #	define IP6T_SO_GET_REVISION_TARGET	69
62 #endif
63 #include <getopt.h>
64 #include "iptables/internal.h"
65 #include "xshared.h"
66 
67 #define NPROTO	255
68 
69 #ifndef PROC_SYS_MODPROBE
70 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
71 #endif
72 
73 /* we need this for ip6?tables-restore.  ip6?tables-restore.c sets line to the
74  * current line of the input file, in order  to give a more precise error
75  * message.  ip6?tables itself doesn't need this, so it is initialized to the
76  * magic number of -1 */
77 int line = -1;
78 
79 void basic_exit_err(enum xtables_exittype status, const char *msg, ...) __attribute__((noreturn, format(printf,2,3)));
80 
81 struct xtables_globals *xt_params = NULL;
82 
basic_exit_err(enum xtables_exittype status,const char * msg,...)83 void basic_exit_err(enum xtables_exittype status, const char *msg, ...)
84 {
85 	va_list args;
86 
87 	va_start(args, msg);
88 	fprintf(stderr, "%s v%s: ", xt_params->program_name, xt_params->program_version);
89 	vfprintf(stderr, msg, args);
90 	va_end(args);
91 	fprintf(stderr, "\n");
92 	exit(status);
93 }
94 
xtables_free_opts(int unused)95 void xtables_free_opts(int unused)
96 {
97 	if (xt_params->opts != xt_params->orig_opts) {
98 		free(xt_params->opts);
99 		xt_params->opts = NULL;
100 	}
101 }
102 
xtables_merge_options(struct option * orig_opts,struct option * oldopts,const struct option * newopts,unsigned int * option_offset)103 struct option *xtables_merge_options(struct option *orig_opts,
104 				     struct option *oldopts,
105 				     const struct option *newopts,
106 				     unsigned int *option_offset)
107 {
108 	unsigned int num_oold = 0, num_old = 0, num_new = 0, i;
109 	struct option *merge, *mp;
110 
111 	if (newopts == NULL)
112 		return oldopts;
113 
114 	for (num_oold = 0; orig_opts[num_oold].name; num_oold++) ;
115 	if (oldopts != NULL)
116 		for (num_old = 0; oldopts[num_old].name; num_old++) ;
117 	for (num_new = 0; newopts[num_new].name; num_new++) ;
118 
119 	/*
120 	 * Since @oldopts also has @orig_opts already (and does so at the
121 	 * start), skip these entries.
122 	 */
123 	if (oldopts != NULL) {
124 		oldopts += num_oold;
125 		num_old -= num_oold;
126 	}
127 
128 	merge = malloc(sizeof(*mp) * (num_oold + num_old + num_new + 1));
129 	if (merge == NULL)
130 		return NULL;
131 
132 	/* Let the base options -[ADI...] have precedence over everything */
133 	memcpy(merge, orig_opts, sizeof(*mp) * num_oold);
134 	mp = merge + num_oold;
135 
136 	/* Second, the new options */
137 	xt_params->option_offset += XT_OPTION_OFFSET_SCALE;
138 	*option_offset = xt_params->option_offset;
139 	memcpy(mp, newopts, sizeof(*mp) * num_new);
140 
141 	for (i = 0; i < num_new; ++i, ++mp)
142 		mp->val += *option_offset;
143 
144 	/* Third, the old options */
145 	if (oldopts != NULL) {
146 		memcpy(mp, oldopts, sizeof(*mp) * num_old);
147 		mp += num_old;
148 	}
149 	xtables_free_opts(0);
150 
151 	/* Clear trailing entry */
152 	memset(mp, 0, sizeof(*mp));
153 	return merge;
154 }
155 
156 static const struct xtables_afinfo afinfo_ipv4 = {
157 	.kmod          = "ip_tables",
158 	.proc_exists   = "/proc/net/ip_tables_names",
159 	.libprefix     = "libipt_",
160 	.family	       = NFPROTO_IPV4,
161 	.ipproto       = IPPROTO_IP,
162 	.so_rev_match  = IPT_SO_GET_REVISION_MATCH,
163 	.so_rev_target = IPT_SO_GET_REVISION_TARGET,
164 };
165 
166 static const struct xtables_afinfo afinfo_ipv6 = {
167 	.kmod          = "ip6_tables",
168 	.proc_exists   = "/proc/net/ip6_tables_names",
169 	.libprefix     = "libip6t_",
170 	.family        = NFPROTO_IPV6,
171 	.ipproto       = IPPROTO_IPV6,
172 	.so_rev_match  = IP6T_SO_GET_REVISION_MATCH,
173 	.so_rev_target = IP6T_SO_GET_REVISION_TARGET,
174 };
175 
176 /* Dummy families for arptables-compat and ebtables-compat. Leave structure
177  * fields that we don't use unset.
178  */
179 static const struct xtables_afinfo afinfo_bridge = {
180 	.libprefix     = "libebt_",
181 	.family        = NFPROTO_BRIDGE,
182 };
183 
184 static const struct xtables_afinfo afinfo_arp = {
185 	.libprefix     = "libarpt_",
186 	.family        = NFPROTO_ARP,
187 };
188 
189 const struct xtables_afinfo *afinfo;
190 
191 /* Search path for Xtables .so files */
192 static const char *xtables_libdir;
193 
194 /* the path to command to load kernel module */
195 const char *xtables_modprobe_program;
196 
197 /* Keep track of matches/targets pending full registration: linked lists. */
198 struct xtables_match *xtables_pending_matches;
199 struct xtables_target *xtables_pending_targets;
200 
201 /* Keep track of fully registered external matches/targets: linked lists. */
202 struct xtables_match *xtables_matches;
203 struct xtables_target *xtables_targets;
204 
205 /* Fully register a match/target which was previously partially registered. */
206 static bool xtables_fully_register_pending_match(struct xtables_match *me,
207 						 struct xtables_match *prev);
208 static bool xtables_fully_register_pending_target(struct xtables_target *me,
209 						  struct xtables_target *prev);
210 
211 #ifndef NO_SHARED_LIBS
212 /* registry for loaded shared objects to close later */
213 struct dlreg {
214 	struct dlreg *next;
215 	void *handle;
216 };
217 static struct dlreg *dlreg = NULL;
218 
dlreg_add(void * handle)219 static int dlreg_add(void *handle)
220 {
221 	struct dlreg *new = malloc(sizeof(*new));
222 
223 	if (!new)
224 		return -1;
225 
226 	new->handle = handle;
227 	new->next = dlreg;
228 	dlreg = new;
229 	return 0;
230 }
231 
dlreg_free(void)232 static void dlreg_free(void)
233 {
234 	struct dlreg *next;
235 
236 	while (dlreg) {
237 		next = dlreg->next;
238 		dlclose(dlreg->handle);
239 		free(dlreg);
240 		dlreg = next;
241 	}
242 }
243 #endif
244 
xtables_init(void)245 void xtables_init(void)
246 {
247 	xtables_libdir = getenv("XTABLES_LIBDIR");
248 	if (xtables_libdir != NULL)
249 		return;
250 	xtables_libdir = getenv("IPTABLES_LIB_DIR");
251 	if (xtables_libdir != NULL) {
252 		fprintf(stderr, "IPTABLES_LIB_DIR is deprecated, "
253 		        "use XTABLES_LIBDIR.\n");
254 		return;
255 	}
256 	/*
257 	 * Well yes, IP6TABLES_LIB_DIR is of lower priority over
258 	 * IPTABLES_LIB_DIR since this moved to libxtables; I think that is ok
259 	 * for these env vars are deprecated anyhow, and in light of the
260 	 * (shared) libxt_*.so files, makes less sense to have
261 	 * IPTABLES_LIB_DIR != IP6TABLES_LIB_DIR.
262 	 */
263 	xtables_libdir = getenv("IP6TABLES_LIB_DIR");
264 	if (xtables_libdir != NULL) {
265 		fprintf(stderr, "IP6TABLES_LIB_DIR is deprecated, "
266 		        "use XTABLES_LIBDIR.\n");
267 		return;
268 	}
269 	xtables_libdir = XTABLES_LIBDIR;
270 }
271 
xtables_fini(void)272 void xtables_fini(void)
273 {
274 #ifndef NO_SHARED_LIBS
275 	dlreg_free();
276 #endif
277 }
278 
xtables_set_nfproto(uint8_t nfproto)279 void xtables_set_nfproto(uint8_t nfproto)
280 {
281 	switch (nfproto) {
282 	case NFPROTO_IPV4:
283 		afinfo = &afinfo_ipv4;
284 		break;
285 	case NFPROTO_IPV6:
286 		afinfo = &afinfo_ipv6;
287 		break;
288 	case NFPROTO_BRIDGE:
289 		afinfo = &afinfo_bridge;
290 		break;
291 	case NFPROTO_ARP:
292 		afinfo = &afinfo_arp;
293 		break;
294 	default:
295 		fprintf(stderr, "libxtables: unhandled NFPROTO in %s\n",
296 		        __func__);
297 	}
298 }
299 
300 /**
301  * xtables_set_params - set the global parameters used by xtables
302  * @xtp:	input xtables_globals structure
303  *
304  * The app is expected to pass a valid xtables_globals data-filled
305  * with proper values
306  * @xtp cannot be NULL
307  *
308  * Returns -1 on failure to set and 0 on success
309  */
xtables_set_params(struct xtables_globals * xtp)310 int xtables_set_params(struct xtables_globals *xtp)
311 {
312 	if (!xtp) {
313 		fprintf(stderr, "%s: Illegal global params\n",__func__);
314 		return -1;
315 	}
316 
317 	xt_params = xtp;
318 
319 	if (!xt_params->exit_err)
320 		xt_params->exit_err = basic_exit_err;
321 
322 	return 0;
323 }
324 
xtables_init_all(struct xtables_globals * xtp,uint8_t nfproto)325 int xtables_init_all(struct xtables_globals *xtp, uint8_t nfproto)
326 {
327 	xtables_init();
328 	xtables_set_nfproto(nfproto);
329 	return xtables_set_params(xtp);
330 }
331 
332 /**
333  * xtables_*alloc - wrappers that exit on failure
334  */
xtables_calloc(size_t count,size_t size)335 void *xtables_calloc(size_t count, size_t size)
336 {
337 	void *p;
338 
339 	if ((p = calloc(count, size)) == NULL) {
340 		perror("ip[6]tables: calloc failed");
341 		exit(1);
342 	}
343 
344 	return p;
345 }
346 
xtables_malloc(size_t size)347 void *xtables_malloc(size_t size)
348 {
349 	void *p;
350 
351 	if ((p = malloc(size)) == NULL) {
352 		perror("ip[6]tables: malloc failed");
353 		exit(1);
354 	}
355 
356 	return p;
357 }
358 
xtables_realloc(void * ptr,size_t size)359 void *xtables_realloc(void *ptr, size_t size)
360 {
361 	void *p;
362 
363 	if ((p = realloc(ptr, size)) == NULL) {
364 		perror("ip[6]tables: realloc failed");
365 		exit(1);
366 	}
367 
368 	return p;
369 }
370 
get_modprobe(void)371 static char *get_modprobe(void)
372 {
373 	int procfile;
374 	char *ret;
375 	int count;
376 
377 	procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
378 	if (procfile < 0)
379 		return NULL;
380 	if (fcntl(procfile, F_SETFD, FD_CLOEXEC) == -1) {
381 		fprintf(stderr, "Could not set close on exec: %s\n",
382 			strerror(errno));
383 		exit(1);
384 	}
385 
386 	ret = malloc(PATH_MAX);
387 	if (ret) {
388 		count = read(procfile, ret, PATH_MAX);
389 		if (count > 0 && count < PATH_MAX)
390 		{
391 			if (ret[count - 1] == '\n')
392 				ret[count - 1] = '\0';
393 			else
394 				ret[count] = '\0';
395 			close(procfile);
396 			return ret;
397 		}
398 	}
399 	free(ret);
400 	close(procfile);
401 	return NULL;
402 }
403 
xtables_insmod(const char * modname,const char * modprobe,bool quiet)404 int xtables_insmod(const char *modname, const char *modprobe, bool quiet)
405 {
406 	char *buf = NULL;
407 	char *argv[4];
408 	int status;
409 	pid_t pid;
410 
411 	/* If they don't explicitly set it, read out of kernel */
412 	if (!modprobe) {
413 		buf = get_modprobe();
414 		if (!buf)
415 			return -1;
416 		modprobe = buf;
417 	}
418 
419 	argv[0] = (char *)modprobe;
420 	argv[1] = (char *)modname;
421 	argv[2] = quiet ? "-q" : NULL;
422 	argv[3] = NULL;
423 
424 	/*
425 	 * Need to flush the buffer, or the child may output it again
426 	 * when switching the program thru execv.
427 	 */
428 	fflush(stdout);
429 
430 	if (posix_spawn(&pid, argv[0], NULL, NULL, argv, NULL)) {
431 		free(buf);
432 		return -1;
433 	} else {
434 		waitpid(pid, &status, 0);
435 	}
436 
437 	free(buf);
438 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
439 		return 0;
440 	return -1;
441 }
442 
443 /* return true if a given file exists within procfs */
proc_file_exists(const char * filename)444 static bool proc_file_exists(const char *filename)
445 {
446 	struct stat s;
447 	struct statfs f;
448 
449 	if (lstat(filename, &s))
450 		return false;
451 	if (!S_ISREG(s.st_mode))
452 		return false;
453 	if (statfs(filename, &f))
454 		return false;
455 	if (f.f_type != PROC_SUPER_MAGIC)
456 		return false;
457 	return true;
458 }
459 
xtables_load_ko(const char * modprobe,bool quiet)460 int xtables_load_ko(const char *modprobe, bool quiet)
461 {
462 	static bool loaded = false;
463 	int ret;
464 
465 	if (loaded)
466 		return 0;
467 
468 	if (proc_file_exists(afinfo->proc_exists)) {
469 		loaded = true;
470 		return 0;
471 	};
472 
473 	ret = xtables_insmod(afinfo->kmod, modprobe, quiet);
474 	if (ret == 0)
475 		loaded = true;
476 
477 	return ret;
478 }
479 
480 /**
481  * xtables_strtou{i,l} - string to number conversion
482  * @s:	input string
483  * @end:	like strtoul's "end" pointer
484  * @value:	pointer for result
485  * @min:	minimum accepted value
486  * @max:	maximum accepted value
487  *
488  * If @end is NULL, we assume the caller wants a "strict strtoul", and hence
489  * "15a" is rejected.
490  * In either case, the value obtained is compared for min-max compliance.
491  * Base is always 0, i.e. autodetect depending on @s.
492  *
493  * Returns true/false whether number was accepted. On failure, *value has
494  * undefined contents.
495  */
xtables_strtoul(const char * s,char ** end,uintmax_t * value,uintmax_t min,uintmax_t max)496 bool xtables_strtoul(const char *s, char **end, uintmax_t *value,
497                      uintmax_t min, uintmax_t max)
498 {
499 	uintmax_t v;
500 	const char *p;
501 	char *my_end;
502 
503 	errno = 0;
504 	/* Since strtoul allows leading minus, we have to check for ourself. */
505 	for (p = s; isspace(*p); ++p)
506 		;
507 	if (*p == '-')
508 		return false;
509 	v = strtoumax(s, &my_end, 0);
510 	if (my_end == s)
511 		return false;
512 	if (end != NULL)
513 		*end = my_end;
514 
515 	if (errno != ERANGE && min <= v && (max == 0 || v <= max)) {
516 		if (value != NULL)
517 			*value = v;
518 		if (end == NULL)
519 			return *my_end == '\0';
520 		return true;
521 	}
522 
523 	return false;
524 }
525 
xtables_strtoui(const char * s,char ** end,unsigned int * value,unsigned int min,unsigned int max)526 bool xtables_strtoui(const char *s, char **end, unsigned int *value,
527                      unsigned int min, unsigned int max)
528 {
529 	uintmax_t v;
530 	bool ret;
531 
532 	ret = xtables_strtoul(s, end, &v, min, max);
533 	if (ret && value != NULL)
534 		*value = v;
535 	return ret;
536 }
537 
xtables_service_to_port(const char * name,const char * proto)538 int xtables_service_to_port(const char *name, const char *proto)
539 {
540 	struct servent *service;
541 
542 	if ((service = getservbyname(name, proto)) != NULL)
543 		return ntohs((unsigned short) service->s_port);
544 
545 	return -1;
546 }
547 
xtables_parse_port(const char * port,const char * proto)548 uint16_t xtables_parse_port(const char *port, const char *proto)
549 {
550 	unsigned int portnum;
551 
552 	if (xtables_strtoui(port, NULL, &portnum, 0, UINT16_MAX) ||
553 	    (portnum = xtables_service_to_port(port, proto)) != (unsigned)-1)
554 		return portnum;
555 
556 	xt_params->exit_err(PARAMETER_PROBLEM,
557 		   "invalid port/service `%s' specified", port);
558 }
559 
xtables_parse_interface(const char * arg,char * vianame,unsigned char * mask)560 void xtables_parse_interface(const char *arg, char *vianame,
561 			     unsigned char *mask)
562 {
563 	unsigned int vialen = strlen(arg);
564 	unsigned int i;
565 
566 	memset(mask, 0, IFNAMSIZ);
567 	memset(vianame, 0, IFNAMSIZ);
568 
569 	if (vialen + 1 > IFNAMSIZ)
570 		xt_params->exit_err(PARAMETER_PROBLEM,
571 			   "interface name `%s' must be shorter than IFNAMSIZ"
572 			   " (%i)", arg, IFNAMSIZ-1);
573 
574 	strcpy(vianame, arg);
575 	if (vialen == 0)
576 		return;
577 	else if (vianame[vialen - 1] == '+') {
578 		memset(mask, 0xFF, vialen - 1);
579 		/* Don't remove `+' here! -HW */
580 	} else {
581 		/* Include nul-terminator in match */
582 		memset(mask, 0xFF, vialen + 1);
583 	}
584 
585 	/* Display warning on invalid characters */
586 	for (i = 0; vianame[i]; i++) {
587 		if (vianame[i] == '/' || vianame[i] == ' ') {
588 			fprintf(stderr,	"Warning: weird character in interface"
589 				" `%s' ('/' and ' ' are not allowed by the kernel).\n",
590 				vianame);
591 			break;
592 		}
593 	}
594 }
595 
596 #ifndef NO_SHARED_LIBS
load_extension(const char * search_path,const char * af_prefix,const char * name,bool is_target)597 static void *load_extension(const char *search_path, const char *af_prefix,
598     const char *name, bool is_target)
599 {
600 	const char *all_prefixes[] = {af_prefix, "libxt_", NULL};
601 	const char **prefix;
602 	const char *dir = search_path, *next;
603 	void *ptr = NULL;
604 	struct stat sb;
605 	char path[256];
606 
607 	do {
608 		next = strchr(dir, ':');
609 		if (next == NULL)
610 			next = dir + strlen(dir);
611 
612 		for (prefix = all_prefixes; *prefix != NULL; ++prefix) {
613 			void *handle;
614 
615 			snprintf(path, sizeof(path), "%.*s/%s%s.so",
616 			         (unsigned int)(next - dir), dir,
617 			         *prefix, name);
618 
619 			if (stat(path, &sb) != 0) {
620 				if (errno == ENOENT)
621 					continue;
622 				fprintf(stderr, "%s: %s\n", path,
623 					strerror(errno));
624 				return NULL;
625 			}
626 			handle = dlopen(path, RTLD_NOW);
627 			if (handle == NULL) {
628 				fprintf(stderr, "%s: %s\n", path, dlerror());
629 				break;
630 			}
631 
632 			dlreg_add(handle);
633 
634 			if (is_target)
635 				ptr = xtables_find_target(name, XTF_DONT_LOAD);
636 			else
637 				ptr = xtables_find_match(name,
638 				      XTF_DONT_LOAD, NULL);
639 
640 			if (ptr != NULL)
641 				return ptr;
642 
643 			errno = ENOENT;
644 			return NULL;
645 		}
646 		dir = next + 1;
647 	} while (*next != '\0');
648 
649 	return NULL;
650 }
651 #endif
652 
extension_cmp(const char * name1,const char * name2,uint32_t family)653 static bool extension_cmp(const char *name1, const char *name2, uint32_t family)
654 {
655 	if (strcmp(name1, name2) == 0 &&
656 	    (family == afinfo->family ||
657 	     family == NFPROTO_UNSPEC))
658 		return true;
659 
660 	return false;
661 }
662 
663 struct xtables_match *
xtables_find_match(const char * name,enum xtables_tryload tryload,struct xtables_rule_match ** matches)664 xtables_find_match(const char *name, enum xtables_tryload tryload,
665 		   struct xtables_rule_match **matches)
666 {
667 	struct xtables_match *prev = NULL;
668 	struct xtables_match **dptr;
669 	struct xtables_match *ptr;
670 	const char *icmp6 = "icmp6";
671 
672 	if (strlen(name) >= XT_EXTENSION_MAXNAMELEN)
673 		xtables_error(PARAMETER_PROBLEM,
674 			   "Invalid match name \"%s\" (%u chars max)",
675 			   name, XT_EXTENSION_MAXNAMELEN - 1);
676 
677 	/* This is ugly as hell. Nonetheless, there is no way of changing
678 	 * this without hurting backwards compatibility */
679 	if ( (strcmp(name,"icmpv6") == 0) ||
680 	     (strcmp(name,"ipv6-icmp") == 0) ||
681 	     (strcmp(name,"icmp6") == 0) )
682 		name = icmp6;
683 
684 	/* Trigger delayed initialization */
685 	for (dptr = &xtables_pending_matches; *dptr; ) {
686 		if (extension_cmp(name, (*dptr)->name, (*dptr)->family)) {
687 			ptr = *dptr;
688 			*dptr = (*dptr)->next;
689 			if (xtables_fully_register_pending_match(ptr, prev)) {
690 				prev = ptr;
691 				continue;
692 			} else if (prev) {
693 				continue;
694 			}
695 			*dptr = ptr;
696 		}
697 		dptr = &((*dptr)->next);
698 	}
699 
700 	for (ptr = xtables_matches; ptr; ptr = ptr->next) {
701 		if (extension_cmp(name, ptr->name, ptr->family)) {
702 			struct xtables_match *clone;
703 
704 			/* First match of this type: */
705 			if (ptr->m == NULL)
706 				break;
707 
708 			/* Second and subsequent clones */
709 			clone = xtables_malloc(sizeof(struct xtables_match));
710 			memcpy(clone, ptr, sizeof(struct xtables_match));
711 			clone->udata = NULL;
712 			clone->mflags = 0;
713 			/* This is a clone: */
714 			clone->next = clone;
715 
716 			ptr = clone;
717 			break;
718 		}
719 	}
720 
721 #ifndef NO_SHARED_LIBS
722 	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
723 		ptr = load_extension(xtables_libdir, afinfo->libprefix,
724 		      name, false);
725 
726 		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
727 			xt_params->exit_err(PARAMETER_PROBLEM,
728 				   "Couldn't load match `%s':%s\n",
729 				   name, strerror(errno));
730 	}
731 #else
732 	if (ptr && !ptr->loaded) {
733 		if (tryload != XTF_DONT_LOAD)
734 			ptr->loaded = 1;
735 		else
736 			ptr = NULL;
737 	}
738 	if(!ptr && (tryload == XTF_LOAD_MUST_SUCCEED)) {
739 		xt_params->exit_err(PARAMETER_PROBLEM,
740 			   "Couldn't find match `%s'\n", name);
741 	}
742 #endif
743 
744 	if (ptr && matches) {
745 		struct xtables_rule_match **i;
746 		struct xtables_rule_match *newentry;
747 
748 		newentry = xtables_malloc(sizeof(struct xtables_rule_match));
749 
750 		for (i = matches; *i; i = &(*i)->next) {
751 			if (extension_cmp(name, (*i)->match->name,
752 					  (*i)->match->family))
753 				(*i)->completed = true;
754 		}
755 		newentry->match = ptr;
756 		newentry->completed = false;
757 		newentry->next = NULL;
758 		*i = newentry;
759 	}
760 
761 	return ptr;
762 }
763 
764 struct xtables_match *
xtables_find_match_revision(const char * name,enum xtables_tryload tryload,struct xtables_match * match,int revision)765 xtables_find_match_revision(const char *name, enum xtables_tryload tryload,
766 			    struct xtables_match *match, int revision)
767 {
768 	if (!match) {
769 		match = xtables_find_match(name, tryload, NULL);
770 		if (!match)
771 			return NULL;
772 	}
773 
774 	while (1) {
775 		if (match->revision == revision)
776 			return match;
777 		match = match->next;
778 		if (!match)
779 			return NULL;
780 		if (!extension_cmp(name, match->name, match->family))
781 			return NULL;
782 	}
783 }
784 
785 struct xtables_target *
xtables_find_target(const char * name,enum xtables_tryload tryload)786 xtables_find_target(const char *name, enum xtables_tryload tryload)
787 {
788 	struct xtables_target *prev = NULL;
789 	struct xtables_target **dptr;
790 	struct xtables_target *ptr;
791 
792 	/* Standard target? */
793 	if (strcmp(name, "") == 0
794 	    || strcmp(name, XTC_LABEL_ACCEPT) == 0
795 	    || strcmp(name, XTC_LABEL_DROP) == 0
796 	    || strcmp(name, XTC_LABEL_QUEUE) == 0
797 	    || strcmp(name, XTC_LABEL_RETURN) == 0)
798 		name = "standard";
799 
800 	/* Trigger delayed initialization */
801 	for (dptr = &xtables_pending_targets; *dptr; ) {
802 		if (extension_cmp(name, (*dptr)->name, (*dptr)->family)) {
803 			ptr = *dptr;
804 			*dptr = (*dptr)->next;
805 			if (xtables_fully_register_pending_target(ptr, prev)) {
806 				prev = ptr;
807 				continue;
808 			} else if (prev) {
809 				continue;
810 			}
811 			*dptr = ptr;
812 		}
813 		dptr = &((*dptr)->next);
814 	}
815 
816 	for (ptr = xtables_targets; ptr; ptr = ptr->next) {
817 		if (extension_cmp(name, ptr->name, ptr->family)) {
818 			struct xtables_target *clone;
819 
820 			/* First target of this type: */
821 			if (ptr->t == NULL)
822 				break;
823 
824 			/* Second and subsequent clones */
825 			clone = xtables_malloc(sizeof(struct xtables_target));
826 			memcpy(clone, ptr, sizeof(struct xtables_target));
827 			clone->udata = NULL;
828 			clone->tflags = 0;
829 			/* This is a clone: */
830 			clone->next = clone;
831 
832 			ptr = clone;
833 			break;
834 		}
835 	}
836 
837 #ifndef NO_SHARED_LIBS
838 	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
839 		ptr = load_extension(xtables_libdir, afinfo->libprefix,
840 		      name, true);
841 
842 		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
843 			xt_params->exit_err(PARAMETER_PROBLEM,
844 				   "Couldn't load target `%s':%s\n",
845 				   name, strerror(errno));
846 	}
847 #else
848 	if (ptr && !ptr->loaded) {
849 		if (tryload != XTF_DONT_LOAD)
850 			ptr->loaded = 1;
851 		else
852 			ptr = NULL;
853 	}
854 	if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED) {
855 		xt_params->exit_err(PARAMETER_PROBLEM,
856 			   "Couldn't find target `%s'\n", name);
857 	}
858 #endif
859 
860 	if (ptr)
861 		ptr->used = 1;
862 
863 	return ptr;
864 }
865 
866 struct xtables_target *
xtables_find_target_revision(const char * name,enum xtables_tryload tryload,struct xtables_target * target,int revision)867 xtables_find_target_revision(const char *name, enum xtables_tryload tryload,
868 			     struct xtables_target *target, int revision)
869 {
870 	if (!target) {
871 		target = xtables_find_target(name, tryload);
872 		if (!target)
873 			return NULL;
874 	}
875 
876 	while (1) {
877 		if (target->revision == revision)
878 			return target;
879 		target = target->next;
880 		if (!target)
881 			return NULL;
882 		if (!extension_cmp(name, target->name, target->family))
883 			return NULL;
884 	}
885 }
886 
xtables_compatible_revision(const char * name,uint8_t revision,int opt)887 int xtables_compatible_revision(const char *name, uint8_t revision, int opt)
888 {
889 	struct xt_get_revision rev;
890 	socklen_t s = sizeof(rev);
891 	int max_rev, sockfd;
892 
893 	sockfd = socket(afinfo->family, SOCK_RAW, IPPROTO_RAW);
894 	if (sockfd < 0) {
895 		if (errno == EPERM) {
896 			/* revision 0 is always supported. */
897 			if (revision != 0)
898 				fprintf(stderr, "%s: Could not determine whether "
899 						"revision %u is supported, "
900 						"assuming it is.\n",
901 					name, revision);
902 			return 1;
903 		}
904 		fprintf(stderr, "Could not open socket to kernel: %s\n",
905 			strerror(errno));
906 		exit(1);
907 	}
908 
909 	if (fcntl(sockfd, F_SETFD, FD_CLOEXEC) == -1) {
910 		fprintf(stderr, "Could not set close on exec: %s\n",
911 			strerror(errno));
912 		exit(1);
913 	}
914 
915 	xtables_load_ko(xtables_modprobe_program, true);
916 
917 	strncpy(rev.name, name, XT_EXTENSION_MAXNAMELEN - 1);
918 	rev.name[XT_EXTENSION_MAXNAMELEN - 1] = '\0';
919 	rev.revision = revision;
920 
921 	max_rev = getsockopt(sockfd, afinfo->ipproto, opt, &rev, &s);
922 	if (max_rev < 0) {
923 		/* Definitely don't support this? */
924 		if (errno == ENOENT || errno == EPROTONOSUPPORT) {
925 			close(sockfd);
926 			return 0;
927 		} else if (errno == ENOPROTOOPT) {
928 			close(sockfd);
929 			/* Assume only revision 0 support (old kernel) */
930 			return (revision == 0);
931 		} else {
932 			fprintf(stderr, "getsockopt failed strangely: %s\n",
933 				strerror(errno));
934 			exit(1);
935 		}
936 	}
937 	close(sockfd);
938 	return 1;
939 }
940 
941 
compatible_match_revision(const char * name,uint8_t revision)942 static int compatible_match_revision(const char *name, uint8_t revision)
943 {
944 	return xt_params->compat_rev(name, revision, afinfo->so_rev_match);
945 }
946 
compatible_target_revision(const char * name,uint8_t revision)947 static int compatible_target_revision(const char *name, uint8_t revision)
948 {
949 	return xt_params->compat_rev(name, revision, afinfo->so_rev_target);
950 }
951 
xtables_check_options(const char * name,const struct option * opt)952 static void xtables_check_options(const char *name, const struct option *opt)
953 {
954 	for (; opt->name != NULL; ++opt)
955 		if (opt->val < 0 || opt->val >= XT_OPTION_OFFSET_SCALE) {
956 			fprintf(stderr, "%s: Extension %s uses invalid "
957 			        "option value %d\n",xt_params->program_name,
958 			        name, opt->val);
959 			exit(1);
960 		}
961 }
962 
963 static int xtables_match_prefer(const struct xtables_match *a,
964 				const struct xtables_match *b);
965 
xtables_register_match(struct xtables_match * me)966 void xtables_register_match(struct xtables_match *me)
967 {
968 	struct xtables_match **pos;
969 	bool seen_myself = false;
970 
971 	if (me->next) {
972 		fprintf(stderr, "%s: match \"%s\" already registered\n",
973 			xt_params->program_name, me->name);
974 		exit(1);
975 	}
976 
977 	if (me->version == NULL) {
978 		fprintf(stderr, "%s: match %s<%u> is missing a version\n",
979 		        xt_params->program_name, me->name, me->revision);
980 		exit(1);
981 	}
982 
983 	if (me->size != XT_ALIGN(me->size)) {
984 		fprintf(stderr, "%s: match \"%s\" has invalid size %u.\n",
985 		        xt_params->program_name, me->name,
986 		        (unsigned int)me->size);
987 		exit(1);
988 	}
989 
990 	if (strcmp(me->version, XTABLES_VERSION) != 0) {
991 		fprintf(stderr, "%s: match \"%s\" has version \"%s\", "
992 		        "but \"%s\" is required.\n",
993 			xt_params->program_name, me->name,
994 			me->version, XTABLES_VERSION);
995 		exit(1);
996 	}
997 
998 	if (strlen(me->name) >= XT_EXTENSION_MAXNAMELEN) {
999 		fprintf(stderr, "%s: match `%s' has invalid name\n",
1000 			xt_params->program_name, me->name);
1001 		exit(1);
1002 	}
1003 
1004 	if (me->real_name && strlen(me->real_name) >= XT_EXTENSION_MAXNAMELEN) {
1005 		fprintf(stderr, "%s: match `%s' has invalid real name\n",
1006 			xt_params->program_name, me->real_name);
1007 		exit(1);
1008 	}
1009 
1010 	if (me->family >= NPROTO) {
1011 		fprintf(stderr,
1012 			"%s: BUG: match %s has invalid protocol family\n",
1013 			xt_params->program_name, me->name);
1014 		exit(1);
1015 	}
1016 
1017 	if (me->x6_options != NULL)
1018 		xtables_option_metavalidate(me->name, me->x6_options);
1019 	if (me->extra_opts != NULL)
1020 		xtables_check_options(me->name, me->extra_opts);
1021 
1022 	/* order into linked list of matches pending full registration */
1023 	for (pos = &xtables_pending_matches; *pos; pos = &(*pos)->next) {
1024 		/* group by name and family */
1025 		if (strcmp(me->name, (*pos)->name) ||
1026 		    me->family != (*pos)->family) {
1027 			if (seen_myself)
1028 				break; /* end of own group, append to it */
1029 			continue;
1030 		}
1031 		/* found own group */
1032 		seen_myself = true;
1033 		if (xtables_match_prefer(me, *pos) >= 0)
1034 			break; /* put preferred items first in group */
1035 	}
1036 	/* if own group was not found, prepend item */
1037 	if (!*pos && !seen_myself)
1038 		pos = &xtables_pending_matches;
1039 
1040 	me->next = *pos;
1041 	*pos = me;
1042 #ifdef DEBUG
1043 	printf("%s: inserted match %s (family %d, revision %d):\n",
1044 			__func__, me->name, me->family, me->revision);
1045 	for (pos = &xtables_pending_matches; *pos; pos = &(*pos)->next) {
1046 		printf("%s:\tmatch %s (family %d, revision %d)\n", __func__,
1047 		       (*pos)->name, (*pos)->family, (*pos)->revision);
1048 	}
1049 #endif
1050 }
1051 
1052 /**
1053  * Compare two actions for their preference
1054  * @a:	one action
1055  * @b: 	another
1056  *
1057  * Like strcmp, returns a negative number if @a is less preferred than @b,
1058  * positive number if @a is more preferred than @b, or zero if equally
1059  * preferred.
1060  */
1061 static int
xtables_mt_prefer(bool a_alias,unsigned int a_rev,unsigned int a_fam,bool b_alias,unsigned int b_rev,unsigned int b_fam)1062 xtables_mt_prefer(bool a_alias, unsigned int a_rev, unsigned int a_fam,
1063 		  bool b_alias, unsigned int b_rev, unsigned int b_fam)
1064 {
1065 	/*
1066 	 * Alias ranks higher than no alias.
1067 	 * (We want the new action to be used whenever possible.)
1068 	 */
1069 	if (!a_alias && b_alias)
1070 		return -1;
1071 	if (a_alias && !b_alias)
1072 		return 1;
1073 
1074 	/* Higher revision ranks higher. */
1075 	if (a_rev < b_rev)
1076 		return -1;
1077 	if (a_rev > b_rev)
1078 		return 1;
1079 
1080 	/* NFPROTO_<specific> ranks higher than NFPROTO_UNSPEC. */
1081 	if (a_fam == NFPROTO_UNSPEC && b_fam != NFPROTO_UNSPEC)
1082 		return -1;
1083 	if (a_fam != NFPROTO_UNSPEC && b_fam == NFPROTO_UNSPEC)
1084 		return 1;
1085 
1086 	/* Must be the same thing. */
1087 	return 0;
1088 }
1089 
xtables_match_prefer(const struct xtables_match * a,const struct xtables_match * b)1090 static int xtables_match_prefer(const struct xtables_match *a,
1091 				const struct xtables_match *b)
1092 {
1093 	return xtables_mt_prefer(a->real_name != NULL,
1094 				 a->revision, a->family,
1095 				 b->real_name != NULL,
1096 				 b->revision, b->family);
1097 }
1098 
xtables_target_prefer(const struct xtables_target * a,const struct xtables_target * b)1099 static int xtables_target_prefer(const struct xtables_target *a,
1100 				 const struct xtables_target *b)
1101 {
1102 	/*
1103 	 * Note that if x->real_name==NULL, it will be set to x->name in
1104 	 * xtables_register_*; the direct pointer comparison here is therefore
1105 	 * legitimate to detect an alias.
1106 	 */
1107 	return xtables_mt_prefer(a->real_name != NULL,
1108 				 a->revision, a->family,
1109 				 b->real_name != NULL,
1110 				 b->revision, b->family);
1111 }
1112 
xtables_fully_register_pending_match(struct xtables_match * me,struct xtables_match * prev)1113 static bool xtables_fully_register_pending_match(struct xtables_match *me,
1114 						 struct xtables_match *prev)
1115 {
1116 	struct xtables_match **i;
1117 	const char *rn;
1118 
1119 	/* See if new match can be used. */
1120 	rn = (me->real_name != NULL) ? me->real_name : me->name;
1121 	if (!compatible_match_revision(rn, me->revision))
1122 		return false;
1123 
1124 	if (!prev) {
1125 		/* Append to list. */
1126 		for (i = &xtables_matches; *i; i = &(*i)->next);
1127 	} else {
1128 		/* Append it */
1129 		i = &prev->next;
1130 		prev = prev->next;
1131 	}
1132 
1133 	me->next = prev;
1134 	*i = me;
1135 
1136 	me->m = NULL;
1137 	me->mflags = 0;
1138 
1139 	return true;
1140 }
1141 
xtables_register_matches(struct xtables_match * match,unsigned int n)1142 void xtables_register_matches(struct xtables_match *match, unsigned int n)
1143 {
1144 	int i;
1145 
1146 	for (i = 0; i < n; i++)
1147 		xtables_register_match(&match[i]);
1148 }
1149 
xtables_register_target(struct xtables_target * me)1150 void xtables_register_target(struct xtables_target *me)
1151 {
1152 	struct xtables_target **pos;
1153 	bool seen_myself = false;
1154 
1155 	if (me->next) {
1156 		fprintf(stderr, "%s: target \"%s\" already registered\n",
1157 			xt_params->program_name, me->name);
1158 		exit(1);
1159 	}
1160 
1161 	if (me->version == NULL) {
1162 		fprintf(stderr, "%s: target %s<%u> is missing a version\n",
1163 		        xt_params->program_name, me->name, me->revision);
1164 		exit(1);
1165 	}
1166 
1167 	if (me->size != XT_ALIGN(me->size)) {
1168 		fprintf(stderr, "%s: target \"%s\" has invalid size %u.\n",
1169 		        xt_params->program_name, me->name,
1170 		        (unsigned int)me->size);
1171 		exit(1);
1172 	}
1173 
1174 	if (strcmp(me->version, XTABLES_VERSION) != 0) {
1175 		fprintf(stderr, "%s: target \"%s\" has version \"%s\", "
1176 		        "but \"%s\" is required.\n",
1177 			xt_params->program_name, me->name,
1178 			me->version, XTABLES_VERSION);
1179 		exit(1);
1180 	}
1181 
1182 	if (strlen(me->name) >= XT_EXTENSION_MAXNAMELEN) {
1183 		fprintf(stderr, "%s: target `%s' has invalid name\n",
1184 			xt_params->program_name, me->name);
1185 		exit(1);
1186 	}
1187 
1188 	if (me->real_name && strlen(me->real_name) >= XT_EXTENSION_MAXNAMELEN) {
1189 		fprintf(stderr, "%s: target `%s' has invalid real name\n",
1190 			xt_params->program_name, me->real_name);
1191 		exit(1);
1192 	}
1193 
1194 	if (me->family >= NPROTO) {
1195 		fprintf(stderr,
1196 			"%s: BUG: target %s has invalid protocol family\n",
1197 			xt_params->program_name, me->name);
1198 		exit(1);
1199 	}
1200 
1201 	if (me->x6_options != NULL)
1202 		xtables_option_metavalidate(me->name, me->x6_options);
1203 	if (me->extra_opts != NULL)
1204 		xtables_check_options(me->name, me->extra_opts);
1205 
1206 	/* ignore not interested target */
1207 	if (me->family != afinfo->family && me->family != AF_UNSPEC)
1208 		return;
1209 
1210 	/* order into linked list of targets pending full registration */
1211 	for (pos = &xtables_pending_targets; *pos; pos = &(*pos)->next) {
1212 		/* group by name */
1213 		if (!extension_cmp(me->name, (*pos)->name, (*pos)->family)) {
1214 			if (seen_myself)
1215 				break; /* end of own group, append to it */
1216 			continue;
1217 		}
1218 		/* found own group */
1219 		seen_myself = true;
1220 		if (xtables_target_prefer(me, *pos) >= 0)
1221 			break; /* put preferred items first in group */
1222 	}
1223 	/* if own group was not found, prepend item */
1224 	if (!*pos && !seen_myself)
1225 		pos = &xtables_pending_targets;
1226 
1227 	me->next = *pos;
1228 	*pos = me;
1229 #ifdef DEBUG
1230 	printf("%s: inserted target %s (family %d, revision %d):\n",
1231 			__func__, me->name, me->family, me->revision);
1232 	for (pos = &xtables_pending_targets; *pos; pos = &(*pos)->next) {
1233 		printf("%s:\ttarget %s (family %d, revision %d)\n", __func__,
1234 		       (*pos)->name, (*pos)->family, (*pos)->revision);
1235 	}
1236 #endif
1237 }
1238 
xtables_fully_register_pending_target(struct xtables_target * me,struct xtables_target * prev)1239 static bool xtables_fully_register_pending_target(struct xtables_target *me,
1240 						  struct xtables_target *prev)
1241 {
1242 	struct xtables_target **i;
1243 	const char *rn;
1244 
1245 	if (strcmp(me->name, "standard") != 0) {
1246 		/* See if new target can be used. */
1247 		rn = (me->real_name != NULL) ? me->real_name : me->name;
1248 		if (!compatible_target_revision(rn, me->revision))
1249 			return false;
1250 	}
1251 
1252 	if (!prev) {
1253 		/* Prepend to list. */
1254 		i = &xtables_targets;
1255 		prev = xtables_targets;
1256 	} else {
1257 		/* Append it */
1258 		i = &prev->next;
1259 		prev = prev->next;
1260 	}
1261 
1262 	me->next = prev;
1263 	*i = me;
1264 
1265 	me->t = NULL;
1266 	me->tflags = 0;
1267 
1268 	return true;
1269 }
1270 
xtables_register_targets(struct xtables_target * target,unsigned int n)1271 void xtables_register_targets(struct xtables_target *target, unsigned int n)
1272 {
1273 	int i;
1274 
1275 	for (i = 0; i < n; i++)
1276 		xtables_register_target(&target[i]);
1277 }
1278 
1279 /* receives a list of xtables_rule_match, release them */
xtables_rule_matches_free(struct xtables_rule_match ** matches)1280 void xtables_rule_matches_free(struct xtables_rule_match **matches)
1281 {
1282 	struct xtables_rule_match *matchp, *tmp;
1283 
1284 	for (matchp = *matches; matchp;) {
1285 		tmp = matchp->next;
1286 		if (matchp->match->m) {
1287 			free(matchp->match->m);
1288 			matchp->match->m = NULL;
1289 		}
1290 		if (matchp->match == matchp->match->next) {
1291 			free(matchp->match);
1292 			matchp->match = NULL;
1293 		}
1294 		free(matchp);
1295 		matchp = tmp;
1296 	}
1297 
1298 	*matches = NULL;
1299 }
1300 
1301 /**
1302  * xtables_param_act - act on condition
1303  * @status:	a constant from enum xtables_exittype
1304  *
1305  * %XTF_ONLY_ONCE: print error message that option may only be used once.
1306  * @p1:		module name (e.g. "mark")
1307  * @p2(...):	option in conflict (e.g. "--mark")
1308  * @p3(...):	condition to match on (see extensions/ for examples)
1309  *
1310  * %XTF_NO_INVERT: option does not support inversion
1311  * @p1:		module name
1312  * @p2:		option in conflict
1313  * @p3:		condition to match on
1314  *
1315  * %XTF_BAD_VALUE: bad value for option
1316  * @p1:		module name
1317  * @p2:		option with which the problem occurred (e.g. "--mark")
1318  * @p3:		string the user passed in (e.g. "99999999999999")
1319  *
1320  * %XTF_ONE_ACTION: two mutually exclusive actions have been specified
1321  * @p1:		module name
1322  *
1323  * Displays an error message and exits the program.
1324  */
xtables_param_act(unsigned int status,const char * p1,...)1325 void xtables_param_act(unsigned int status, const char *p1, ...)
1326 {
1327 	const char *p2, *p3;
1328 	va_list args;
1329 	bool b;
1330 
1331 	va_start(args, p1);
1332 
1333 	switch (status) {
1334 	case XTF_ONLY_ONCE:
1335 		p2 = va_arg(args, const char *);
1336 		b  = va_arg(args, unsigned int);
1337 		if (!b) {
1338 			va_end(args);
1339 			return;
1340 		}
1341 		xt_params->exit_err(PARAMETER_PROBLEM,
1342 		           "%s: \"%s\" option may only be specified once",
1343 		           p1, p2);
1344 		break;
1345 	case XTF_NO_INVERT:
1346 		p2 = va_arg(args, const char *);
1347 		b  = va_arg(args, unsigned int);
1348 		if (!b) {
1349 			va_end(args);
1350 			return;
1351 		}
1352 		xt_params->exit_err(PARAMETER_PROBLEM,
1353 		           "%s: \"%s\" option cannot be inverted", p1, p2);
1354 		break;
1355 	case XTF_BAD_VALUE:
1356 		p2 = va_arg(args, const char *);
1357 		p3 = va_arg(args, const char *);
1358 		xt_params->exit_err(PARAMETER_PROBLEM,
1359 		           "%s: Bad value for \"%s\" option: \"%s\"",
1360 		           p1, p2, p3);
1361 		break;
1362 	case XTF_ONE_ACTION:
1363 		b = va_arg(args, unsigned int);
1364 		if (!b) {
1365 			va_end(args);
1366 			return;
1367 		}
1368 		xt_params->exit_err(PARAMETER_PROBLEM,
1369 		           "%s: At most one action is possible", p1);
1370 		break;
1371 	default:
1372 		xt_params->exit_err(status, p1, args);
1373 		break;
1374 	}
1375 
1376 	va_end(args);
1377 }
1378 
xtables_ipaddr_to_numeric(const struct in_addr * addrp)1379 const char *xtables_ipaddr_to_numeric(const struct in_addr *addrp)
1380 {
1381 	static char buf[20];
1382 	const unsigned char *bytep = (const void *)&addrp->s_addr;
1383 
1384 	sprintf(buf, "%u.%u.%u.%u", bytep[0], bytep[1], bytep[2], bytep[3]);
1385 	return buf;
1386 }
1387 
ipaddr_to_host(const struct in_addr * addr)1388 static const char *ipaddr_to_host(const struct in_addr *addr)
1389 {
1390 	static char hostname[NI_MAXHOST];
1391 	struct sockaddr_in saddr = {
1392 		.sin_family = AF_INET,
1393 		.sin_addr = *addr,
1394 	};
1395 	int err;
1396 
1397 
1398 	err = getnameinfo((const void *)&saddr, sizeof(struct sockaddr_in),
1399 		       hostname, sizeof(hostname) - 1, NULL, 0, 0);
1400 	if (err != 0)
1401 		return NULL;
1402 
1403 	return hostname;
1404 }
1405 
ipaddr_to_network(const struct in_addr * addr)1406 static const char *ipaddr_to_network(const struct in_addr *addr)
1407 {
1408 	struct netent *net;
1409 
1410 	if ((net = getnetbyaddr(ntohl(addr->s_addr), AF_INET)) != NULL)
1411 		return net->n_name;
1412 
1413 	return NULL;
1414 }
1415 
xtables_ipaddr_to_anyname(const struct in_addr * addr)1416 const char *xtables_ipaddr_to_anyname(const struct in_addr *addr)
1417 {
1418 	const char *name;
1419 
1420 	if ((name = ipaddr_to_host(addr)) != NULL ||
1421 	    (name = ipaddr_to_network(addr)) != NULL)
1422 		return name;
1423 
1424 	return xtables_ipaddr_to_numeric(addr);
1425 }
1426 
xtables_ipmask_to_cidr(const struct in_addr * mask)1427 int xtables_ipmask_to_cidr(const struct in_addr *mask)
1428 {
1429 	uint32_t maskaddr, bits;
1430 	int i;
1431 
1432 	maskaddr = ntohl(mask->s_addr);
1433 	/* shortcut for /32 networks */
1434 	if (maskaddr == 0xFFFFFFFFL)
1435 		return 32;
1436 
1437 	i = 32;
1438 	bits = 0xFFFFFFFEL;
1439 	while (--i >= 0 && maskaddr != bits)
1440 		bits <<= 1;
1441 	if (i >= 0)
1442 		return i;
1443 
1444 	/* this mask cannot be converted to CIDR notation */
1445 	return -1;
1446 }
1447 
xtables_ipmask_to_numeric(const struct in_addr * mask)1448 const char *xtables_ipmask_to_numeric(const struct in_addr *mask)
1449 {
1450 	static char buf[20];
1451 	uint32_t cidr;
1452 
1453 	cidr = xtables_ipmask_to_cidr(mask);
1454 	if (cidr == (unsigned int)-1) {
1455 		/* mask was not a decent combination of 1's and 0's */
1456 		sprintf(buf, "/%s", xtables_ipaddr_to_numeric(mask));
1457 		return buf;
1458 	} else if (cidr == 32) {
1459 		/* we don't want to see "/32" */
1460 		return "";
1461 	}
1462 
1463 	sprintf(buf, "/%d", cidr);
1464 	return buf;
1465 }
1466 
__numeric_to_ipaddr(const char * dotted,bool is_mask)1467 static struct in_addr *__numeric_to_ipaddr(const char *dotted, bool is_mask)
1468 {
1469 	static struct in_addr addr;
1470 	unsigned char *addrp;
1471 	unsigned int onebyte;
1472 	char buf[20], *p, *q;
1473 	int i;
1474 
1475 	/* copy dotted string, because we need to modify it */
1476 	strncpy(buf, dotted, sizeof(buf) - 1);
1477 	buf[sizeof(buf) - 1] = '\0';
1478 	addrp = (void *)&addr.s_addr;
1479 
1480 	p = buf;
1481 	for (i = 0; i < 3; ++i) {
1482 		if ((q = strchr(p, '.')) == NULL) {
1483 			if (is_mask)
1484 				return NULL;
1485 
1486 			/* autocomplete, this is a network address */
1487 			if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1488 				return NULL;
1489 
1490 			addrp[i] = onebyte;
1491 			while (i < 3)
1492 				addrp[++i] = 0;
1493 
1494 			return &addr;
1495 		}
1496 
1497 		*q = '\0';
1498 		if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1499 			return NULL;
1500 
1501 		addrp[i] = onebyte;
1502 		p = q + 1;
1503 	}
1504 
1505 	/* we have checked 3 bytes, now we check the last one */
1506 	if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1507 		return NULL;
1508 
1509 	addrp[3] = onebyte;
1510 	return &addr;
1511 }
1512 
xtables_numeric_to_ipaddr(const char * dotted)1513 struct in_addr *xtables_numeric_to_ipaddr(const char *dotted)
1514 {
1515 	return __numeric_to_ipaddr(dotted, false);
1516 }
1517 
xtables_numeric_to_ipmask(const char * dotted)1518 struct in_addr *xtables_numeric_to_ipmask(const char *dotted)
1519 {
1520 	return __numeric_to_ipaddr(dotted, true);
1521 }
1522 
network_to_ipaddr(const char * name)1523 static struct in_addr *network_to_ipaddr(const char *name)
1524 {
1525 	static struct in_addr addr;
1526 	struct netent *net;
1527 
1528 	if ((net = getnetbyname(name)) != NULL) {
1529 		if (net->n_addrtype != AF_INET)
1530 			return NULL;
1531 		addr.s_addr = htonl(net->n_net);
1532 		return &addr;
1533 	}
1534 
1535 	return NULL;
1536 }
1537 
host_to_ipaddr(const char * name,unsigned int * naddr)1538 static struct in_addr *host_to_ipaddr(const char *name, unsigned int *naddr)
1539 {
1540 	struct in_addr *addr;
1541 	struct addrinfo hints;
1542 	struct addrinfo *res, *p;
1543 	int err;
1544 	unsigned int i;
1545 
1546 	memset(&hints, 0, sizeof(hints));
1547 	hints.ai_family   = AF_INET;
1548 	hints.ai_socktype = SOCK_RAW;
1549 
1550 	*naddr = 0;
1551 	err = getaddrinfo(name, NULL, &hints, &res);
1552 	if (err != 0)
1553 		return NULL;
1554 	for (p = res; p != NULL; p = p->ai_next)
1555 		++*naddr;
1556 	addr = xtables_calloc(*naddr, sizeof(struct in_addr));
1557 	for (i = 0, p = res; p != NULL; p = p->ai_next)
1558 		memcpy(&addr[i++],
1559 		       &((const struct sockaddr_in *)p->ai_addr)->sin_addr,
1560 		       sizeof(struct in_addr));
1561 	freeaddrinfo(res);
1562 	return addr;
1563 }
1564 
1565 static struct in_addr *
ipparse_hostnetwork(const char * name,unsigned int * naddrs)1566 ipparse_hostnetwork(const char *name, unsigned int *naddrs)
1567 {
1568 	struct in_addr *addrptmp, *addrp;
1569 
1570 	if ((addrptmp = xtables_numeric_to_ipaddr(name)) != NULL ||
1571 	    (addrptmp = network_to_ipaddr(name)) != NULL) {
1572 		addrp = xtables_malloc(sizeof(struct in_addr));
1573 		memcpy(addrp, addrptmp, sizeof(*addrp));
1574 		*naddrs = 1;
1575 		return addrp;
1576 	}
1577 	if ((addrptmp = host_to_ipaddr(name, naddrs)) != NULL)
1578 		return addrptmp;
1579 
1580 	xt_params->exit_err(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1581 }
1582 
parse_ipmask(const char * mask)1583 static struct in_addr *parse_ipmask(const char *mask)
1584 {
1585 	static struct in_addr maskaddr;
1586 	struct in_addr *addrp;
1587 	unsigned int bits;
1588 
1589 	if (mask == NULL) {
1590 		/* no mask at all defaults to 32 bits */
1591 		maskaddr.s_addr = 0xFFFFFFFF;
1592 		return &maskaddr;
1593 	}
1594 	if ((addrp = xtables_numeric_to_ipmask(mask)) != NULL)
1595 		/* dotted_to_addr already returns a network byte order addr */
1596 		return addrp;
1597 	if (!xtables_strtoui(mask, NULL, &bits, 0, 32))
1598 		xt_params->exit_err(PARAMETER_PROBLEM,
1599 			   "invalid mask `%s' specified", mask);
1600 	if (bits != 0) {
1601 		maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
1602 		return &maskaddr;
1603 	}
1604 
1605 	maskaddr.s_addr = 0U;
1606 	return &maskaddr;
1607 }
1608 
xtables_ipparse_multiple(const char * name,struct in_addr ** addrpp,struct in_addr ** maskpp,unsigned int * naddrs)1609 void xtables_ipparse_multiple(const char *name, struct in_addr **addrpp,
1610                               struct in_addr **maskpp, unsigned int *naddrs)
1611 {
1612 	struct in_addr *addrp;
1613 	char buf[256], *p, *next;
1614 	unsigned int len, i, j, n, count = 1;
1615 	const char *loop = name;
1616 
1617 	while ((loop = strchr(loop, ',')) != NULL) {
1618 		++count;
1619 		++loop; /* skip ',' */
1620 	}
1621 
1622 	*addrpp = xtables_malloc(sizeof(struct in_addr) * count);
1623 	*maskpp = xtables_malloc(sizeof(struct in_addr) * count);
1624 
1625 	loop = name;
1626 
1627 	for (i = 0; i < count; ++i) {
1628 		while (isspace(*loop))
1629 			++loop;
1630 		next = strchr(loop, ',');
1631 		if (next != NULL)
1632 			len = next - loop;
1633 		else
1634 			len = strlen(loop);
1635 		if (len > sizeof(buf) - 1)
1636 			xt_params->exit_err(PARAMETER_PROBLEM,
1637 				"Hostname too long");
1638 
1639 		strncpy(buf, loop, len);
1640 		buf[len] = '\0';
1641 		if ((p = strrchr(buf, '/')) != NULL) {
1642 			*p = '\0';
1643 			addrp = parse_ipmask(p + 1);
1644 		} else {
1645 			addrp = parse_ipmask(NULL);
1646 		}
1647 		memcpy(*maskpp + i, addrp, sizeof(*addrp));
1648 
1649 		/* if a null mask is given, the name is ignored, like in "any/0" */
1650 		if ((*maskpp + i)->s_addr == 0)
1651 			/*
1652 			 * A bit pointless to process multiple addresses
1653 			 * in this case...
1654 			 */
1655 			strcpy(buf, "0.0.0.0");
1656 
1657 		addrp = ipparse_hostnetwork(buf, &n);
1658 		if (n > 1) {
1659 			count += n - 1;
1660 			*addrpp = xtables_realloc(*addrpp,
1661 			          sizeof(struct in_addr) * count);
1662 			*maskpp = xtables_realloc(*maskpp,
1663 			          sizeof(struct in_addr) * count);
1664 			for (j = 0; j < n; ++j)
1665 				/* for each new addr */
1666 				memcpy(*addrpp + i + j, addrp + j,
1667 				       sizeof(*addrp));
1668 			for (j = 1; j < n; ++j)
1669 				/* for each new mask */
1670 				memcpy(*maskpp + i + j, *maskpp + i,
1671 				       sizeof(*addrp));
1672 			i += n - 1;
1673 		} else {
1674 			memcpy(*addrpp + i, addrp, sizeof(*addrp));
1675 		}
1676 		/* free what ipparse_hostnetwork had allocated: */
1677 		free(addrp);
1678 		if (next == NULL)
1679 			break;
1680 		loop = next + 1;
1681 	}
1682 	*naddrs = count;
1683 	for (i = 0; i < count; ++i)
1684 		(*addrpp+i)->s_addr &= (*maskpp+i)->s_addr;
1685 }
1686 
1687 
1688 /**
1689  * xtables_ipparse_any - transform arbitrary name to in_addr
1690  *
1691  * Possible inputs (pseudo regex):
1692  * 	m{^($hostname|$networkname|$ipaddr)(/$mask)?}
1693  * "1.2.3.4/5", "1.2.3.4", "hostname", "networkname"
1694  */
xtables_ipparse_any(const char * name,struct in_addr ** addrpp,struct in_addr * maskp,unsigned int * naddrs)1695 void xtables_ipparse_any(const char *name, struct in_addr **addrpp,
1696                          struct in_addr *maskp, unsigned int *naddrs)
1697 {
1698 	unsigned int i, j, k, n;
1699 	struct in_addr *addrp;
1700 	char buf[256], *p;
1701 
1702 	strncpy(buf, name, sizeof(buf) - 1);
1703 	buf[sizeof(buf) - 1] = '\0';
1704 	if ((p = strrchr(buf, '/')) != NULL) {
1705 		*p = '\0';
1706 		addrp = parse_ipmask(p + 1);
1707 	} else {
1708 		addrp = parse_ipmask(NULL);
1709 	}
1710 	memcpy(maskp, addrp, sizeof(*maskp));
1711 
1712 	/* if a null mask is given, the name is ignored, like in "any/0" */
1713 	if (maskp->s_addr == 0U)
1714 		strcpy(buf, "0.0.0.0");
1715 
1716 	addrp = *addrpp = ipparse_hostnetwork(buf, naddrs);
1717 	n = *naddrs;
1718 	for (i = 0, j = 0; i < n; ++i) {
1719 		addrp[j++].s_addr &= maskp->s_addr;
1720 		for (k = 0; k < j - 1; ++k)
1721 			if (addrp[k].s_addr == addrp[j-1].s_addr) {
1722 				/*
1723 				 * Nuke the dup by copying an address from the
1724 				 * tail here, and check the current position
1725 				 * again (--j).
1726 				 */
1727 				memcpy(&addrp[--j], &addrp[--*naddrs],
1728 				       sizeof(struct in_addr));
1729 				break;
1730 			}
1731 	}
1732 }
1733 
xtables_ip6addr_to_numeric(const struct in6_addr * addrp)1734 const char *xtables_ip6addr_to_numeric(const struct in6_addr *addrp)
1735 {
1736 	/* 0000:0000:0000:0000:0000:0000:000.000.000.000
1737 	 * 0000:0000:0000:0000:0000:0000:0000:0000 */
1738 	static char buf[50+1];
1739 	return inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
1740 }
1741 
ip6addr_to_host(const struct in6_addr * addr)1742 static const char *ip6addr_to_host(const struct in6_addr *addr)
1743 {
1744 	static char hostname[NI_MAXHOST];
1745 	struct sockaddr_in6 saddr;
1746 	int err;
1747 
1748 	memset(&saddr, 0, sizeof(struct sockaddr_in6));
1749 	memcpy(&saddr.sin6_addr, addr, sizeof(*addr));
1750 	saddr.sin6_family = AF_INET6;
1751 
1752 	err = getnameinfo((const void *)&saddr, sizeof(struct sockaddr_in6),
1753 			hostname, sizeof(hostname) - 1, NULL, 0, 0);
1754 	if (err != 0)
1755 		return NULL;
1756 
1757 	return hostname;
1758 }
1759 
xtables_ip6addr_to_anyname(const struct in6_addr * addr)1760 const char *xtables_ip6addr_to_anyname(const struct in6_addr *addr)
1761 {
1762 	const char *name;
1763 
1764 	if ((name = ip6addr_to_host(addr)) != NULL)
1765 		return name;
1766 
1767 	return xtables_ip6addr_to_numeric(addr);
1768 }
1769 
xtables_ip6mask_to_cidr(const struct in6_addr * k)1770 int xtables_ip6mask_to_cidr(const struct in6_addr *k)
1771 {
1772 	unsigned int bits = 0;
1773 	uint32_t a, b, c, d;
1774 
1775 	a = ntohl(k->s6_addr32[0]);
1776 	b = ntohl(k->s6_addr32[1]);
1777 	c = ntohl(k->s6_addr32[2]);
1778 	d = ntohl(k->s6_addr32[3]);
1779 	while (a & 0x80000000U) {
1780 		++bits;
1781 		a <<= 1;
1782 		a  |= (b >> 31) & 1;
1783 		b <<= 1;
1784 		b  |= (c >> 31) & 1;
1785 		c <<= 1;
1786 		c  |= (d >> 31) & 1;
1787 		d <<= 1;
1788 	}
1789 	if (a != 0 || b != 0 || c != 0 || d != 0)
1790 		return -1;
1791 	return bits;
1792 }
1793 
xtables_ip6mask_to_numeric(const struct in6_addr * addrp)1794 const char *xtables_ip6mask_to_numeric(const struct in6_addr *addrp)
1795 {
1796 	static char buf[50+2];
1797 	int l = xtables_ip6mask_to_cidr(addrp);
1798 
1799 	if (l == -1) {
1800 		strcpy(buf, "/");
1801 		strcat(buf, xtables_ip6addr_to_numeric(addrp));
1802 		return buf;
1803 	}
1804 	/* we don't want to see "/128" */
1805 	if (l == 128)
1806 		return "";
1807 	else
1808 		sprintf(buf, "/%d", l);
1809 	return buf;
1810 }
1811 
xtables_numeric_to_ip6addr(const char * num)1812 struct in6_addr *xtables_numeric_to_ip6addr(const char *num)
1813 {
1814 	static struct in6_addr ap;
1815 	int err;
1816 
1817 	if ((err = inet_pton(AF_INET6, num, &ap)) == 1)
1818 		return &ap;
1819 
1820 	return NULL;
1821 }
1822 
1823 static struct in6_addr *
host_to_ip6addr(const char * name,unsigned int * naddr)1824 host_to_ip6addr(const char *name, unsigned int *naddr)
1825 {
1826 	struct in6_addr *addr;
1827 	struct addrinfo hints;
1828 	struct addrinfo *res, *p;
1829 	int err;
1830 	unsigned int i;
1831 
1832 	memset(&hints, 0, sizeof(hints));
1833 	hints.ai_family   = AF_INET6;
1834 	hints.ai_socktype = SOCK_RAW;
1835 
1836 	*naddr = 0;
1837 	err = getaddrinfo(name, NULL, &hints, &res);
1838 	if (err != 0)
1839 		return NULL;
1840 	/* Find length of address chain */
1841 	for (p = res; p != NULL; p = p->ai_next)
1842 		++*naddr;
1843 	/* Copy each element of the address chain */
1844 	addr = xtables_calloc(*naddr, sizeof(struct in6_addr));
1845 	for (i = 0, p = res; p != NULL; p = p->ai_next)
1846 		memcpy(&addr[i++],
1847 		       &((const struct sockaddr_in6 *)p->ai_addr)->sin6_addr,
1848 		       sizeof(struct in6_addr));
1849 	freeaddrinfo(res);
1850 	return addr;
1851 }
1852 
network_to_ip6addr(const char * name)1853 static struct in6_addr *network_to_ip6addr(const char *name)
1854 {
1855 	/*	abort();*/
1856 	/* TODO: not implemented yet, but the exception breaks the
1857 	 *       name resolvation */
1858 	return NULL;
1859 }
1860 
1861 static struct in6_addr *
ip6parse_hostnetwork(const char * name,unsigned int * naddrs)1862 ip6parse_hostnetwork(const char *name, unsigned int *naddrs)
1863 {
1864 	struct in6_addr *addrp, *addrptmp;
1865 
1866 	if ((addrptmp = xtables_numeric_to_ip6addr(name)) != NULL ||
1867 	    (addrptmp = network_to_ip6addr(name)) != NULL) {
1868 		addrp = xtables_malloc(sizeof(struct in6_addr));
1869 		memcpy(addrp, addrptmp, sizeof(*addrp));
1870 		*naddrs = 1;
1871 		return addrp;
1872 	}
1873 	if ((addrp = host_to_ip6addr(name, naddrs)) != NULL)
1874 		return addrp;
1875 
1876 	xt_params->exit_err(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1877 }
1878 
parse_ip6mask(char * mask)1879 static struct in6_addr *parse_ip6mask(char *mask)
1880 {
1881 	static struct in6_addr maskaddr;
1882 	struct in6_addr *addrp;
1883 	unsigned int bits;
1884 
1885 	if (mask == NULL) {
1886 		/* no mask at all defaults to 128 bits */
1887 		memset(&maskaddr, 0xff, sizeof maskaddr);
1888 		return &maskaddr;
1889 	}
1890 	if ((addrp = xtables_numeric_to_ip6addr(mask)) != NULL)
1891 		return addrp;
1892 	if (!xtables_strtoui(mask, NULL, &bits, 0, 128))
1893 		xt_params->exit_err(PARAMETER_PROBLEM,
1894 			   "invalid mask `%s' specified", mask);
1895 	if (bits != 0) {
1896 		char *p = (void *)&maskaddr;
1897 		memset(p, 0xff, bits / 8);
1898 		memset(p + ((bits + 7) / 8), 0, (128 - bits) / 8);
1899 		if (bits < 128)
1900 			p[bits/8] = 0xff << (8 - (bits & 7));
1901 		return &maskaddr;
1902 	}
1903 
1904 	memset(&maskaddr, 0, sizeof(maskaddr));
1905 	return &maskaddr;
1906 }
1907 
1908 void
xtables_ip6parse_multiple(const char * name,struct in6_addr ** addrpp,struct in6_addr ** maskpp,unsigned int * naddrs)1909 xtables_ip6parse_multiple(const char *name, struct in6_addr **addrpp,
1910 		      struct in6_addr **maskpp, unsigned int *naddrs)
1911 {
1912 	static const struct in6_addr zero_addr;
1913 	struct in6_addr *addrp;
1914 	char buf[256], *p, *next;
1915 	unsigned int len, i, j, n, count = 1;
1916 	const char *loop = name;
1917 
1918 	while ((loop = strchr(loop, ',')) != NULL) {
1919 		++count;
1920 		++loop; /* skip ',' */
1921 	}
1922 
1923 	*addrpp = xtables_malloc(sizeof(struct in6_addr) * count);
1924 	*maskpp = xtables_malloc(sizeof(struct in6_addr) * count);
1925 
1926 	loop = name;
1927 
1928 	for (i = 0; i < count /*NB: count can grow*/; ++i) {
1929 		while (isspace(*loop))
1930 			++loop;
1931 		next = strchr(loop, ',');
1932 		if (next != NULL)
1933 			len = next - loop;
1934 		else
1935 			len = strlen(loop);
1936 		if (len > sizeof(buf) - 1)
1937 			xt_params->exit_err(PARAMETER_PROBLEM,
1938 				"Hostname too long");
1939 
1940 		strncpy(buf, loop, len);
1941 		buf[len] = '\0';
1942 		if ((p = strrchr(buf, '/')) != NULL) {
1943 			*p = '\0';
1944 			addrp = parse_ip6mask(p + 1);
1945 		} else {
1946 			addrp = parse_ip6mask(NULL);
1947 		}
1948 		memcpy(*maskpp + i, addrp, sizeof(*addrp));
1949 
1950 		/* if a null mask is given, the name is ignored, like in "any/0" */
1951 		if (memcmp(*maskpp + i, &zero_addr, sizeof(zero_addr)) == 0)
1952 			strcpy(buf, "::");
1953 
1954 		addrp = ip6parse_hostnetwork(buf, &n);
1955 		if (n > 1) {
1956 			count += n - 1;
1957 			*addrpp = xtables_realloc(*addrpp,
1958 			          sizeof(struct in6_addr) * count);
1959 			*maskpp = xtables_realloc(*maskpp,
1960 			          sizeof(struct in6_addr) * count);
1961 			for (j = 0; j < n; ++j)
1962 				/* for each new addr */
1963 				memcpy(*addrpp + i + j, addrp + j,
1964 				       sizeof(*addrp));
1965 			for (j = 1; j < n; ++j)
1966 				/* for each new mask */
1967 				memcpy(*maskpp + i + j, *maskpp + i,
1968 				       sizeof(*addrp));
1969 			i += n - 1;
1970 		} else {
1971 			memcpy(*addrpp + i, addrp, sizeof(*addrp));
1972 		}
1973 		/* free what ip6parse_hostnetwork had allocated: */
1974 		free(addrp);
1975 		if (next == NULL)
1976 			break;
1977 		loop = next + 1;
1978 	}
1979 	*naddrs = count;
1980 	for (i = 0; i < count; ++i)
1981 		for (j = 0; j < 4; ++j)
1982 			(*addrpp+i)->s6_addr32[j] &= (*maskpp+i)->s6_addr32[j];
1983 }
1984 
xtables_ip6parse_any(const char * name,struct in6_addr ** addrpp,struct in6_addr * maskp,unsigned int * naddrs)1985 void xtables_ip6parse_any(const char *name, struct in6_addr **addrpp,
1986                           struct in6_addr *maskp, unsigned int *naddrs)
1987 {
1988 	static const struct in6_addr zero_addr;
1989 	struct in6_addr *addrp;
1990 	unsigned int i, j, k, n;
1991 	char buf[256], *p;
1992 
1993 	strncpy(buf, name, sizeof(buf) - 1);
1994 	buf[sizeof(buf)-1] = '\0';
1995 	if ((p = strrchr(buf, '/')) != NULL) {
1996 		*p = '\0';
1997 		addrp = parse_ip6mask(p + 1);
1998 	} else {
1999 		addrp = parse_ip6mask(NULL);
2000 	}
2001 	memcpy(maskp, addrp, sizeof(*maskp));
2002 
2003 	/* if a null mask is given, the name is ignored, like in "any/0" */
2004 	if (memcmp(maskp, &zero_addr, sizeof(zero_addr)) == 0)
2005 		strcpy(buf, "::");
2006 
2007 	addrp = *addrpp = ip6parse_hostnetwork(buf, naddrs);
2008 	n = *naddrs;
2009 	for (i = 0, j = 0; i < n; ++i) {
2010 		for (k = 0; k < 4; ++k)
2011 			addrp[j].s6_addr32[k] &= maskp->s6_addr32[k];
2012 		++j;
2013 		for (k = 0; k < j - 1; ++k)
2014 			if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
2015 				/*
2016 				 * Nuke the dup by copying an address from the
2017 				 * tail here, and check the current position
2018 				 * again (--j).
2019 				 */
2020 				memcpy(&addrp[--j], &addrp[--*naddrs],
2021 				       sizeof(struct in_addr));
2022 				break;
2023 			}
2024 	}
2025 }
2026 
xtables_save_string(const char * value)2027 void xtables_save_string(const char *value)
2028 {
2029 	static const char no_quote_chars[] = "_-0123456789"
2030 		"abcdefghijklmnopqrstuvwxyz"
2031 		"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2032 	static const char escape_chars[] = "\"\\'";
2033 	size_t length;
2034 	const char *p;
2035 
2036 	length = strspn(value, no_quote_chars);
2037 	if (length > 0 && value[length] == 0) {
2038 		/* no quoting required */
2039 		putchar(' ');
2040 		fputs(value, stdout);
2041 	} else {
2042 		/* there is at least one dangerous character in the
2043 		   value, which we have to quote.  Write double quotes
2044 		   around the value and escape special characters with
2045 		   a backslash */
2046 		printf(" \"");
2047 
2048 		for (p = strpbrk(value, escape_chars); p != NULL;
2049 		     p = strpbrk(value, escape_chars)) {
2050 			if (p > value)
2051 				fwrite(value, 1, p - value, stdout);
2052 			putchar('\\');
2053 			putchar(*p);
2054 			value = p + 1;
2055 		}
2056 
2057 		/* print the rest and finish the double quoted
2058 		   string */
2059 		fputs(value, stdout);
2060 		putchar('\"');
2061 	}
2062 }
2063 
2064 const struct xtables_pprot xtables_chain_protos[] = {
2065 	{"tcp",       IPPROTO_TCP},
2066 	{"sctp",      IPPROTO_SCTP},
2067 	{"udp",       IPPROTO_UDP},
2068 	{"udplite",   IPPROTO_UDPLITE},
2069 	{"icmp",      IPPROTO_ICMP},
2070 	{"icmpv6",    IPPROTO_ICMPV6},
2071 	{"ipv6-icmp", IPPROTO_ICMPV6},
2072 	{"esp",       IPPROTO_ESP},
2073 	{"ah",        IPPROTO_AH},
2074 	{"ipv6-mh",   IPPROTO_MH},
2075 	{"mh",        IPPROTO_MH},
2076 	{"all",       0},
2077 	{NULL},
2078 };
2079 
2080 uint16_t
xtables_parse_protocol(const char * s)2081 xtables_parse_protocol(const char *s)
2082 {
2083 	const struct protoent *pent;
2084 	unsigned int proto, i;
2085 
2086 	if (xtables_strtoui(s, NULL, &proto, 0, UINT8_MAX))
2087 		return proto;
2088 
2089 	/* first deal with the special case of 'all' to prevent
2090 	 * people from being able to redefine 'all' in nsswitch
2091 	 * and/or provoke expensive [not working] ldap/nis/...
2092 	 * lookups */
2093 	if (strcmp(s, "all") == 0)
2094 		return 0;
2095 
2096 	pent = getprotobyname(s);
2097 	if (pent != NULL)
2098 		return pent->p_proto;
2099 
2100 	for (i = 0; i < ARRAY_SIZE(xtables_chain_protos); ++i) {
2101 		if (xtables_chain_protos[i].name == NULL)
2102 			continue;
2103 		if (strcmp(s, xtables_chain_protos[i].name) == 0)
2104 			return xtables_chain_protos[i].num;
2105 	}
2106 	xt_params->exit_err(PARAMETER_PROBLEM,
2107 		"unknown protocol \"%s\" specified", s);
2108 	return -1;
2109 }
2110 
xtables_print_num(uint64_t number,unsigned int format)2111 void xtables_print_num(uint64_t number, unsigned int format)
2112 {
2113 	if (!(format & FMT_KILOMEGAGIGA)) {
2114 		printf(FMT("%8llu ","%llu "), (unsigned long long)number);
2115 		return;
2116 	}
2117 	if (number <= 99999) {
2118 		printf(FMT("%5llu ","%llu "), (unsigned long long)number);
2119 		return;
2120 	}
2121 	number = (number + 500) / 1000;
2122 	if (number <= 9999) {
2123 		printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
2124 		return;
2125 	}
2126 	number = (number + 500) / 1000;
2127 	if (number <= 9999) {
2128 		printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
2129 		return;
2130 	}
2131 	number = (number + 500) / 1000;
2132 	if (number <= 9999) {
2133 		printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
2134 		return;
2135 	}
2136 	number = (number + 500) / 1000;
2137 	printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
2138 }
2139 
2140 #include <netinet/ether.h>
2141 
2142 static const unsigned char mac_type_unicast[ETH_ALEN] =   {};
2143 static const unsigned char msk_type_unicast[ETH_ALEN] =   {1};
2144 static const unsigned char mac_type_multicast[ETH_ALEN] = {1};
2145 static const unsigned char msk_type_multicast[ETH_ALEN] = {1};
2146 #define ALL_ONE_MAC {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
2147 static const unsigned char mac_type_broadcast[ETH_ALEN] = ALL_ONE_MAC;
2148 static const unsigned char msk_type_broadcast[ETH_ALEN] = ALL_ONE_MAC;
2149 static const unsigned char mac_type_bridge_group[ETH_ALEN] = {0x01, 0x80, 0xc2};
2150 static const unsigned char msk_type_bridge_group[ETH_ALEN] = ALL_ONE_MAC;
2151 #undef ALL_ONE_MAC
2152 
xtables_parse_mac_and_mask(const char * from,void * to,void * mask)2153 int xtables_parse_mac_and_mask(const char *from, void *to, void *mask)
2154 {
2155 	char *p;
2156 	int i;
2157 	struct ether_addr *addr = NULL;
2158 
2159 	if (strcasecmp(from, "Unicast") == 0) {
2160 		memcpy(to, mac_type_unicast, ETH_ALEN);
2161 		memcpy(mask, msk_type_unicast, ETH_ALEN);
2162 		return 0;
2163 	}
2164 	if (strcasecmp(from, "Multicast") == 0) {
2165 		memcpy(to, mac_type_multicast, ETH_ALEN);
2166 		memcpy(mask, msk_type_multicast, ETH_ALEN);
2167 		return 0;
2168 	}
2169 	if (strcasecmp(from, "Broadcast") == 0) {
2170 		memcpy(to, mac_type_broadcast, ETH_ALEN);
2171 		memcpy(mask, msk_type_broadcast, ETH_ALEN);
2172 		return 0;
2173 	}
2174 	if (strcasecmp(from, "BGA") == 0) {
2175 		memcpy(to, mac_type_bridge_group, ETH_ALEN);
2176 		memcpy(mask, msk_type_bridge_group, ETH_ALEN);
2177 		return 0;
2178 	}
2179 	if ( (p = strrchr(from, '/')) != NULL) {
2180 		*p = '\0';
2181 		if (!(addr = ether_aton(p + 1)))
2182 			return -1;
2183 		memcpy(mask, addr, ETH_ALEN);
2184 	} else
2185 		memset(mask, 0xff, ETH_ALEN);
2186 	if (!(addr = ether_aton(from)))
2187 		return -1;
2188 	memcpy(to, addr, ETH_ALEN);
2189 	for (i = 0; i < ETH_ALEN; i++)
2190 		((char *)to)[i] &= ((char *)mask)[i];
2191 	return 0;
2192 }
2193 
xtables_print_well_known_mac_and_mask(const void * mac,const void * mask)2194 int xtables_print_well_known_mac_and_mask(const void *mac, const void *mask)
2195 {
2196 	if (!memcmp(mac, mac_type_unicast, ETH_ALEN) &&
2197 	    !memcmp(mask, msk_type_unicast, ETH_ALEN))
2198 		printf("Unicast");
2199 	else if (!memcmp(mac, mac_type_multicast, ETH_ALEN) &&
2200 	         !memcmp(mask, msk_type_multicast, ETH_ALEN))
2201 		printf("Multicast");
2202 	else if (!memcmp(mac, mac_type_broadcast, ETH_ALEN) &&
2203 	         !memcmp(mask, msk_type_broadcast, ETH_ALEN))
2204 		printf("Broadcast");
2205 	else if (!memcmp(mac, mac_type_bridge_group, ETH_ALEN) &&
2206 	         !memcmp(mask, msk_type_bridge_group, ETH_ALEN))
2207 		printf("BGA");
2208 	else
2209 		return -1;
2210 	return 0;
2211 }
2212 
xtables_print_mac(const unsigned char * macaddress)2213 void xtables_print_mac(const unsigned char *macaddress)
2214 {
2215 	unsigned int i;
2216 
2217 	printf("%02x", macaddress[0]);
2218 	for (i = 1; i < 6; ++i)
2219 		printf(":%02x", macaddress[i]);
2220 }
2221 
xtables_print_mac_and_mask(const unsigned char * mac,const unsigned char * mask)2222 void xtables_print_mac_and_mask(const unsigned char *mac, const unsigned char *mask)
2223 {
2224 	static const char hlpmsk[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
2225 
2226 	xtables_print_mac(mac);
2227 
2228 	if (memcmp(mask, hlpmsk, 6) == 0)
2229 		return;
2230 
2231 	printf("/");
2232 	xtables_print_mac(mask);
2233 }
2234 
xtables_parse_val_mask(struct xt_option_call * cb,unsigned int * val,unsigned int * mask,const struct xtables_lmap * lmap)2235 void xtables_parse_val_mask(struct xt_option_call *cb,
2236 			    unsigned int *val, unsigned int *mask,
2237 			    const struct xtables_lmap *lmap)
2238 {
2239 	char *end;
2240 
2241 	*mask = ~0U;
2242 
2243 	if (!xtables_strtoui(cb->arg, &end, val, 0, UINT32_MAX)) {
2244 		if (lmap)
2245 			goto name2val;
2246 		else
2247 			goto bad_val;
2248 	}
2249 
2250 	if (*end == '\0')
2251 		return;
2252 
2253 	if (*end != '/') {
2254 		if (lmap)
2255 			goto name2val;
2256 		else
2257 			goto garbage;
2258 	}
2259 
2260 	if (!xtables_strtoui(end + 1, &end, mask, 0, UINT32_MAX))
2261 		goto bad_val;
2262 
2263 	if (*end == '\0')
2264 		return;
2265 
2266 garbage:
2267 	xt_params->exit_err(PARAMETER_PROBLEM,
2268 			"%s: trailing garbage after value "
2269 			"for option \"--%s\".\n",
2270 			cb->ext_name, cb->entry->name);
2271 
2272 bad_val:
2273 	xt_params->exit_err(PARAMETER_PROBLEM,
2274 			"%s: bad integer value for option \"--%s\", "
2275 			"or out of range.\n",
2276 			cb->ext_name, cb->entry->name);
2277 
2278 name2val:
2279 	*val = xtables_lmap_name2id(lmap, cb->arg);
2280 	if ((int)*val == -1)
2281 		xt_params->exit_err(PARAMETER_PROBLEM,
2282 			"%s: could not map name %s to an integer value "
2283 			"for option \"--%s\".\n",
2284 			cb->ext_name, cb->arg, cb->entry->name);
2285 }
2286 
xtables_print_val_mask(unsigned int val,unsigned int mask,const struct xtables_lmap * lmap)2287 void xtables_print_val_mask(unsigned int val, unsigned int mask,
2288 			    const struct xtables_lmap *lmap)
2289 {
2290 	if (mask != ~0U) {
2291 		printf(" 0x%x/0x%x", val, mask);
2292 		return;
2293 	}
2294 
2295 	if (lmap) {
2296 		const char *name = xtables_lmap_id2name(lmap, val);
2297 
2298 		if (name) {
2299 			printf(" %s", name);
2300 			return;
2301 		}
2302 	}
2303 
2304 	printf(" 0x%x", val);
2305 }
2306 
2307 int kernel_version;
2308 
get_kernel_version(void)2309 void get_kernel_version(void)
2310 {
2311 	static struct utsname uts;
2312 	int x = 0, y = 0, z = 0;
2313 
2314 	if (uname(&uts) == -1) {
2315 		fprintf(stderr, "Unable to retrieve kernel version.\n");
2316 		xtables_free_opts(1);
2317 		exit(1);
2318 	}
2319 
2320 	sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
2321 	kernel_version = LINUX_VERSION(x, y, z);
2322 }
2323 
2324 #include <linux/netfilter/nf_tables.h>
2325 
2326 struct xt_xlate {
2327 	struct {
2328 		char	*data;
2329 		int	size;
2330 		int	rem;
2331 		int	off;
2332 	} buf;
2333 	char comment[NFT_USERDATA_MAXLEN];
2334 };
2335 
xt_xlate_alloc(int size)2336 struct xt_xlate *xt_xlate_alloc(int size)
2337 {
2338 	struct xt_xlate *xl;
2339 
2340 	xl = malloc(sizeof(struct xt_xlate));
2341 	if (xl == NULL)
2342 		xtables_error(RESOURCE_PROBLEM, "OOM");
2343 
2344 	xl->buf.data = malloc(size);
2345 	if (xl->buf.data == NULL)
2346 		xtables_error(RESOURCE_PROBLEM, "OOM");
2347 
2348 	xl->buf.data[0] = '\0';
2349 	xl->buf.size = size;
2350 	xl->buf.rem = size;
2351 	xl->buf.off = 0;
2352 	xl->comment[0] = '\0';
2353 
2354 	return xl;
2355 }
2356 
xt_xlate_free(struct xt_xlate * xl)2357 void xt_xlate_free(struct xt_xlate *xl)
2358 {
2359 	free(xl->buf.data);
2360 	free(xl);
2361 }
2362 
xt_xlate_add(struct xt_xlate * xl,const char * fmt,...)2363 void xt_xlate_add(struct xt_xlate *xl, const char *fmt, ...)
2364 {
2365 	va_list ap;
2366 	int len;
2367 
2368 	va_start(ap, fmt);
2369 	len = vsnprintf(xl->buf.data + xl->buf.off, xl->buf.rem, fmt, ap);
2370 	if (len < 0 || len >= xl->buf.rem)
2371 		xtables_error(RESOURCE_PROBLEM, "OOM");
2372 
2373 	va_end(ap);
2374 	xl->buf.rem -= len;
2375 	xl->buf.off += len;
2376 }
2377 
xt_xlate_add_comment(struct xt_xlate * xl,const char * comment)2378 void xt_xlate_add_comment(struct xt_xlate *xl, const char *comment)
2379 {
2380 	strncpy(xl->comment, comment, NFT_USERDATA_MAXLEN - 1);
2381 	xl->comment[NFT_USERDATA_MAXLEN - 1] = '\0';
2382 }
2383 
xt_xlate_get_comment(struct xt_xlate * xl)2384 const char *xt_xlate_get_comment(struct xt_xlate *xl)
2385 {
2386 	return xl->comment[0] ? xl->comment : NULL;
2387 }
2388 
xt_xlate_get(struct xt_xlate * xl)2389 const char *xt_xlate_get(struct xt_xlate *xl)
2390 {
2391 	return xl->buf.data;
2392 }
2393