firewall.c 65.4 KB
Newer Older
1 2 3 4
/*
 *
 *  Connection Manager
 *
5
 *  Copyright (C) 2013,2015  BMW Car IT GmbH.
6
 *  Copyright (C) 2018,2019  Jolla Ltd.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 *  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>
28
#include <netdb.h>
29 30 31

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

34 35
#include <gdbus.h>

36 37 38
#include "connman.h"

#define CHAIN_PREFIX "connman-"
39
#define FW_ALL_RULES -1
40

41 42 43 44
/*
 * All IPv6 equivalents of the indexes used here have the same values as the
 * IPv4 ones.
 */
45 46 47 48 49 50 51 52 53
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 {
54
	int family;
55 56 57 58 59
	char *name;
	unsigned int chains[NF_INET_NUMHOOKS];
};

struct fw_rule {
60
	int id;
61
	int family;
62
	bool enabled;
63 64 65
	char *table;
	char *chain;
	char *rule_spec;
66
	char *ifname;
67
	char *config_file;
68
	connman_iptables_manage_cb_t cb;
69 70 71 72
};

struct firewall_context {
	GList *rules;
73
	bool enabled;
74 75
};

76
static GSList *managed_tables = NULL;
77

78
static bool firewall_is_up;
79
static unsigned int firewall_rule_id;
80

81 82 83 84
#define FIREWALLFILE "firewall.conf"
#define FIREWALLCONFIGFILE CONFIGDIR "/" FIREWALLFILE
#define FIREWALLCONFIGDIR CONFIGDIR "/firewall.d/"
#define GROUP_GENERAL "General"
85
#define GROUP_TETHERING "tethering"
86 87
#define GENERAL_FIREWALL_POLICIES 3

88
/* TODO add all (tethering and dynamic) under this general firewall context */
89 90 91 92 93 94 95 96 97 98 99 100 101
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;

102 103 104
/* Tethering rules are a special case */
static struct firewall_context *tethering_firewall = NULL;

105 106 107
/* Configuration files that are read */
static GList *configuration_files = NULL;

