firewall.c 58.6 KB
Newer Older
1 2 3 4
/*
 *
 *  Connection Manager
 *
5
 *  Copyright (C) 2013,2015  BMW Car IT GmbH.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <errno.h>
27
#include <netdb.h>
28 29 30

#include <xtables.h>
#include <linux/netfilter_ipv4/ip_tables.h>
31
#include <linux/netfilter_ipv6/ip6_tables.h>
32 33 34 35

#include "connman.h"

#define CHAIN_PREFIX "connman-"
36
#define FW_ALL_RULES -1
37

38 39 40 41
/*
 * All IPv6 equivalents of the indexes used here have the same values as the
 * IPv4 ones.
 */
42 43 44 45 46 47 48 49 50
static const char *builtin_chains[] = {
	[NF_IP_PRE_ROUTING]	= "PREROUTING",
	[NF_IP_LOCAL_IN]	= "INPUT",
	[NF_IP_FORWARD]		= "FORWARD",
	[NF_IP_LOCAL_OUT]	= "OUTPUT",
	[NF_IP_POST_ROUTING]	= "POSTROUTING",
};

struct connman_managed_table {
51
	int type;
52 53 54 55 56
	char *name;
	unsigned int chains[NF_INET_NUMHOOKS];
};

struct fw_rule {
57
	int id;
58
	int type;
59
	bool enabled;
60 61 62
	char *table;
	char *chain;
	char *rule_spec;
63
	char *ifname;
64 65 66 67
};

struct firewall_context {
	GList *rules;
68
	bool enabled;
69 70
};

71
static GSList *managed_tables = NULL;
72

73
static bool firewall_is_up;
74
static unsigned int firewall_rule_id;
75

76 77 78 79
#define FIREWALLFILE "firewall.conf"
#define FIREWALLCONFIGFILE CONFIGDIR "/" FIREWALLFILE
#define FIREWALLCONFIGDIR CONFIGDIR "/firewall.d/"
#define GROUP_GENERAL "General"
80
#define GROUP_TETHERING "tethering"
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#define GENERAL_FIREWALL_POLICIES 3

struct general_firewall_context {
	char **policies;
	char **policiesv6;
	char **restore_policies;
	char **restore_policiesv6;
	struct firewall_context *ctx;
};

static struct general_firewall_context *general_firewall = NULL;

/* The dynamic rules that are loaded from config */
static struct firewall_context **dynamic_rules = NULL;