108 109
static const char *supported_chains[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
110 111 112
	[NF_IP_LOCAL_IN]	= "IPv4.INPUT.RULES",
	[NF_IP_FORWARD]		= "IPv4.FORWARD.RULES",
	[NF_IP_LOCAL_OUT]	= "IPv4.OUTPUT.RULES",
113 114 115 116 117
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_chainsv6[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
118 119 120
	[NF_IP_LOCAL_IN]	= "IPv6.INPUT.RULES",
	[NF_IP_FORWARD]		= "IPv6.FORWARD.RULES",
	[NF_IP_LOCAL_OUT]	= "IPv6.OUTPUT.RULES",
121 122 123 124 125
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_policies[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
126 127 128
	[NF_IP_LOCAL_IN]	= "IPv4.INPUT.POLICY",
	[NF_IP_FORWARD]		= "IPv4.FORWARD.POLICY",
	[NF_IP_LOCAL_OUT]	= "IPv4.OUTPUT.POLICY",
129 130 131 132 133
	[NF_IP_POST_ROUTING]	= NULL,
};

static const char *supported_policiesv6[] = {
	[NF_IP_PRE_ROUTING]	= NULL,
134 135 136
	[NF_IP_LOCAL_IN]	= "IPv6.INPUT.POLICY",
	[NF_IP_FORWARD]		= "IPv6.FORWARD.POLICY",
	[NF_IP_LOCAL_OUT]	= "IPv6.OUTPUT.POLICY",
137 138 139 140 141 142 143
	[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.
 */
144
static GHashTable *current_dynamic_rules = NULL;
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
static int firewall_rule_compare(gconstpointer a, gconstpointer b)
{
	const struct fw_rule *rule_a;
	const struct fw_rule *rule_b;

	rule_a = a;
	rule_b = b;

	/*
	 * g_strcmp0 sorts NULLs before others, the system defined rules that
	 * are added by connman have no config_file and should be on top of
	 * other rules.
	 */
	return g_strcmp0(rule_a->config_file, rule_b->config_file);
}

162 163 164 165 166 167 168 169 170 171 172
static int firewall_rule_compare_reverse(gconstpointer a, gconstpointer b)
{
	/*
	 * This reverses the rule order for dynamic and tethering rules. These
	 * rules are inserted to iptables instead of appending so the last one
	 * to be inserted should not be on top. With reversed list the rule that
	 * is loaded as first rule from configs stays on top of iptables rules.
	 */
	return firewall_rule_compare(b, a);
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
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)
{
191
	if (!g_str_has_prefix(chain_name, CHAIN_PREFIX))
192 193 194 195 196
		return -1;

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

197
static int insert_managed_chain(int family, const char *table_name, int id)
198 199 200 201 202 203 204
{
	char *rule, *managed_chain;
	int err;

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

205
	err = __connman_iptables_new_chain(family, table_name, managed_chain);
206

207 208 209 210
	if (err < 0)
		goto out;

	rule = g_strdup_printf("-j %s", managed_chain);
211

212
	err = __connman_iptables_insert(family, table_name,
213 214
					builtin_chains[id], rule);

215 216
	g_free(rule);
	if (err < 0) {
217
		__connman_iptables_delete_chain(family, table_name,
218
						managed_chain);
219 220 221 222 223 224 225 226 227
		goto out;
	}

out:
	g_free(managed_chain);

	return err;
}

228
static int delete_managed_chain(int family, const char *table_name, int id)
229 230 231 232 233 234 235 236
{
	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);
237
	err = __connman_iptables_delete(family, table_name,
238
					builtin_chains[id], rule);
239 240 241 242 243
	g_free(rule);

	if (err < 0)
		goto out;

244
	err =  __connman_iptables_delete_chain(family, table_name,
245
					managed_chain);
246 247 248 249 250 251 252

out:
	g_free(managed_chain);

	return err;
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
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;
}

274
static int insert_managed_rule(connman_iptables_manage_cb_t cb,
275
				int family,
276
				const char *table_name,
277
				const char *chain_name,
278
				const char *ifname,
279 280 281 282
				const char *rule_spec)
{
	struct connman_managed_table *mtable = NULL;
	GSList *list;
283
	char *chain = NULL;
284
	char *full_rule = NULL;
285 286 287
	int id, err;

	id = chain_to_index(chain_name);
288 289 290

	full_rule = format_new_rule(id, ifname, rule_spec);

291 292 293 294 295 296
	if (id < 0) {
		/* This chain is not managed */
		chain = g_strdup(chain_name);
		goto out;
	}

297
	for (list = managed_tables; list; list = list->next) {
298 299
		mtable = list->data;

300
		if (g_strcmp0(mtable->name, table_name) == 0 &&
301
				mtable->family == family)
302 303 304 305 306
			break;

		mtable = NULL;
	}

307
	if (!mtable) {
308 309
		mtable = g_new0(struct connman_managed_table, 1);
		mtable->name = g_strdup(table_name);
310
		mtable->family = family;
311 312 313 314 315 316 317 318

		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);

319
		err = insert_managed_chain(family, table_name, id);
320
		if (err < 0)
321
			goto err;
322 323 324 325 326 327
	}

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

out:
328
	if (cb)
329
		err = cb(family, table_name, chain,
330 331
					full_rule ? full_rule : rule_spec);
	else
332
		err = __connman_iptables_append(family, table_name, chain,
333
					full_rule ? full_rule : rule_spec);
334 335

err:
336
	if (err < 0)
337 338
		DBG("table %s cannot append rule %s", table_name,
				full_rule ? full_rule : rule_spec);
339 340

	g_free(chain);
341
	g_free(full_rule);
342 343 344 345

	return err;
 }

346
static int delete_managed_rule(int family, const char *table_name,
347
				const char *chain_name,
348
				const char *ifname,
349 350 351 352 353
				const char *rule_spec)
 {
	struct connman_managed_table *mtable = NULL;
	GSList *list;
	int id, err;
354
	char *managed_chain = NULL;
355
	char *full_rule = NULL;
356 357

	id = chain_to_index(chain_name);
358 359 360

	full_rule = format_new_rule(id, ifname, rule_spec);

361 362
	if (id < 0) {
		/* This chain is not managed */
363
		err = __connman_iptables_delete(family, table_name,
364 365
					chain_name,
					full_rule ? full_rule : rule_spec);
366
		goto out;
367 368 369 370
	}

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

371
	err = __connman_iptables_delete(family, table_name, managed_chain,
372
				full_rule ? full_rule : rule_spec);
373 374 375
	
	if (err < 0)
		DBG("table %s managed rule %s was not removed from ip%stables",
376
			table_name, full_rule ? full_rule : rule_spec,
377
			family == AF_INET6 ? "6" : "");
378

379
	for (list = managed_tables; list; list = list->next) {
380 381
		mtable = list->data;

382
		if (g_strcmp0(mtable->name, table_name) == 0 &&
383
				mtable->family == family)
384 385 386 387 388
			break;

		mtable = NULL;
	}

389
	if (!mtable) {
390 391 392 393 394 395 396 397 398 399 400
		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);

401
	err = delete_managed_chain(family, table_name, id);
402

403
out:
404
	g_free(managed_chain);
405
	g_free(full_rule);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

	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;

422
	g_free(rule->ifname);
423 424 425
	g_free(rule->rule_spec);
	g_free(rule->chain);
	g_free(rule->table);
426
	g_free(rule->config_file);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
	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);
}

445 446 447 448 449 450 451
static int firewall_enable_rule(struct fw_rule *rule)
{
	int err;

	if (rule->enabled)
		return -EALREADY;

452
	DBG("%d %s %s %s %s", rule->family, rule->table, rule->chain,
453
					rule->ifname, rule->rule_spec);
454

455
	err = insert_managed_rule(rule->cb, rule->family, rule->table,
456 457
					rule->chain, rule->ifname,
					rule->rule_spec);
458 459
	if (err < 0) {
		DBG("cannot insert managed rule %d", err);
460
		goto err;
461
	}
462

463
	err = __connman_iptables_commit(rule->family, rule->table);
464

465 466
	if (err < 0) {
		DBG("iptables commit failed %d", err);
467
		goto err;
468
	}
469 470 471 472

	rule->enabled = true;

	return 0;
473 474

err:
475
	connman_warn("failed to add rule to iptables: id: %d IP family: %d "
476
				"table: %s chain: %s interface: %s rule: %s",
477
				rule->id, rule->family, rule->table, rule->chain,
478 479
				rule->ifname, rule->rule_spec);
	return err;
480 481 482 483 484 485 486 487 488
}

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

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

489
	err = delete_managed_rule(rule->family, rule->table, rule->chain,
490
					rule->ifname, rule->rule_spec);
491
	if (err < 0) {
492
		connman_error("pre-commit: Cannot remove previously installed "
493 494 495 496
			"iptables rules: %s", strerror(-err));
		return err;
	}

497
	err = __connman_iptables_commit(rule->family, rule->table);
498
	
499 500 501 502 503 504 505 506 507 508 509
	if (err < 0) {
		connman_error("Cannot remove previously installed "
			"iptables rules: %s", strerror(-err));
		return err;
	}

	rule->enabled = false;

	return 0;
}

510
static int firewall_add_rule(struct firewall_context *ctx,
511
				connman_iptables_manage_cb_t cb,
512
				const char *config_file,
513
				int family,
514 515
				const char *table,
				const char *chain,
516
				char *rule_spec)
517 518
{
	struct fw_rule *rule;
519
	GCompareFunc comparefunc;
520 521 522

	rule = g_new0(struct fw_rule, 1);

523
	rule->id = firewall_rule_id++;
524
	rule->family = family;
525
	rule->enabled = false;
526
	rule->cb = cb;
527

528 529 530 531 532
	if (!cb || cb == __connman_iptables_append)
		comparefunc = firewall_rule_compare;
	else
		comparefunc = firewall_rule_compare_reverse;

533 534 535
	if (config_file)
		rule->config_file = g_path_get_basename(config_file);

536 537 538 539
	rule->table = g_strdup(table);
	rule->chain = g_strdup(chain);
	rule->rule_spec = rule_spec;

540
	ctx->rules = g_list_insert_sorted(ctx->rules, rule, comparefunc);
541 542 543
	return rule->id;
}

544
int __connman_firewall_add_rule(struct firewall_context *ctx,
545
				connman_iptables_manage_cb_t cb,
546
				const char *config_file,
547 548 549 550 551 552 553 554 555 556 557 558 559
				const char *table,
				const char *chain,
				const char *rule_fmt, ...)
{
	va_list args;
	char *rule_spec;

	va_start(args, rule_fmt);

	rule_spec = g_strdup_vprintf(rule_fmt, args);

	va_end(args);

560 561 562
	return firewall_add_rule(ctx, cb, config_file, AF_INET, table, chain,
				rule_spec);
}
563

564 565 566 567 568 569 570 571 572
int __connman_firewall_add_ipv6_rule(struct firewall_context *ctx,
				connman_iptables_manage_cb_t cb,
				const char *config_file,
				const char *table,
				const char *chain,
				const char *rule_fmt, ...)
{
	va_list args;
	char *rule_spec;
573

574
	va_start(args, rule_fmt);
575

576
	rule_spec = g_strdup_vprintf(rule_fmt, args);
577

578 579 580 581
	va_end(args);

	return firewall_add_rule(ctx, cb, config_file, AF_INET6, table, chain,
				rule_spec);
582 583
}

584
int __connman_firewall_remove_rule(struct firewall_context *ctx, int id)
585 586 587
{
	struct fw_rule *rule;
	GList *list;
588
	int err = -ENOENT;
589

590 591 592
	list = g_list_last(ctx->rules);
	while (list) {
		GList *prev = g_list_previous(list);
593

594
		rule = list->data;
595 596 597 598 599 600 601
		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;
602
		}
603 604

		list = prev;
605
	}
606

607 608 609 610
	/* An empty list of rules is not an error if all rules are removed */
	if (id == FW_ALL_RULES && !g_list_length(ctx->rules))
		return 0;

611 612 613
	return err;
}

614 615 616 617 618 619
/* 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);
}

620 621 622 623
int __connman_firewall_enable_rule(struct firewall_context *ctx, int id)
{
	struct fw_rule *rule;
	GList *list;
624
	int e;
625
	int err = -ENOENT;
626
	int count = 0;
627
	int invalid = 0;
628 629 630 631 632

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

		if (rule->id == id || id == FW_ALL_RULES) {
633
			e = firewall_enable_rule(rule);
634

635
			/* Do not stop if enabling all rules */
636
			if (e == 0 && err == -ENOENT) {
637
				err = 0;
638
			} else if (e < 0) {
639
				err = e;
640 641
				invalid++;
			}
642 643 644

			if (id != FW_ALL_RULES)
				break;
645
		}
646 647 648 649

		count++;
	}

650 651 652
	/* Invalid rules are ignored, just report errors */
	if (id == FW_ALL_RULES) {
		DBG("firewall enabled, invalid rules: %d", invalid);
653
		ctx->enabled = true;
654 655
	}

656
	return err;
657 658
}

659
int __connman_firewall_disable_rule(struct firewall_context *ctx, int id)
660 661 662
{
	struct fw_rule *rule;
	GList *list;
663 664
	int e;
	int err = -ENOENT;
665

666 667
	for (list = g_list_last(ctx->rules); list;
			list = g_list_previous(list)) {
668 669
		rule = list->data;

670 671
		if (rule->id == id || id == FW_ALL_RULES) {
			e = firewall_disable_rule(rule);
672

673 674
			/* Report last error back */
			if (e == 0 && err == -ENOENT)
675 676 677
				err = 0;
			else if (e < 0)
				err = e;
678

679 680 681
			if (id != FW_ALL_RULES)
				break;
		}
682 683
	}

684 685
	/* An empty list of rules is not an error */
	if ((!err || !g_list_length(ctx->rules)) && id == FW_ALL_RULES) {
686 687 688 689
		DBG("firewall disabled");
		ctx->enabled = false;
	}

690 691
	return err;
}
692