96 97 98
/* Tethering rules are a special case */
static struct firewall_context *tethering_firewall = NULL;

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static const char *supported_chains[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
	[NF_IP_LOCAL_IN]	= "INPUT",
	[NF_IP_FORWARD]		= "FORWARD",
	[NF_IP_LOCAL_OUT]	= "OUTPUT",
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_chainsv6[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
	[NF_IP_LOCAL_IN]	= "INPUT_IPv6",
	[NF_IP_FORWARD]		= "FORWARD_IPv6",
	[NF_IP_LOCAL_OUT]	= "OUTPUT_IPv6",
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_policies[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
	[NF_IP_LOCAL_IN]	= "INPUT_POLICY",
	[NF_IP_FORWARD]		= "FORWARD_POLICY",
	[NF_IP_LOCAL_OUT]	= "OUTPUT_POLICY",
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_policiesv6[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
	[NF_IP_LOCAL_IN]	= "INPUT_POLICY_IPv6",
	[NF_IP_FORWARD]		= "FORWARD_POLICY_IPv6",
	[NF_IP_LOCAL_OUT]	= "OUTPUT_POLICY_IPv6",
	[NF_IP_POST_ROUTING]	= NULL,
};

/*
 * The dynamic rules that are currently in use. Service name is used as hash
 * value and the struct firewall_context is the data held.
 */
135
static GHashTable *current_dynamic_rules = NULL;
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
static int chain_to_index(const char *chain_name)
{
	if (!g_strcmp0(builtin_chains[NF_IP_PRE_ROUTING], chain_name))
		return NF_IP_PRE_ROUTING;
	if (!g_strcmp0(builtin_chains[NF_IP_LOCAL_IN], chain_name))
		return NF_IP_LOCAL_IN;
	if (!g_strcmp0(builtin_chains[NF_IP_FORWARD], chain_name))
		return NF_IP_FORWARD;
	if (!g_strcmp0(builtin_chains[NF_IP_LOCAL_OUT], chain_name))
		return NF_IP_LOCAL_OUT;
	if (!g_strcmp0(builtin_chains[NF_IP_POST_ROUTING], chain_name))
		return NF_IP_POST_ROUTING;

	return -1;
}

static int managed_chain_to_index(const char *chain_name)
{
155
	if (!g_str_has_prefix(chain_name, CHAIN_PREFIX))
156 157 158 159 160
		return -1;

	return chain_to_index(chain_name + strlen(CHAIN_PREFIX));
}

161
static int insert_managed_chain(int type, const char *table_name, int id)
162 163 164 165 166 167 168
{
	char *rule, *managed_chain;
	int err;

	managed_chain = g_strdup_printf("%s%s", CHAIN_PREFIX,
					builtin_chains[id]);

169 170
	err = __connman_iptables_new_chain(type, table_name, managed_chain);

171 172 173 174
	if (err < 0)
		goto out;

	rule = g_strdup_printf("-j %s", managed_chain);
175 176 177 178

	err = __connman_iptables_insert(type, table_name,
					builtin_chains[id], rule);

179 180
	g_free(rule);
	if (err < 0) {
181 182
		__connman_iptables_delete_chain(type, table_name,
						managed_chain);
183 184 185 186 187 188 189 190 191
		goto out;
	}

out:
	g_free(managed_chain);

	return err;
}

192
static int delete_managed_chain(int type, const char *table_name, int id)
193 194 195 196 197 198 199 200
{
	char *rule, *managed_chain;
	int err;

	managed_chain = g_strdup_printf("%s%s", CHAIN_PREFIX,
					builtin_chains[id]);

	rule = g_strdup_printf("-j %s", managed_chain);
201 202
	err = __connman_iptables_delete(type, table_name,
					builtin_chains[id], rule);
203 204 205 206 207
	g_free(rule);

	if (err < 0)
		goto out;

208 209
	err =  __connman_iptables_delete_chain(type, table_name,
					managed_chain);
210 211 212 213 214 215 216

out:
	g_free(managed_chain);

	return err;
}

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
static char *format_new_rule(int chain, const char* ifname, const char* rule)
{
	char *new_rule = NULL;

	if (ifname && *ifname && rule && *rule) {
		switch (chain) {
		case NF_IP_LOCAL_IN:
			new_rule = g_strdup_printf("-i %s %s", ifname, rule);
			break;
		case NF_IP_FORWARD:
		case NF_IP_LOCAL_OUT:
			new_rule = g_strdup_printf("-o %s %s", ifname, rule);
			break;
		default:
			break;
		}
	}

	return new_rule;
}

static int insert_managed_rule(int type,
				const char *table_name,
240
				const char *chain_name,
241
				const char *ifname,
242 243 244 245 246
				const char *rule_spec)
{
	struct connman_managed_table *mtable = NULL;
	GSList *list;
	char *chain;
247
	char *full_rule = NULL;
248 249 250
	int id, err;

	id = chain_to_index(chain_name);
251 252 253

	full_rule = format_new_rule(id, ifname, rule_spec);

254 255 256 257 258 259
	if (id < 0) {
		/* This chain is not managed */
		chain = g_strdup(chain_name);
		goto out;
	}

260
	for (list = managed_tables; list; list = list->next) {
261 262
		mtable = list->data;

263 264
		if (g_strcmp0(mtable->name, table_name) == 0 &&
				mtable->type == type)
265 266 267 268 269
			break;

		mtable = NULL;
	}

270
	if (!mtable) {
271 272
		mtable = g_new0(struct connman_managed_table, 1);
		mtable->name = g_strdup(table_name);
273
		mtable->type = type;
274 275 276 277 278 279 280 281

		managed_tables = g_slist_prepend(managed_tables, mtable);
	}

	if (mtable->chains[id] == 0) {
		DBG("table %s add managed chain for %s",
			table_name, chain_name);

282
		err = insert_managed_chain(type, table_name, id);
283 284 285 286 287 288 289 290
		if (err < 0)
			return err;
	}

	mtable->chains[id]++;
	chain = g_strdup_printf("%s%s", CHAIN_PREFIX, chain_name);

out:
291 292
	err = __connman_iptables_append(type, table_name, chain,
				full_rule ? full_rule : rule_spec);
293 294
	
	if (err < 0)
295 296
		DBG("table %s cannot append rule %s", table_name,
				full_rule ? full_rule : rule_spec);
297 298

	g_free(chain);
299
	g_free(full_rule);
300 301 302 303

	return err;
 }

304
static int delete_managed_rule(int type, const char *table_name,
305
				const char *chain_name,
306
				const char *ifname,
307 308 309 310 311 312
				const char *rule_spec)
 {
	struct connman_managed_table *mtable = NULL;
	GSList *list;
	int id, err;
	char *managed_chain;
313
	char *full_rule = NULL;
314 315

	id = chain_to_index(chain_name);
316 317 318

	full_rule = format_new_rule(id, ifname, rule_spec);

319 320
	if (id < 0) {
		/* This chain is not managed */
321
		return __connman_iptables_delete(type, table_name,
322 323
					chain_name,
					full_rule ? full_rule : rule_spec);
324 325 326 327
	}

	managed_chain = g_strdup_printf("%s%s", CHAIN_PREFIX, chain_name);

328
	err = __connman_iptables_delete(type, table_name, managed_chain,
329
				full_rule ? full_rule : rule_spec);
330 331 332
	
	if (err < 0)
		DBG("table %s managed rule %s was not removed from ip%stables",
333 334
			table_name, full_rule ? full_rule : rule_spec,
			type == AF_INET6 ? "6" : "");
335

336
	for (list = managed_tables; list; list = list->next) {
337 338
		mtable = list->data;

339 340
		if (g_strcmp0(mtable->name, table_name) == 0 &&
				mtable->type == type)
341 342 343 344 345
			break;

		mtable = NULL;
	}

346
	if (!mtable) {
347 348 349 350 351 352 353 354 355 356 357
		err = -ENOENT;
		goto out;
	}

	mtable->chains[id]--;
	if (mtable->chains[id] > 0)
		goto out;

	DBG("table %s remove managed chain for %s",
			table_name, chain_name);

358
	err = delete_managed_chain(type, table_name, id);
359 360 361

 out:
	g_free(managed_chain);
362
	g_free(full_rule);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

	return err;
}

static void cleanup_managed_table(gpointer user_data)
{
	struct connman_managed_table *table = user_data;

	g_free(table->name);
	g_free(table);
}

static void cleanup_fw_rule(gpointer user_data)
{
	struct fw_rule *rule = user_data;

379
	g_free(rule->ifname);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	g_free(rule->rule_spec);
	g_free(rule->chain);
	g_free(rule->table);
	g_free(rule);
}

struct firewall_context *__connman_firewall_create(void)
{
	struct firewall_context *ctx;

	ctx = g_new0(struct firewall_context, 1);

	return ctx;
}

void __connman_firewall_destroy(struct firewall_context *ctx)
{
	g_list_free_full(ctx->rules, cleanup_fw_rule);
	g_free(ctx);
}

401 402 403 404 405 406 407
static int firewall_enable_rule(struct fw_rule *rule)
{
	int err;

	if (rule->enabled)
		return -EALREADY;

408
	DBG("%d %s %s %s %s", rule->type, rule->table, rule->chain,
409
					rule->ifname, rule->rule_spec);
410

411
	err = insert_managed_rule(rule->type, rule->table, rule->chain,
412
					rule->ifname, rule->rule_spec);
413 414
	if (err < 0) {
		DBG("cannot insert managed rule %d", err);
415
		return err;
416
	}
417

418 419
	err = __connman_iptables_commit(rule->type, rule->table);

420 421
	if (err < 0) {
		DBG("iptables commit failed %d", err);
422
		return err;
423
	}
424 425 426 427 428 429 430 431 432 433 434 435 436

	rule->enabled = true;

	return 0;
}

static int firewall_disable_rule(struct fw_rule *rule)
{
	int err;

	if (!rule->enabled)
		return -EALREADY;

437
	err = delete_managed_rule(rule->type, rule->table, rule->chain,
438
					rule->ifname, rule->rule_spec);
439
	if (err < 0) {
440
		connman_error("pre-commit: Cannot remove previously installed "
441 442 443 444
			"iptables rules: %s", strerror(-err));
		return err;
	}

445 446
	err = __connman_iptables_commit(rule->type, rule->table);
	
447 448 449 450 451 452 453 454 455 456 457
	if (err < 0) {
		connman_error("Cannot remove previously installed "
			"iptables rules: %s", strerror(-err));
		return err;
	}

	rule->enabled = false;

	return 0;
}

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
int __connman_firewall_add_rule(struct firewall_context *ctx,
				const char *table,
				const char *chain,
				const char *rule_fmt, ...)
{
	va_list args;
	char *rule_spec;
	struct fw_rule *rule;

	va_start(args, rule_fmt);

	rule_spec = g_strdup_vprintf(rule_fmt, args);

	va_end(args);

	rule = g_new0(struct fw_rule, 1);

475
	rule->id = firewall_rule_id++;
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
	rule->type = AF_INET;
	rule->enabled = false;
	rule->table = g_strdup(table);
	rule->chain = g_strdup(chain);
	rule->rule_spec = rule_spec;

	ctx->rules = g_list_append(ctx->rules, rule);
	return rule->id;
}

int __connman_firewall_add_ipv6_rule(struct firewall_context *ctx,
				const char *table,
				const char *chain,
				const char *rule_fmt, ...)
{
	va_list args;
	char *rule_spec;
	struct fw_rule *rule;

	va_start(args, rule_fmt);

	rule_spec = g_strdup_vprintf(rule_fmt, args);

	va_end(args);

	rule = g_new0(struct fw_rule, 1);

	rule->id = firewall_rule_id++;
	rule->type = AF_INET6;
505
	rule->enabled = false;
506 507 508 509 510
	rule->table = g_strdup(table);
	rule->chain = g_strdup(chain);
	rule->rule_spec = rule_spec;

	ctx->rules = g_list_append(ctx->rules, rule);
511
	return rule->id;
512 513
}

514
int __connman_firewall_remove_rule(struct firewall_context *ctx, int id)
515 516 517
{
	struct fw_rule *rule;
	GList *list;
518
	int err = -ENOENT;
519

520 521 522
	list = g_list_last(ctx->rules);
	while (list) {
		GList *prev = g_list_previous(list);
523

524
		rule = list->data;
525 526 527 528 529 530 531
		if (rule->id == id || id == FW_ALL_RULES) {
			ctx->rules = g_list_remove(ctx->rules, rule);
			cleanup_fw_rule(rule);
			err = 0;

			if (id != FW_ALL_RULES)
				break;
532
		}
533 534

		list = prev;
535
	}
536

537 538 539
	return err;
}

540 541 542 543 544 545
/* For consistency, both IPv4 and IPv6 rules can be removed in similar way. */
int __connman_firewall_remove_ipv6_rule(struct firewall_context *ctx, int id)
{
	return __connman_firewall_remove_rule(ctx, id);
}

546 547 548 549
int __connman_firewall_enable_rule(struct firewall_context *ctx, int id)
{
	struct fw_rule *rule;
	GList *list;
550
	int e;
551
	int err = -ENOENT;
552
	int count = 0;
553 554 555 556 557

	for (list = g_list_first(ctx->rules); list; list = g_list_next(list)) {
		rule = list->data;

		if (rule->id == id || id == FW_ALL_RULES) {
558
			e = firewall_enable_rule(rule);
559

560 561 562 563 564
			/* Do not stop if enabling all rules */
			if (e == 0 && err == -ENOENT)
				err = 0;
			else if (e < 0)
				err = e;
565 566 567

			if (id != FW_ALL_RULES)
				break;
568
		}
569 570 571 572 573 574 575

		count++;
	}

	if (!err && id == FW_ALL_RULES) {
		DBG("firewall enabled");
		ctx->enabled = true;
576 577
	}

578
	return err;
579 580
}

581
int __connman_firewall_disable_rule(struct firewall_context *ctx, int id)
582 583 584
{
	struct fw_rule *rule;
	GList *list;
585 586
	int e;
	int err = -ENOENT;
587

588 589
	for (list = g_list_last(ctx->rules); list;
			list = g_list_previous(list)) {
590 591
		rule = list->data;

592 593
		if (rule->id == id || id == FW_ALL_RULES) {
			e = firewall_disable_rule(rule);
594

595 596
			/* Report last error back */
			if (e == 0 && err == -ENOENT)
597 598 599
				err = 0;
			else if (e < 0)
				err = e;
600

601 602 603
			if (id != FW_ALL_RULES)
				break;
		}
604 605
	}

606 607 608 609 610
	if (!err && id == FW_ALL_RULES) {
		DBG("firewall disabled");
		ctx->enabled = false;
	}

611 612
	return err;
}
613

614 615 616
int __connman_firewall_enable(struct firewall_context *ctx)
{
	int err;
617

618 619 620 621 622 623 624
	err = __connman_firewall_enable_rule(ctx, FW_ALL_RULES);
	if (err < 0) {
		connman_warn("Failed to install iptables rules: %s",
				strerror(-err));
		__connman_firewall_disable_rule(ctx, FW_ALL_RULES);
		return err;
	}
625

626
	firewall_is_up = true;
627

628
	return 0;
629 630 631 632
}

int __connman_firewall_disable(struct firewall_context *ctx)
{
633 634
	__connman_firewall_disable_rule(ctx, FW_ALL_RULES);
	return __connman_firewall_remove_rule(ctx, FW_ALL_RULES);
635 636
}

637 638 639 640 641
bool __connman_firewall_is_up(void)
{
	return firewall_is_up;
}

642 643 644 645 646 647 648 649 650 651 652 653
static void iterate_chains_cb(const char *chain_name, void *user_data)
{
	GSList **chains = user_data;
	int id;

	id = managed_chain_to_index(chain_name);
	if (id < 0)
		return;

	*chains = g_slist_prepend(*chains, GINT_TO_POINTER(id));
}

654
static void flush_table(int type, const char *table_name)
655 656 657 658 659
{
	GSList *chains = NULL, *list;
	char *rule, *managed_chain;
	int id, err;

660 661 662 663 664
	err = __connman_iptables_iterate_chains(type, table_name,
					iterate_chains_cb, &chains);
	
	if (err < 0)
		DBG("table %s cannot iterate chains", table_name);
665

666
	for (list = chains; list; list = list->next) {
667 668 669 670 671 672
		id = GPOINTER_TO_INT(list->data);

		managed_chain = g_strdup_printf("%s%s", CHAIN_PREFIX,
						builtin_chains[id]);

		rule = g_strdup_printf("-j %s", managed_chain);
673 674 675 676 677
		
		err = __connman_iptables_delete(type, table_name,
						builtin_chains[id],
						rule);

678 679 680 681 682 683
		if (err < 0) {
			connman_warn("Failed to delete jump rule '%s': %s",
				rule, strerror(-err));
		}
		g_free(rule);

684 685 686
		err = __connman_iptables_flush_chain(type, table_name,
						managed_chain);
		
687 688 689 690
		if (err < 0) {
			connman_warn("Failed to flush chain '%s': %s",
				managed_chain, strerror(-err));
		}
691 692 693 694
		
		err = __connman_iptables_delete_chain(type, table_name,
						managed_chain);
		
695 696 697 698 699 700 701 702
		if (err < 0) {
			connman_warn("Failed to delete chain '%s': %s",
				managed_chain, strerror(-err));
		}

		g_free(managed_chain);
	}

703
	err = __connman_iptables_commit(type, table_name);
704 705 706 707 708 709 710 711
	if (err < 0) {
		connman_warn("Failed to flush table '%s': %s",
			table_name, strerror(-err));
	}

	g_slist_free(chains);
}

712 713 714
#define IP_TABLES_NAMES_FILE "/proc/net/ip_tables_names"
#define IP6_TABLES_NAMES_FILE "/proc/net/ip6_tables_names"

715
static void flush_all_tables(int type)
716
{
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	gchar *content = NULL;
	gsize len = -1;
	GError *error = NULL;
	const char *iptables_file = NULL;
	const char *tables[] = { "filter", "mangle", "nat", NULL };
	char **tokens = NULL;
	int i, j;

	switch (type) {
	case AF_INET:
		iptables_file = IP_TABLES_NAMES_FILE;
		break;
	case AF_INET6:
		iptables_file = IP6_TABLES_NAMES_FILE;
		break;
	default:
		return;
	}
735

736
	if (!g_file_test(iptables_file,
737 738 739 740 741 742
			G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR)) {
		firewall_is_up = false;
		return;
	}

	firewall_is_up = true;
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
	if (!g_file_get_contents(iptables_file, &content, &len, &error)) {
		DBG("cannot flush tables, file %s read error: %s",
					iptables_file, error->message);
		g_clear_error(&error);
		goto out;
	}

	tokens = g_strsplit(content, "\n", -1);

	if (!tokens || !g_strv_length(tokens))
		goto out;

	/* Flush the tables ConnMan might have modified
	 * But do so if only ConnMan has done something with
	 * iptables */
	for (i = 0; tables[i]; i++) {
		for (j = 0; tokens[j]; j++) {
			if (!g_strcmp0(tables[i], tokens[j])) {
				DBG("flush type %d table %s", type, tables[i]);
				flush_table(type, tables[i]);
			}
		}
	}

out:
	g_free(content);
	g_strfreev(tokens);
771 772
}

773 774 775 776 777 778 779 780 781 782 783
static bool has_dynamic_rules_set(enum connman_service_type type)
{
	if (!dynamic_rules || !dynamic_rules[type])
		return false;

	if (g_list_length(dynamic_rules[type]->rules) == 0)
		return false;

	return true;
}

784
static void setup_firewall_rule_interface(gpointer data, gpointer user_data)
785 786 787 788
{
	struct fw_rule *rule;
	char *ifname;

789
	rule = data;
790
	ifname = user_data;
791

792
	/* If rule is already enabled interface info is already set */
793
	if (!rule || !ifname || rule->enabled)
794
		return;
795

796 797 798 799
	if (rule->ifname && g_str_equal(rule->ifname, ifname)) {
		DBG("rule %d ifname %s not changed", rule->id, rule->ifname);
		return;
	}
800

801
	g_free(rule->ifname);
802
	rule->ifname = g_strdup(ifname);
803

804 805
	DBG("rule %d %s %s", rule->id, rule->ifname, rule->rule_spec);
}
806

807 808 809 810
static gpointer copy_fw_rule(gconstpointer src, gpointer data)
{
	const struct fw_rule *old;
	struct fw_rule *new;
811
	char *ifname;
812 813
	
	old = src;
814
	ifname = data;
815

816 817
	if (!old)
		return NULL;
818

819 820 821 822
	new = g_try_new0(struct fw_rule, 1);

	if (!new)
		return NULL;
823

824 825 826 827 828 829
	new->id = firewall_rule_id++;
	new->enabled = false;
	new->type = old->type;
	new->table = g_strdup(old->table);
	new->chain = g_strdup(old->chain);
	new->rule_spec = g_strdup(old->rule_spec);
830

831
	setup_firewall_rule_interface(new, ifname);
832 833

	return new;
834 835
}

836 837
static struct firewall_context *clone_firewall_context(
						struct firewall_context *ctx,
838
						char *ifname)
839
{
840 841
	struct firewall_context *clone;

842
	if (!ctx || !ifname)
843 844 845 846 847 848 849
		return NULL;
	
	clone = __connman_firewall_create();
	
	if (!clone)
		return NULL;
	
850
	clone->rules = g_list_copy_deep(ctx->rules, copy_fw_rule, ifname);
851 852 853 854 855 856 857
	
	return clone;
}

static int enable_dynamic_rules(struct connman_service *service)
{
	struct firewall_context *ctx;
858
	enum connman_service_type type;
859
	const char *identifier;
860
	char *ifname = NULL;
861
	char *hash;
862

863
	DBG("");
864

865 866
	/* This is not set if the configuration has not been loaded */
	if (!current_dynamic_rules)
867
		return 0;
868 869

	identifier = connman_service_get_identifier(service);
870

871 872 873 874 875 876 877 878 879 880
	ctx = g_hash_table_lookup(current_dynamic_rules, identifier);

	/* Not found, check if it has dynamic rules configured */
	if (!ctx) {
		type = connman_service_get_type(service);
		
		/* No rules set for this type */
		if (!has_dynamic_rules_set(type))
			return 0;

881 882
		ifname = connman_service_get_interface(service);

883
		/* Create a clone with interface info from service */
884
		ctx = clone_firewall_context(dynamic_rules[type], ifname);
885 886

		/* Allocation of ctx failed */
887 888
		if (!ctx) {
			g_free(ifname);
889
			return -ENOMEM;
890
		}
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906

		hash = g_strdup(identifier);

		/*
		 * Add a new into hash table, this condition should not be ever
		 * met. Left for debugging.
		 */
		if (!g_hash_table_replace(current_dynamic_rules, hash, ctx))
			DBG("hash table error, key %s exists", hash);
		else
			DBG("added new firewall rules for service %p %s",
					service, identifier);
	} else {
		if (ctx->enabled)
			return -EALREADY;

907 908
		ifname = connman_service_get_interface(service);

909 910
		/* Set interface information for each firewall rule */
		g_list_foreach(ctx->rules, setup_firewall_rule_interface,
911
					ifname);
912 913

		DBG("reused firewall for service %p %s", service, identifier);
914 915
	}

916 917
	g_free(ifname);

918 919
	return __connman_firewall_enable(ctx);
}
920

921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
static int disable_dynamic_rules(struct connman_service *service)
{
	struct firewall_context *ctx;
	const char *identifier;

	DBG("");

	if (!current_dynamic_rules)
		return 0;

	identifier = connman_service_get_identifier(service);

	ctx = g_hash_table_lookup(current_dynamic_rules, identifier);

	/* No rules set, no error */
	if (!ctx)
		return 0;

	if (!ctx->enabled)
		return -EALREADY;

	/* Only disable rules, do not remove them to reduce mem fragmentation */
	return __connman_firewall_disable_rule(ctx, FW_ALL_RULES);
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
}

static void service_state_changed(struct connman_service *service,
				enum connman_service_state state)
{
	enum connman_service_type type;
	int err;

	type = connman_service_get_type(service);

	DBG("service %p %s type %d state %d", service,
				__connman_service_get_name(service), type,
				state);

	switch (state) {
	case CONNMAN_SERVICE_STATE_UNKNOWN:
	case CONNMAN_SERVICE_STATE_ASSOCIATION:
	case CONNMAN_SERVICE_STATE_CONFIGURATION:
		break;
	case CONNMAN_SERVICE_STATE_IDLE:
	case CONNMAN_SERVICE_STATE_FAILURE:
	case CONNMAN_SERVICE_STATE_DISCONNECT:
		err = disable_dynamic_rules(service);
967 968 969 970 971 972 973 974

		if (err == -EALREADY)
			DBG("dynamic firewall already disabled for service %p",
						service);
		else if (err)
			DBG("cannot disable dynamic rules of service %p "
						"error %d", service, err);

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
		break;
	case CONNMAN_SERVICE_STATE_READY:
	case CONNMAN_SERVICE_STATE_ONLINE:
		err = enable_dynamic_rules(service);

		if (err == -EALREADY)
			DBG("dynamic firewall already enabled for service %p",
						service);
		else if (err == -ENOMEM)
			DBG("firewall cloning failed for service %p", service);
		else if (err)
			DBG("cannot enable dynamic rules of service %p "
						", error %d", service, err);
	}
}

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
static void service_remove(struct connman_service *service)
{
	const char *identifier;

	if (!current_dynamic_rules)
		return;

	identifier = connman_service_get_identifier(service);

	if (g_hash_table_remove(current_dynamic_rules, identifier))
		DBG("removed dynamic rules of service %s", identifier);
}

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
static int add_default_tethering_rules(struct firewall_context *ctx,
								char *ifname)
{
	/* Add more in the future if needed */
	const char *tethering_rules[] = { "-j ACCEPT", NULL };
	int id;
	int i;

	/* Add tethering rules for both IPv4 and IPv6 when using usb */
	for (i = 0; tethering_rules[i]; i++) {
		id = __connman_firewall_add_rule(ctx, "filter", "INPUT",
					tethering_rules[i]);
		if (id < 0)
			DBG("cannot add IPv4 rule %s",
						tethering_rules[i]);

		id = __connman_firewall_add_ipv6_rule(ctx, "filter",
					"INPUT", tethering_rules[i]);
		if (id < 0)
			DBG("cannot add IPv6 rule %s",
						tethering_rules[i]);
	}

	g_list_foreach(ctx->rules, setup_firewall_rule_interface,
					ifname);

	return 0;
}

#define DEFAULT_TETHERING_IDENT "tethering_default"

static void tethering_changed(struct connman_technology *tech, bool on)
{
	struct firewall_context *ctx;
	enum connman_service_type type;
	const char *identifier;
	char *ifname = NULL;
	char *hash;
	int err;
	
	DBG("technology %p %s", tech, on ? "on" : "off");
	
	if (!tech)
		return;
	
	/* This is not set if the configuration has not been loaded */
	if (!current_dynamic_rules)
		return;

	type = __connman_technology_get_type(tech);
	identifier = __connman_technology_get_tethering_ident(tech);
	
	/* This is known to happen with usb tethering, no ident exists */
	if (!identifier)
		identifier = DEFAULT_TETHERING_IDENT;
	
	DBG("tethering ident %s type %s", identifier,
				__connman_service_type2string(type));
	
	ctx = g_hash_table_lookup(current_dynamic_rules, identifier);

	/* Not found, create new. */
	if (!ctx) {
		/* If no rules are set and tethering is disabled, return */
		if (!on)
			return;

		/*
		 * Eventually ifname is duplicated for each rule but bridge is
		 * defined as const in technology.c it is safer to dup the
		 * ifname and free it accordingly.
		 */
		ifname = g_strdup(__connman_tethering_get_bridge());

		/* Clone with specific types only */
		switch (type) {
		case CONNMAN_SERVICE_TYPE_WIFI:
			ctx = clone_firewall_context(tethering_firewall,
						ifname);
			break;
		default:
			break;
		}

		/* No match to type of tethering_firewall is not set */
		if (!ctx) {
			ctx = __connman_firewall_create();

			/* Allocation of ctx failed, disable tethering. */
			if (!ctx) {
				DBG("new firewall cannot be created");
				goto disable;
			}
		}

		/* If list is empty add default rules */
		if (!g_list_length(ctx->rules)) {
			/* Try to add default rules for tethering */
			if (add_default_tethering_rules(ctx, ifname)) {
				DBG("default tethering rules cannot be added.");
				goto disable;
			}
		}

		hash = g_strdup(identifier);

		/*
		 * Add a new into hash table, this condition should not be ever
		 * met. Left for debugging.
		 */
		if (!g_hash_table_replace(current_dynamic_rules, hash, ctx))
			DBG("hash table error, key %s exists", hash);
		else
			DBG("added new tethering firewall rules for %p %s %s",
						tech, identifier, ifname);
	} else {
		/*
		 * If tethering is on and firewall is enabled, return. 
		 * If tethering is off and firewall is disabled, return.
		 */
		if ((on && ctx->enabled) || (!on && !ctx->enabled)) {
			DBG("tethering firewall already %s for %s",
						on ? "enabled" : "disabled",
						identifier);
			return;
		}

		/*
		 * If there is a tethering firewall for this identifier it will
		 * have the rules set up properly. Just to make sure, update the
		 * used interface info.
		 */
		if (on) {
			ifname = g_strdup(__connman_tethering_get_bridge());

			/* Set interface information for each firewall rule */
			g_list_foreach(ctx->rules,
						setup_firewall_rule_interface,
						ifname);

			DBG("reused tethering firewall for %p %s %s",
						tech, identifier, ifname);
		}
	}

	if (on) {
		err = __connman_firewall_enable(ctx);

		if (err && err != -EALREADY) {
			DBG("cannot enable firewall, tethering disabled: "
						"error %d", err);
			goto disable;
		}
	} else {
		err = __connman_firewall_disable_rule(ctx, FW_ALL_RULES);

		if (err && err != -EALREADY)
			DBG("cannot disable firewall: error %d", err);
	}

	g_free(ifname);

	return;

disable:
	connman_error("tethering firewall error, tethering disabled");

	/* This generates notification */
	connman_technology_tethering_notify(tech, FALSE);
	g_free(ifname);
}

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
enum iptables_switch_type {
	IPTABLES_UNSET    = 0,
	IPTABLES_SWITCH   = 1,
	IPTABLES_MATCH    = 2,
	IPTABLES_TARGET   = 3,
	IPTABLES_PROTO    = 4,
	IPTABLES_PORT     = 5,
};

#define MAX_IPTABLES_SWITCH 6

static bool is_string_digits(const char *str)
{
	int i;

	if (!str || !*str)
		return false;

	for (i = 0; str[i]; i++) {
		if (!g_ascii_isdigit(str[i]))
			return false;
	}
	return true;
}

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
/* Protocols that iptables supports with -p or --protocol switch */
	const char *supported_protocols[] = { 	"tcp",
						"udp",
						"udplite",
						"icmp",
						"icmpv6",
						"ipv6-icmp",
						"esp",
						"ah",
						"sctp",
						"mh",
						"all",
						NULL
	};

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
static bool is_supported(int type, enum iptables_switch_type switch_type,
					const char* group, const char *str)
{
	/*
	 * The switches and matches that are not supported.
	 * 
	 * Chain manipulation is not supported, the rules are going to specific
	 * managed chains within connman.
	 *
	 * Setting specific addresses is not supported because the purpose of
	 * these rules is to set the base line of prevention to be used on both
	 * IPv4 and IPv6. In the future rules may be separated to have own for
	 * both of the IP protocols.
	 
	 * Setting specific interfaces is not supported for dynamic rules, these
	 * are added dynamically into the rules when interface comes up. For
	 * General rules setting interfaces is allowed.
	 */
	const char *not_supported_switches[] = { "--source", "--src","-s",
						"--destination", "--dst", "-d",
						"--append", "-A",
						"--delete", "-D",
						"--delete-chain", "-X",
						"--flush", "-F",
						"--insert", "-I",
						"--new-chain", "-N",
						"--policy", "-P",
						"--rename-chain", "-E",
						"--replace", "-R",
						"--zero", "-Z",
						"--to-destination",
						"--from-destination",
						NULL
	};
	const char *not_supported_dynamic_switches[] = { "--in-interface", "-i",
						"--out-interface", "-o",
						NULL
	};

	const char *not_supported_matches_ipv4[] = { "comment",
						"state",
1257 1258 1259
						"iprange",
						"recent",
						"owner",
1260 1261
						NULL
	};
1262 1263 1264 1265
	/*
	 * For yet unknown reason following work with IPv4 but not with IPv6:
	    -m conntrack
	 */
1266 1267
	const char *not_supported_matches_ipv6[] = { "comment",
						"state",
1268 1269 1270
						"iprange",
						"recent",
						"owner",
1271
						"conntrack",
1272
						"ttl",
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
						NULL
	};

	/*
	 * Targets that are supported. No targets to custom chains are
	 * allowed
	 */
	const char *supported_targets[] = { "ACCEPT",
						"DROP",
						"REJECT",
						"LOG",
						"QUEUE",
						NULL
	};

	struct protoent *p = NULL;
	bool is_general = false;
	int protonum = 0;
	int i = 0;

	/* Do not care about empty or nonexistent content */
	if (!str || !*str)
		return true;
	
	if (group && !g_strcmp0(group, GROUP_GENERAL))
		is_general = true;

	switch (switch_type) {
	case IPTABLES_SWITCH:
		for (i = 0; not_supported_switches[i]; i++) {
			if (!g_strcmp0(str, not_supported_switches[i]))
				return false;
		}

		/* If the rule is not in Group general */
		if (!is_general) {
			for (i = 0; not_supported_dynamic_switches[i]; i++) {
				if (!g_strcmp0(str,
					not_supported_dynamic_switches[i]))
					return false;
			} 
		}

		return true;
	case IPTABLES_MATCH:
		if (type == AF_INET) {
			for (i = 0 ; not_supported_matches_ipv4[i] ; i++) {
				if(!g_strcmp0(str,
						not_supported_matches_ipv4[i]))
					return false;
			}
		} else if (type == AF_INET6) {
			for (i = 0 ; not_supported_matches_ipv6[i] ; i++) {
				if(!g_strcmp0(str,
						not_supported_matches_ipv6[i]))
					return false;
			}
		} else {
			return false;
		}

		return true;
	case IPTABLES_TARGET:
		for (i = 0 ; supported_targets[i] ; i++) {
			if(!g_strcmp0(str, supported_targets[i]))
				return true;
		}

		return false;
	case IPTABLES_PROTO:
		if (is_string_digits(str))
			protonum = (int) g_ascii_strtoll(str, NULL, 10);

		for (i = 0; supported_protocols[i]; i++) {
			/* Protocols can be also capitalized */
			if (!g_ascii_strcasecmp(str, supported_protocols[i]))
				return true;

			/* Protocols can be defined by their number. */
			if (protonum) {
				p = getprotobyname(supported_protocols[i]);
				if (p && protonum == p->p_proto)
					return true;
			}
		}

		return false;
	default:
		return true;
	}
}

static bool is_port_switch(const char *str, bool multiport)
{
	const char *multiport_switches[] = { "--destination-ports", "--dports",
					"--source-ports", "--sports",
					"--port", "--ports",
					NULL
	};
	const char *port_switches[] = { "--destination-port", "--dport",
					"--source-port", "--sport",
					NULL
	};

	int i;

	if (!str || !*str)
		return true;

	if (multiport) {
		for (i = 0; multiport_switches[i]; i++) {
			if (!g_strcmp0(str, multiport_switches[i]))
				return true;
		}
	}

	/* Normal port switches can be used also with -m multiport */
	for (i = 0; port_switches[i]; i++) {
		if (!g_strcmp0(str, port_switches[i])) {
			return true;
		}
	}

	return false;
}

static bool validate_ports_or_services(const char *str)
{
	gchar **tokens;
	 /* In iptables ports are separated with commas, ranges with colon. */
	const char delimiters[] = ",:";
	struct servent *s;
	bool ret = true;
	int portnum;
	int i;

	if (!str || !*str)
		return false;

	tokens = g_strsplit_set(str, delimiters, 0);

	if (!tokens)
		return false;

	for (i = 0; tokens[i]; i++) {

		/* Plain digits, check if port is valid */
		if (is_string_digits(tokens[i])) {
			portnum = (int) g_ascii_strtoll(tokens[i], NULL, 10);

			/* Valid port number */
			if (portnum && portnum < G_MAXUINT16)
				continue;
		}

		/* Check if service name is valid with any protocol */
		s = getservbyname(tokens[i], NULL);

		if (s) {
			if (!g_strcmp0(tokens[i], s->s_name))
				continue;
		}

		/* If one of the ports/services is invalid, rule is invalid */
		ret = false;
		DBG("invalid port/service %s in %s", tokens[i], str);
		break;
	}

	g_strfreev(tokens);

	return ret;
}

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
static bool protocol_match_equals(const char *protocol, const char *match)
{
	struct protoent *p = NULL;
	int protonum;
	int i;

	if (!protocol || !match)
		return false;

	if (!g_ascii_strcasecmp(protocol, match))
		return true;

	/* If protocol is integer */
	if (is_string_digits(protocol)) {
		protonum = (int) g_ascii_strtoll(protocol, NULL, 10);

		if (!protonum)
			return false;

		p = getprotobynumber(protonum);
	} else {
		p = getprotobyname(protocol);
	}

	if (!p)
		return false;

	/* Protocol official name equals */
	if (!g_ascii_strcasecmp(p->p_name, match))
		return true;

	/* Check if it is one of the aliases */
	for (i = 0; p->p_aliases && p->p_aliases[i]; i++) {
		/* Protocols can be also capitalized */
		if (!g_ascii_strcasecmp(p->p_aliases[i], match))
			return true;
	}

	return false;
}

1488 1489 1490 1491 1492 1493 1494 1495
static bool validate_iptables_rule(int type, const char *group,
							const char *rule_spec)
{
	gchar **argv = NULL;
	GError *error = NULL;
	bool ret = false;
	int i = 0;
	int argc = 0;
1496 1497 1498
	int protocol_opt_index = 0;
	int protocol_match_index = 0;
	bool multiport_used = false;
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
	unsigned int switch_types_found[MAX_IPTABLES_SWITCH] = { 0 };
	enum iptables_switch_type switch_type = IPTABLES_UNSET;
	const char *match = NULL;
	const char valid_prefix = '-';

	if (!g_shell_parse_argv(rule_spec, &argc, &argv, &error)) {
		DBG("failed in parsing %s", error ? error->message : "");
		goto out;
	}

	/* -j TARGET is the bare minimum of a rule */
	if (argc < 2 || !argv[0][0]) {
		DBG("parsed content is invalid");
		goto out;
	}

	/* Only '-' prefixed rules are allowed in iptables. */
	if (argv[0][0] != valid_prefix) {
		DBG("invalid rule prefix");
		goto out;
	}

	for (i = 0; i < argc; ) {
		const char *arg = argv[i++];

		if (!is_supported(type, IPTABLES_SWITCH, group, arg)) {
			DBG("switch %s is not supported", arg);
			goto out;
		}

		if (!g_strcmp0(arg, "-m")) {
			switch_type = IPTABLES_MATCH;
			match = argv[i++];

			if (!match) {
				DBG("trailing '-m' in rule \"%s\"", rule_spec);
				goto out;
			}

			/* multiport match has to have valid port switches */
			if (!g_strcmp0(match, "multiport")) {
1540 1541 1542 1543 1544 1545 1546 1547 1548
				multiport_used = true;
				
				/* Cannot use -m multiport with -m protocol */
				if (protocol_match_index) {
					DBG("-m multiport with -m %s",
						argv[protocol_match_index]);
					goto out;
				}
				
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
				const char *opt = argv[i++];

				if (!opt) {
					DBG("empty %s %s switch", arg, match);
					goto out;
				}

				if (!is_port_switch(opt, true)) {
					DBG("non-supported %s %s switch %s",
						arg, match, opt);
					goto out;
				}

				const char *param = argv[i++];
				if (!param) {
					DBG("empty parameter with %s", opt);
					goto out;
				}

				/* Negated switch must be skipped */
				if (!g_strcmp0(param, "!"))
					param = argv[i++];

				if (!validate_ports_or_services(param)) {
					DBG("invalid ports %s %s", opt, param);
					goto out;
				}
			}
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
			
			/* If this is one of the supported protocols */
			if (is_supported(type, IPTABLES_PROTO, group, match)) {
				/*
				 * If no protocol is set before, protocol match
				 * cannot be used
				 */
				if (!switch_types_found[IPTABLES_PROTO]) {
					DBG("-m %s without -p protocol", match);
					goto out;
				}

				/* Check if match protocol equals */
				if (!protocol_match_equals(
						argv[protocol_opt_index],
						match)) {
					DBG("-p %s -m %s different protocol",
						argv[protocol_opt_index],
						match);
					goto out;
				}

				if (multiport_used) {
					DBG("-m multiport -m %s not supported",
							match);
					goto out;
				}

				/* Store the match index for multiport */
				protocol_match_index = i-1;
			}
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
		}

		if (!g_strcmp0(arg, "-j")) {
			switch_type = IPTABLES_TARGET;
			match = argv[i++];

			if (!match) {
				DBG("trailing '-j' in rule \"%s\"", rule_spec);
				goto out;
			}
		}

		if (!g_strcmp0(arg, "-p")) {
			switch_type = IPTABLES_PROTO;
			match = argv[i++];

			if (!match) {
				DBG("trailing '-p' in rule \"%s\"", rule_spec);
				goto out;
			}

			/* Negated switch must be skipped */
			if (!g_strcmp0(match, "!"))
				match = argv[i++];
1632 1633 1634
			
			/* Save the protocol index for -m switch check */
			protocol_opt_index = i-1;
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
		}

		if (is_port_switch(arg, false)) {
			switch_type = IPTABLES_PORT;
			match = argv[i++];

			if (!match) {
				DBG("trailing '%s' in rule \"%s\"", arg,
					rule_spec);
				goto out;
			}

			/* Negated switch must be skipped */
			if (!g_strcmp0(match, "!"))
				match = argv[i++];

			if (!validate_ports_or_services(match)) {
				DBG("invalid ports %s %s", arg, match);
				goto out;
			}
		}

		if (match && !is_supported(type, switch_type, group, match)) {
			DBG("%s %s is not supported", arg, match);
			goto out;
		}

		/* Record the current switch type */
		switch_types_found[switch_type]++;
		switch_type = IPTABLES_UNSET;
		match = NULL;
	}

	/* There can be 0...2 port switches in rule */
	if (switch_types_found[IPTABLES_PORT] > 2)
		goto out;

1672 1673
	/* There should be 0...2 matches in one rule */
	if (switch_types_found[IPTABLES_MATCH] > 2)
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
		goto out;

	/* There should be 0...1 protocols defined in rule */
	if (switch_types_found[IPTABLES_PROTO] > 1)
		goto out;

	/* There has to be exactly one target in rule */
	if (switch_types_found[IPTABLES_TARGET] != 1)
		goto out;

	ret = true;

out:
	g_clear_error(&error);

	return ret;
}

typedef int (*add_rules_cb_t)(int type, const char *group, int chain_id,
								char** rules);

static int add_dynamic_rules_cb(int type, const char *group, int chain_id,
								char** rules)
{
	enum connman_service_type service_type;
	char table[] = "filter";
	int count = 0;
	int err = 0;
	int id;
	int i; 

	if (!dynamic_rules || !rules)
		return 0;

	service_type = __connman_service_string2type(group);

	if (!dynamic_rules[service_type])
		dynamic_rules[service_type] = __connman_firewall_create();

	for(i = 0; rules[i] ; i++) {

		DBG("process rule tech %s chain %s rule %s", group,
					builtin_chains[chain_id], rules[i]);

		if (!validate_iptables_rule(type, group, rules[i])) {
			DBG("failed to add rule, rule is invalid");
			continue;
		}

		switch (type) {
		case AF_INET:
			id = __connman_firewall_add_rule(
						dynamic_rules[service_type],
						table, builtin_chains[chain_id],
						rules[i]);
			break;
		case AF_INET6:
			id = __connman_firewall_add_ipv6_rule(
						dynamic_rules[service_type],
						table, builtin_chains[chain_id],
						rules[i]);
			break;
		default:
			id = -1;
			DBG("invalid IP protocol %d", type);
			break;
		}

		if (id < 0) {
			DBG("failed to add rule to firewall");
			err = -EINVAL;
		} else {
			DBG("added with id %d", id);
			count++;
		}
	}

	if (!err)
		return count;

	return err;
}

static int add_general_rules_cb(int type, const char *group, int chain_id,
								char** rules)
{
	char table[] = "filter";
	int count = 0;
	int err = 0;
	int id;
	int i;

	if (!general_firewall)
		return -EINVAL;

1769 1770
	if (!general_firewall->ctx)
		general_firewall->ctx = __connman_firewall_create();
1771 1772 1773 1774 1775 1776 1777 1778

	if (!general_firewall->ctx)
		return -ENOMEM;

	if (!rules)
		return 0;

	for (i = 0; rules[i]; i++) {
1779 1780 1781 1782 1783 1784

		if (!g_utf8_validate(rules[i], -1, NULL)) {
			DBG("skipping rule, not valid UTF8");
			continue;
		}

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
		DBG("processing type %d group %s rule chain %s rule %s", type,
					GROUP_GENERAL, builtin_chains[chain_id],
					rules[i]);

		if (!validate_iptables_rule(type, group, rules[i])) {
			DBG("invalid general rule");
			continue;
		}

		switch (type) {
		case AF_INET:
			id = __connman_firewall_add_rule(general_firewall->ctx,
					table, builtin_chains[chain_id],
					rules[i]);
			break;
		case AF_INET6:
			id = __connman_firewall_add_ipv6_rule(
					general_firewall->ctx, table,
					builtin_chains[chain_id], rules[i]);
			break;
		default:
			id = -1;
			DBG("invalid IP protocol %d", type);
			break;
		}

		if (id < 0) {
			DBG("failed to add group %s chain_id %d rule %s",
					GROUP_GENERAL, chain_id, rules[i]);
			err = -EINVAL;
		} else {
			DBG("added with id %d", id);
			count++;
		}
	}

	if (!err)
		return count;

	return err;
}

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
static int add_tethering_rules_cb(int type, const char *group, int chain_id,
								char** rules)
{
	char table[] = "filter";
	int count = 0;
	int err = 0;
	int id;
	int i;

	if (!tethering_firewall)
		tethering_firewall = __connman_firewall_create();

	if (!tethering_firewall)
		return -ENOMEM;

	if (!rules)
		return 0;

	for (i = 0; rules[i]; i++) {

		if (!g_utf8_validate(rules[i], -1, NULL)) {
			DBG("skipping rule, not valid UTF8");
			continue;
		}

		DBG("processing type %d group %s rule chain %s rule %s", type,
					group, builtin_chains[chain_id],
					rules[i]);

		if (!validate_iptables_rule(type, group, rules[i])) {
			DBG("invalid general rule");
			continue;
		}

		switch (type) {
		case AF_INET:
			id = __connman_firewall_add_rule(tethering_firewall,
					table, builtin_chains[chain_id],
					rules[i]);
			break;
		case AF_INET6:
			id = __connman_firewall_add_ipv6_rule(
					tethering_firewall, table,
					builtin_chains[chain_id], rules[i]);
			break;
		default:
			id = -1;
			DBG("invalid IP protocol %d", type);
			break;
		}

		if (id < 0) {
			DBG("failed to add group %s chain_id %d rule %s",
					group, chain_id, rules[i]);
			err = -EINVAL;
		} else {
			DBG("added with id %d", id);
			count++;
		}
	}

	if (!err)
		return count;

	return err;
}

1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
static int add_rules_from_group(GKeyFile *config, const char *group,
							add_rules_cb_t cb)
{
	GError *error = NULL;
	char** rules;
	const char *chain_name = NULL;
	int types[3] = { AF_INET, AF_INET6, 0 };
	int chain;
	int count;
	int err = 0;
	int i;
	gsize len;

	DBG("");

	if (!group || !*group || !cb)
		return 0;

	for (chain = NF_IP_LOCAL_IN; chain < NF_IP_NUMHOOKS - 1; chain++) {
		for (i = 0; types[i] ; i++) {

			/* Setup chain name based on IP type */
			switch (types[i]) {
			case AF_INET:
				chain_name = supported_chains[chain];
				break;
			case AF_INET6:
				chain_name = supported_chainsv6[chain];
				break;
			default:
				chain_name = NULL;
			}

			if (!chain_name)
				continue;

			rules = __connman_config_get_string_list(config, group,
						chain_name, &len, &error);

			if (rules && len) {
				DBG("found %d rules in group %s chain %s", len,
							group, chain_name);

				count = cb(types[i], group, chain, rules);
			
				if (count < 0) {
					DBG("cannot add rules from config");
					err = -EINVAL;
				} else if (count < len) {
					DBG("%d invalid rules were detected,"
						"%d rules were added",
						len - count, count);
				} else {
					DBG("all %d rules were added", count);
				}
			} else if (rules && error) {
					/* A real error has happened */
					DBG("group %s chain %s error: %s",
							group, chain_name,
							error->message);
			} else {
				/*
				 * Error with rules set as NULL = no such key
				 * exists in the group specified.
				 */
				DBG("type %d no rules found for group %s "
							"chain %s", types[i],
							group, chain_name);
			}

			g_clear_error(&error);

			g_strfreev(rules);
		}
	}

	return err;
}

static bool check_config_key(const char* group, const char* key)
{
	bool is_general = false;
	int i;

	if (group && !g_strcmp0(group, GROUP_GENERAL))
		is_general = true;

	/*
	 * Allow only NF_IP_LOCAL_IN...NF_IP_LOCAL_OUT chains since filter
	 * table has no PRE/POST_ROUTING chains.
	 *
	 * The chain ids defined by netfilter are:
	 * NF_IP_PRE_ROUTING	0
	 * NF_IP_LOCAL_IN	1
	 * NF_IP_FORWARD	2
	 * NF_IP_LOCAL_OUT	3
	 * NF_IP_POST_ROUTING	4
	 * NF_IP_NUMHOOKS	5
	 */
	for (i = NF_IP_LOCAL_IN; i < NF_IP_NUMHOOKS - 1; i++) {
		if (!g_strcmp0(key, supported_chains[i]))  {
			DBG("match key %s chain %s", key, supported_chains[i]);
			return true;
		}

		if (!g_strcmp0(key, supported_chainsv6[i])) {
			DBG("match key %s chain %s", key,
						supported_chainsv6[i]);
			return true;
		}

		/* No other than General group should have policies set. */
		if (is_general) {
			if (!g_strcmp0(key, supported_policies[i])) {
				DBG("match key %s chain %s", key,
						supported_policies[i]);
				return true;
			}
			
			if (!g_strcmp0(key, supported_policiesv6[i])) {
				DBG("match key %s chain %s", key,
						supported_policiesv6[i]);
				return true;
			}
		}
	}

	DBG("no match for key %s", key);

	return false;
}

static bool check_config_group(const char *group)
{
	const char *type_str;
	enum connman_service_type type;
	
	if (!g_strcmp0(group, GROUP_GENERAL)) {
		DBG("match group %s", group);
		return true;
	}

	for (type = CONNMAN_SERVICE_TYPE_UNKNOWN;
				type < MAX_CONNMAN_SERVICE_TYPES; type++) {
			type_str = __connman_service_type2string(type);

			if (!type_str)
				continue;

			if (!g_strcmp0(group, type_str)) {
				DBG("match group %s type %s", group, type_str);
				return true;
			}
	}

2049 2050 2051 2052 2053
	if (!g_strcmp0(group, GROUP_TETHERING)) {
		DBG("match group %s", group);
		return true;
	}

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
	DBG("no match for group %s", group);

	return false;
}

static bool check_dynamic_rules(GKeyFile *config)
{
	enum connman_service_type type;
	char **keys;
	int i;
	bool ret = true;
	const char *group;

	if (!config)
		return false;

	keys = g_key_file_get_groups(config, NULL);

	/* Check that there are only valid service types */
	for (i = 0; keys && keys[i]; i++) {
		if (!check_config_group(keys[i])) {
			connman_warn("Unknown group %s in file %s",
						keys[i], FIREWALLFILE);
			ret = false;
		}
	}

	g_strfreev(keys);

	for (type = CONNMAN_SERVICE_TYPE_UNKNOWN;
			type < MAX_CONNMAN_SERVICE_TYPES; type++) {

		group = __connman_service_type2string(type);

		if (!group)
			continue;

		keys = g_key_file_get_keys(config, group, NULL, NULL);

		for (i = 0; keys && keys[i]; i++) {
			if (!check_config_key(group, keys[i])) {
2095 2096 2097
				connman_warn("Unknown group %s option %s in %s",
							group, keys[i],
							FIREWALLFILE);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
				ret = false;
			}
		}