693 694 695
int __connman_firewall_enable(struct firewall_context *ctx)
{
	int err;
696

697
	/* Invalid rules are ignored, just report that there were errors */
698
	err = __connman_firewall_enable_rule(ctx, FW_ALL_RULES);
699 700 701
	if (err < 0)
		connman_warn("Failed to install some of the iptables rules. "
					"Last error: %s", strerror(-err));
702

703
	firewall_is_up = true;
704

705
	return 0;
706 707 708 709
}

int __connman_firewall_disable(struct firewall_context *ctx)
{
710 711
	__connman_firewall_disable_rule(ctx, FW_ALL_RULES);
	return __connman_firewall_remove_rule(ctx, FW_ALL_RULES);
712 713
}

714 715 716 717 718
bool __connman_firewall_is_up(void)
{
	return firewall_is_up;
}

719 720 721 722 723 724 725 726 727 728 729 730
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));
}

731
static void flush_table(int family, const char *table_name)
732 733 734 735 736
{
	GSList *chains = NULL, *list;
	char *rule, *managed_chain;
	int id, err;

737
	err = __connman_iptables_iterate_chains(family, table_name,
738 739 740 741
					iterate_chains_cb, &chains);
	
	if (err < 0)
		DBG("table %s cannot iterate chains", table_name);
742

743
	for (list = chains; list; list = list->next) {
744 745 746 747 748 749
		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);
750
		
751
		err = __connman_iptables_delete(family, table_name,
752 753 754
						builtin_chains[id],
						rule);

755 756 757 758 759 760
		if (err < 0) {
			connman_warn("Failed to delete jump rule '%s': %s",
				rule, strerror(-err));
		}
		g_free(rule);

761
		err = __connman_iptables_flush_chain(family, table_name,
762 763
						managed_chain);
		
764 765 766 767
		if (err < 0) {
			connman_warn("Failed to flush chain '%s': %s",
				managed_chain, strerror(-err));
		}
768
		
769
		err = __connman_iptables_delete_chain(family, table_name,
770 771
						managed_chain);
		
772 773 774 775 776 777 778 779
		if (err < 0) {
			connman_warn("Failed to delete chain '%s': %s",
				managed_chain, strerror(-err));
		}

		g_free(managed_chain);
	}

780
	err = __connman_iptables_commit(family, table_name);
781 782 783 784 785 786 787 788
	if (err < 0) {
		connman_warn("Failed to flush table '%s': %s",
			table_name, strerror(-err));
	}

	g_slist_free(chains);
}

789 790 791
#define IP_TABLES_NAMES_FILE "/proc/net/ip_tables_names"
#define IP6_TABLES_NAMES_FILE "/proc/net/ip6_tables_names"

792
static void flush_all_tables(int family)
793
{
794 795 796 797 798 799 800 801
	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;

802
	switch (family) {
803 804 805 806 807 808 809 810 811
	case AF_INET:
		iptables_file = IP_TABLES_NAMES_FILE;
		break;
	case AF_INET6:
		iptables_file = IP6_TABLES_NAMES_FILE;
		break;
	default:
		return;
	}
812

813
	if (!g_file_test(iptables_file,
814 815 816 817 818 819
			G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR)) {
		firewall_is_up = false;
		return;
	}

	firewall_is_up = true;
820

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
	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])) {
839 840 841
				DBG("flush IP family %d table %s", family,
							tables[i]);
				flush_table(family, tables[i]);
842 843 844 845 846 847 848
			}
		}
	}

out:
	g_free(content);
	g_strfreev(tokens);
849 850
}

851 852 853 854 855 856 857 858 859 860 861
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;
}

862
static void setup_firewall_rule_interface(gpointer data, gpointer user_data)
863 864 865 866
{
	struct fw_rule *rule;
	char *ifname;

867
	rule = data;
868
	ifname = user_data;
869

870
	/* If rule is already enabled interface info is already set */
871
	if (!rule || !ifname || rule->enabled)
872
		return;
873

874 875 876 877
	if (rule->ifname && g_str_equal(rule->ifname, ifname)) {
		DBG("rule %d ifname %s not changed", rule->id, rule->ifname);
		return;
	}
878

879
	g_free(rule->ifname);
880
	rule->ifname = g_strdup(ifname);
881

882 883
	DBG("rule %d %s %s", rule->id, rule->ifname, rule->rule_spec);
}
884

885 886 887 888
static gpointer copy_fw_rule(gconstpointer src, gpointer data)
{
	const struct fw_rule *old;
	struct fw_rule *new;
889
	char *ifname;
890 891
	
	old = src;
892
	ifname = data;
893

894 895
	if (!old)
		return NULL;
896

897 898 899 900
	new = g_try_new0(struct fw_rule, 1);

	if (!new)
		return NULL;
901

902 903
	new->id = firewall_rule_id++;
	new->enabled = false;
904
	new->family = old->family;
905
	new->cb = old->cb;
906 907 908 909

	if (old->config_file)
		new->config_file = g_strdup(old->config_file);

910 911 912
	new->table = g_strdup(old->table);
	new->chain = g_strdup(old->chain);
	new->rule_spec = g_strdup(old->rule_spec);
913

914
	setup_firewall_rule_interface(new, ifname);
915 916

	return new;
917 918
}

919 920
static struct firewall_context *clone_firewall_context(
						struct firewall_context *ctx,
921
						char *ifname)
922
{
923 924
	struct firewall_context *clone;

925
	if (!ctx || !ifname)
926 927 928 929 930 931 932
		return NULL;
	
	clone = __connman_firewall_create();
	
	if (!clone)
		return NULL;
	
933
	clone->rules = g_list_copy_deep(ctx->rules, copy_fw_rule, ifname);
934 935 936 937 938 939 940
	
	return clone;
}

static int enable_dynamic_rules(struct connman_service *service)
{
	struct firewall_context *ctx;
941
	enum connman_service_type type;
942
	const char *identifier;
943
	char *ifname = NULL;
944
	char *hash;
945

946
	DBG("");
947

948 949
	/* This is not set if the configuration has not been loaded */
	if (!current_dynamic_rules)
950
		return 0;
951 952

	identifier = connman_service_get_identifier(service);
953

954 955 956 957 958 959 960 961 962 963
	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;

964 965
		ifname = connman_service_get_interface(service);

966
		/* Create a clone with interface info from service */
967
		ctx = clone_firewall_context(dynamic_rules[type], ifname);
968 969

		/* Allocation of ctx failed */
970 971
		if (!ctx) {
			g_free(ifname);
972
			return -ENOMEM;
973
		}
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

		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;

990 991
		ifname = connman_service_get_interface(service);

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

		DBG("reused firewall for service %p %s", service, identifier);
997 998
	}

999 1000
	g_free(ifname);

1001 1002
	return __connman_firewall_enable(ctx);
}
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
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);
1027 1028 1029 1030 1031 1032 1033 1034
}

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

	DBG("service %p %s type %d state %d", service,
1035 1036
				__connman_service_get_name(service),
				connman_service_get_type(service),
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
				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);
1048 1049 1050 1051 1052 1053 1054 1055

		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);

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		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);
	}
}

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
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);
}

1085 1086
static int add_default_accept_all_rules(struct firewall_context *ctx,
			char *ifname, bool both_directions)
1087 1088
{
	/* Add more in the future if needed */
1089
	const char *default_rules[] = { "-j ACCEPT", NULL };
1090
	connman_iptables_manage_cb_t cb = __connman_iptables_insert;
1091
	int err = 0;
1092 1093 1094 1095
	int id;
	int i;

	/* Add tethering rules for both IPv4 and IPv6 when using usb */
1096
	for (i = 0; default_rules[i]; i++) {
1097
		id = __connman_firewall_add_rule(ctx, cb, NULL, "filter",
1098 1099 1100 1101 1102
					"INPUT", default_rules[i]);
		if (id < 0) {
			DBG("cannot add IPv4 rule %s", default_rules[i]);
			err = -EINVAL;
		}
1103

1104
		id = __connman_firewall_add_ipv6_rule(ctx, cb, NULL, "filter",
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
					"INPUT", default_rules[i]);
		if (id < 0) {
			DBG("cannot add IPv6 rule %s", default_rules[i]);
			err = -EINVAL;
		}

		if (both_directions) {
			id = __connman_firewall_add_rule(ctx, cb, NULL,
						"filter", "OUTPUT",
						default_rules[i]);
			if (id < 0) {
				DBG("cannot add IPv4 rule %s",
							default_rules[i]);
				err = -EINVAL;
			}

			id = __connman_firewall_add_ipv6_rule(ctx, cb, NULL,
						"filter", "OUTPUT",
						default_rules[i]);
			if (id < 0) {
				DBG("cannot add IPv6 rule %s",
							default_rules[i]);
				err = -EINVAL;
			}
		}
1130 1131
	}

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

1134
	return err;
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 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
}

#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;
		}

1192
		/* No match to type, tethering_firewall is not set */
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
		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 */
1206
			if (add_default_accept_all_rules(ctx, ifname, false)) {
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
				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 {
		/*
1225
		 * If tethering is on and firewall is enabled, return.
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 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
		 * 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);
}

1280
static void device_status_changed(struct connman_device *device, bool on)
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
{
	struct firewall_context *ctx;
	char *ifname = NULL;
	int err = 0;

	if (!device) {
		DBG("no device");
		return;
	}

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
	/* Device is managed by connman */
	if (connman_device_get_managed(device)) {
		/*
		 * If there is a status change, this is a status change
		 * notification from a managed device, which can be ignored.
		 * Otherwise when the status has not changed and transition is
		 * from non-managed to managed this must be processed to remove
		 * the device index from the list in case device is off.
		 */
		if (connman_device_has_status_changed_to(device, on)) {
			DBG("ignoring managed status change notify");
			return;
		} else if (on) {
			DBG("ignoring managed false to true with status on");
			return;
		}
	} else if (!connman_device_has_status_changed_to(device, on)) {
		/*
		 * If non-managed device has no change, it is managed true to
		 * false notify, which can be ignored.
		 */
		DBG("ignoring managed status change to false notify");
		return;
	}

	if (connman_device_get_managed(device)) {
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
		DBG("ignoring managed device %p", device);
		return;
	}

	/* This is not set if the configuration has not been loaded */
	if (!current_dynamic_rules)
		return;

	/* It is safer to dup the interface name than to remove const */
	ifname = g_strdup(connman_device_get_string(device, "Interface"));

	if (!ifname) {
		DBG("no interface for device %p", device);
		return;
	}

1333
	DBG("device %s %s", ifname, on ? "up" : "down");
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

	ctx = g_hash_table_lookup(current_dynamic_rules, ifname);

	/* Not found, create new. */
	if (!ctx) {
		if (!on)
			goto out;

		ctx = __connman_firewall_create();

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

		/* Add default rules for device for both directions */
		err = add_default_accept_all_rules(ctx, ifname, true);
		if (err) {
			DBG("default device rules cannot be added.");
			goto out;
		}

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

		/*
		 * If there is a device firewall for this identifier it will
		 * have the rules set up properly. Just to make sure, update the
		 * used interface info.
		 */
		if (on) {
			/* Set interface information for each firewall rule */
			g_list_foreach(ctx->rules,
						setup_firewall_rule_interface,
						ifname);
			DBG("reused device firewall for %s", ifname);
		}
	}
	if (on)
		err = __connman_firewall_enable(ctx);
	else
		err = __connman_firewall_disable_rule(ctx, FW_ALL_RULES);

out:
	g_free(ifname);

	if (err)
		DBG("cannot make change, error: %s", strerror(-err));
}

1403
static bool is_rule_in_context(struct firewall_context *ctx, int family,
1404 1405 1406 1407 1408
			const char *table, const char *chain, const char *rule)
{
	GList *iter;
	struct fw_rule *list_rule;

1409
	for (iter = g_list_first(ctx->rules); iter; iter = iter->next) {
1410 1411 1412 1413 1414
		list_rule = iter->data;

		if (!list_rule)
			continue;

1415
		if (list_rule->family == family &&
1416 1417 1418 1419 1420 1421 1422 1423 1424
					!g_strcmp0(list_rule->table, table) &&
					!g_strcmp0(list_rule->chain, chain) &&
					!g_strcmp0(list_rule->rule_spec, rule))
			return true;
	}

	return false;
}

1425
static bool validate_iptables_rule(int family, const char *group,
1426 1427 1428 1429 1430 1431 1432
			const char *rule_spec)
{
	bool allow_dynamic = false;
	
	if (group && !g_strcmp0(group, GROUP_GENERAL))
		allow_dynamic = true;
	
1433
	return __connman_iptables_validate_rule(family, allow_dynamic, rule_spec);
1434 1435
}

1436
typedef int (*add_rules_cb_t)(int family, const char *filename, const char *group,
1437
						int chain_id, char** rules);
1438

1439
static int add_dynamic_rules_cb(int family, const char *filename,
1440
				const char *group, int chain_id, char** rules)
1441 1442
{
	enum connman_service_type service_type;
1443
	connman_iptables_manage_cb_t cb = __connman_iptables_insert;
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
	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();

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

1460 1461
		DBG("processing IP family %d rule tech %s chain %s rule %s",
					family, group, builtin_chains[chain_id],
1462
					rules[i]);
1463

1464
		if (!validate_iptables_rule(family, group, rules[i])) {
1465 1466 1467 1468
			DBG("failed to add rule, rule is invalid");
			continue;
		}

1469
		if (is_rule_in_context(dynamic_rules[service_type], family, table,
1470 1471 1472 1473 1474 1475 1476
						builtin_chains[chain_id],
						rules[i])) {
			DBG("ignoring rule %s in service type %d, rule exists",
						rules[i], service_type);
			continue;
		}

1477
		switch (family) {
1478 1479 1480
		case AF_INET:
			id = __connman_firewall_add_rule(
						dynamic_rules[service_type],
1481
						cb, filename, table,
1482
						builtin_chains[chain_id],
1483 1484 1485 1486 1487
						rules[i]);
			break;
		case AF_INET6:
			id = __connman_firewall_add_ipv6_rule(
						dynamic_rules[service_type],
1488
						cb, filename, table,
1489
						builtin_chains[chain_id],
1490 1491 1492 1493
						rules[i]);
			break;
		default:
			id = -1;
1494
			DBG("invalid IP protocol %d", family);
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
			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;
}

1513
static int add_general_rules_cb(int family, const char *filename,
1514
				const char *group, int chain_id, char** rules)
1515
{
1516
	connman_iptables_manage_cb_t cb = __connman_iptables_append;
1517 1518 1519 1520 1521 1522 1523 1524 1525
	char table[] = "filter";
	int count = 0;
	int err = 0;
	int id;
	int i;

	if (!general_firewall)
		return -EINVAL;

1526 1527
	if (!general_firewall->ctx)
		general_firewall->ctx = __connman_firewall_create();
1528 1529 1530 1531 1532 1533 1534 1535

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

	if (!rules)
		return 0;

	for (i = 0; rules[i]; i++) {
1536 1537 1538 1539 1540 1541

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

1542 1543 1544
		DBG("processing IP family %d group %s rule chain %s rule %s",
					family, GROUP_GENERAL,
					builtin_chains[chain_id], rules[i]);
1545

1546
		if (!validate_iptables_rule(family, group, rules[i])) {
1547 1548 1549 1550
			DBG("invalid general rule");
			continue;
		}

1551
		if (is_rule_in_context(general_firewall->ctx, family, table,
1552 1553 1554