Project

General

Profile

Download (16.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * easyrule.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2009-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2024 Rubicon Communications, LLC (Netgate)
9
 * Originally Sponsored By Anathematic @ pfSense Forums
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
$blockaliasname = 'EasyRuleBlockHosts';
26
$protocols_with_ports = array('tcp', 'udp');
27
require_once("functions.inc");
28
require_once("util.inc");
29
require_once("ipsec.inc");
30
require_once("config.inc");
31

    
32
function easyrule_find_rule_interface($int) {
33
	global $config;
34
	/* Borrowed from firewall_rules.php */
35
	$iflist = get_configured_interface_with_descr(true);
36

    
37
	/* Add interface groups */
38
	foreach (config_get_path('ifgroups/ifgroupentry', []) as $ifgen) {
39
		$iflist[$ifgen['ifname']] = $ifgen['ifname'];
40
	}
41

    
42
	if (is_pppoe_server_enabled()) {
43
		$iflist['pppoe'] = gettext("PPPoE Server");
44
	}
45

    
46
	if (config_get_path('l2tp/mode') == "server") {
47
		$iflist['l2tp'] = gettext("L2TP VPN");
48
	}
49

    
50
	/* Add IPsec tunnel interface */
51
	if (ipsec_enabled()) {
52
		$iflist["enc0"] = gettext("IPsec");
53
	}
54

    
55
	if (count(config_get_path('openvpn/openvpn-server', [])) ||
56
	    count(config_get_path('openvpn/openvpn-client', []))) {
57
		$iflist["openvpn"] = gettext("OpenVPN");
58
	}
59

    
60
	/* Check if the given name matches a known assigned interface id or
61
	 * common group name */
62
	if (array_key_exists($int, $iflist)) {
63
		return $int;
64
	}
65

    
66
	/* Check if the user passed an interface description name instead of the
67
	 * internal name. */
68
	foreach ($iflist as $if => $ifd) {
69
		if (strtolower($int) == strtolower($ifd)) {
70
			return $if;
71
		}
72
	}
73

    
74
	/* Check for unassigned OpenVPN or IPsec and return the associated
75
	 * group name. */
76
	if (substr($int, 0, 4) == "ovpn") {
77
		return "openvpn";
78
	}
79
	if (substr($int, 0, 5) == "ipsec") {
80
		return "ipsec";
81
	}
82

    
83
	/* If the user passed a real interface name, attempt to map it to an
84
	 * assigned interface */
85
	$iff = convert_real_interface_to_friendly_interface_name($int);
86
	if (($iff !== NULL) && ($iff != $int)) {
87
		return $iff;
88
	}
89

    
90
	return false;
91
}
92

    
93
function easyrule_block_rule_exists($int = 'wan', $ipproto = "inet") {
94
	global $blockaliasname, $config;
95
	/* No rules, we we know it doesn't exist */
96
	if (empty(config_get_path('filter/rule', []))) {
97
		return false;
98
	}
99

    
100
	/* Search through the rules for one referencing our alias */
101
	foreach (config_get_path('filter/rule', []) as $rule) {
102
		if (!is_array($rule) || !is_array($rule['source'])) {
103
			continue;
104
		}
105
		$checkproto = isset($rule['ipprotocol']) ? $rule['ipprotocol'] : "inet";
106
		if ((array_get_path($rule, 'source/address') == $blockaliasname . strtoupper($int)) &&
107
		    ($rule['interface'] == $int) &&
108
		    ($checkproto == $ipproto)) {
109
			return true;
110
		}
111
	}
112
	return false;
113
}
114

    
115
function easyrule_block_rule_create($int = 'wan', $ipproto = "inet") {
116
	global $blockaliasname;
117
	/* If the alias doesn't exist, exit.
118
	 * Can't create an empty alias, and we don't know a host */
119
	if (easyrule_block_alias_getid($int) === false) {
120
		return "noalias";
121
	}
122

    
123
	/* If the rule already exists, no need to do it again */
124
	if (easyrule_block_rule_exists($int, $ipproto)) {
125
		return true;
126
	}
127

    
128
	filter_rules_sort();
129
	$a_filter = config_get_path('filter/rule', []);
130

    
131
	/* Make up a new rule */
132
	$filterent = array();
133
	$filterent['type'] = 'block';
134
	$filterent['interface'] = $int;
135
	$filterent['ipprotocol'] = $ipproto;
136
	$filterent['source'] = [];
137
	$filterent['source']['address'] = $blockaliasname . strtoupper($int);
138
	$filterent['destination'] = [];
139
	$filterent['destination']['any'] = '';
140
	$filterent['descr'] = gettext("Blocked via EasyRule");
141
	$filterent['created'] = make_config_revision_entry(null, "EasyRule");
142
	$filterent['tracker'] = (int)microtime(true);
143

    
144
	// place the rule on top
145
	$ridx = get_interface_ruleindex($int);
146
	array_splice($a_filter, $ridx['first'], 0, array($filterent));
147
	config_set_path('filter/rule', $a_filter);
148

    
149
	// shift the separators
150
	$a_separators = config_get_path('filter/separator/' . strtolower($int), []);
151
	shift_separators($a_separators, -1);
152
	config_set_path('filter/separator/' . strtolower($int), $a_separators);
153

    
154
	return true;
155
}
156

    
157
function easyrule_block_alias_getid($int = 'wan') {
158
	global $blockaliasname;
159

    
160
	/* Hunt down an alias with the name we want, return its id */
161
	foreach (config_get_path('aliases/alias', []) as $aliasid => $alias) {
162
		if ($alias['name'] == $blockaliasname . strtoupper($int)) {
163
			return $aliasid;
164
		}
165
	}
166

    
167
	return false;
168
}
169

    
170
function easyrule_block_alias_add($host, $int = 'wan') {
171
	global $blockaliasname, $config;
172
	$easyrule_nettype_flags = [SPECIALNET_ANY, SPECIALNET_SELF, SPECIALNET_CLIENTS];
173
	/* If the host isn't a valid IP address, bail */
174
	$host = trim($host, "[]");
175
	if (!is_ipaddr($host) && !is_subnet($host)) {
176
		return "invalid";
177
	}
178

    
179
	$a_aliases = config_get_path('aliases/alias', []);
180

    
181
	/* Try to get the ID if the alias already exists */
182
	$id = easyrule_block_alias_getid($int);
183
	if ($id === false) {
184
		unset($id);
185
	}
186

    
187
	$alias = array();
188

    
189
	if (is_subnet($host)) {
190
		list($host, $mask) = explode("/", $host);
191
	} elseif (get_specialnet($host, $easyrule_nettype_flags)) {
192
		$mask = 0;
193
	} elseif (is_ipaddrv6($host)) {
194
		$mask = 128;
195
	} else {
196
		$mask = 32;
197
	}
198

    
199
	if (isset($id) &&
200
	    array_key_exists($id, $a_aliases) &&
201
	    is_array($a_aliases[$id])) {
202

    
203
		// Catch case when the list is empty
204
		if (empty(array_get_path($a_aliases, "{$id}/address", ""))) {
205
			$a_address = array();
206
			$a_detail = array();
207
		} else {
208
			$a_address = explode(" ", array_get_path($a_aliases, "{$id}/address", ""));
209

    
210
			/* Make sure this IP address isn't already in the list. */
211
			if (in_array($host.'/'.$mask, $a_address)) {
212
				return "exists";
213
			}
214
			$a_detail = explode("||", array_get_path($a_aliases, "{$id}/detail"));
215
		}
216

    
217
		/* Since the alias already exists, just add to it. */
218
		$alias['name']    = array_get_path($a_aliases, "{$id}/name");
219
		$alias['type']    = array_get_path($a_aliases, "{$id}/type");
220
		$alias['descr']   = array_get_path($a_aliases, "{$id}/descr");
221

    
222
		$a_address[] = $host.'/'.$mask;
223
		$a_detail[] = gettext('Entry added') . ' ' . date('r');
224

    
225
		$alias['address'] = join(" ", $a_address);
226
		$alias['detail']  = join("||", $a_detail);
227

    
228
	} else {
229
		/* Create a new alias with all the proper information */
230
		$alias['name']    = $blockaliasname . strtoupper($int);
231
		$alias['type']    = 'network';
232
		$alias['descr']   = gettext("Blocked via EasyRule");
233

    
234
		$alias['address'] = $host . '/' . $mask;
235
		$alias['detail']  = gettext('Entry added') . ' ' . date('r') . '||';
236
	}
237

    
238
	/* Replace the old alias if needed, otherwise tack it on the end */
239
	if (isset($id) && $a_aliases[$id]) {
240
		$a_aliases[$id] = $alias;
241
	} else {
242
		$a_aliases[] = $alias;
243
	}
244

    
245
	// Sort list
246
	$a_aliases = msort($a_aliases, "name");
247

    
248
	config_set_path('aliases/alias', $a_aliases);
249
	return true;
250
}
251

    
252
function easyrule_block_host_add($host, $int = 'wan') {
253
	global $retval;
254
	/* Bail if the supplied host is not a valid IP address */
255
	$host = trim($host, "[]");
256
	if (!is_ipaddr($host) && !is_subnet($host)) {
257
		return "invalid";
258
	}
259

    
260
	if (is_v6($host)) {
261
		$ipproto = 'inet6';
262
	} else {
263
		$ipproto = 'inet';
264
	}
265

    
266
	/* Flag whether or not we need to reload the filter */
267
	$dirty = false;
268

    
269
	/* Attempt to add this host to the alias */
270
	$alias_add_result = easyrule_block_alias_add($host, $int);
271
	if ($alias_add_result === true) {
272
		$dirty = true;
273
	} else {
274
		/* Couldn't add the alias, or adding the host failed. */
275
		return $alias_add_result;
276
	}
277

    
278
	/* Attempt to add the firewall rule if it doesn't exist.
279
	 * Failing to add the rule isn't necessarily an error, it may
280
	 * have been modified by the user in some way. Adding to the
281
	 * Alias is what's important.
282
	 */
283
	if (!easyrule_block_rule_exists($int, $ipproto)) {
284
		$rule_create_result = easyrule_block_rule_create($int, $ipproto);
285
		if ($rule_create_result === true) {
286
			$dirty = true;
287
		} else {
288
			return $rule_create_result;
289
		}
290
	}
291

    
292
	/* If needed, write the config and reload the filter */
293
	if ($dirty) {
294
		write_config(sprintf(gettext("Blocked %s via EasyRule"), $host));
295
		$retval = filter_configure();
296
		if (!empty($_SERVER['DOCUMENT_ROOT'])) {
297
			header("Location: firewall_aliases.php");
298
			exit;
299
		} else {
300
			return true;
301
		}
302
	} else {
303
		return false;
304
	}
305
}
306

    
307
function easyrule_pass_rule_add($int, $proto, $srchost, $dsthost, $dstport, $ipproto) {
308
	global $config;
309
	$easyrule_nettype_flags = [SPECIALNET_ANY, SPECIALNET_SELF, SPECIALNET_CLIENTS];
310

    
311
	init_config_arr(array('filter', 'rule'));
312
	filter_rules_sort();
313
	$a_filter = config_get_path('filter/rule', []);
314

    
315
	/* Make up a new rule */
316
	$filterent = array();
317
	$filterent['type'] = 'pass';
318
	$filterent['interface'] = $int;
319
	$filterent['ipprotocol'] = $ipproto;
320
	$filterent['descr'] = gettext("Passed via EasyRule");
321

    
322
	if ($proto != "any") {
323
		$filterent['protocol'] = $proto;
324
	} else {
325
		unset($filterent['protocol']);
326
	}
327

    
328
	if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6")) {
329
		$filterent['protocol'] = "icmp";
330
	}
331

    
332
	/* Default to only allow echo requests, since that's what most people want and
333
	 *  it should be a safe choice. */
334
	if ($proto == "icmp") {
335
		$filterent['icmptype'] = 'echoreq';
336
	}
337

    
338
	if (is_subnet($srchost)) {
339
		list($srchost, $srcmask) = explode("/", $srchost);
340
	} elseif (get_specialnet($srchost, $easyrule_nettype_flags)) {
341
		$srcmask = 0;
342
	} elseif (is_ipaddrv6($srchost)) {
343
		$srcmask = 128;
344
	} else {
345
		$srcmask = 32;
346
	}
347

    
348
	if (is_subnet($dsthost)) {
349
		list($dsthost, $dstmask) = explode("/", $dsthost);
350
	} elseif (get_specialnet($dsthost, $easyrule_nettype_flags)) {
351
		$dstmask = 0;
352
	} elseif (is_ipaddrv6($dsthost)) {
353
		$dstmask = 128;
354
	} else {
355
		$dstmask = 32;
356
	}
357

    
358
	pconfig_to_address($filterent['source'], $srchost, $srcmask, false, 0, 0, false, $easyrule_nettype_flags);
359
	pconfig_to_address($filterent['destination'], $dsthost, $dstmask, '', $dstport, $dstport, false, $easyrule_nettype_flags);
360

    
361
	$filterent['created'] = make_config_revision_entry(null, "EasyRule");
362
	$filterent['tracker'] = (int)microtime(true);
363
	$a_filter[] = $filterent;
364
	config_set_path('filter/rule', $a_filter);
365

    
366
	write_config($filterent['descr']);
367
	$retval = filter_configure();
368
	if (!empty($_SERVER['DOCUMENT_ROOT'])) {
369
		header("Location: firewall_rules.php?if={$int}");
370
		exit;
371
	} else {
372
		return true;
373
	}
374
}
375

    
376
function easyrule_parse_block($int, $src) {
377
	if (!empty($src) && !empty($int)) {
378
		$src = trim($src, "[]");
379
		if (!is_ipaddr($src) && !is_subnet($src)) {
380
			return gettext("Tried to block invalid address:") . ' ' . htmlspecialchars($src);
381
		}
382
		$int = easyrule_find_rule_interface($int);
383
		if ($int === false) {
384
			return gettext("Invalid interface for block rule.");
385
		}
386
		switch ((string)easyrule_block_host_add($src, $int)) {
387
			case "exists":
388
				return gettext("Block entry already exists.");
389
				break;
390
			case "invalid":
391
				return gettext("Invalid address.");
392
				break;
393
			case "1":
394
				return gettext("Block added successfully");
395
				break;
396
			case "":
397
			default:
398
				return gettext("Failed to create block rule, alias, or add entry.");
399
				break;
400
		}
401
	} else {
402
		return gettext("Tried to block but had no address or interface");
403
	}
404
	return gettext("Unknown block error.");
405
}
406

    
407
function easyrule_parse_unblock($int, $host) {
408
	global $blockaliasname, $config;
409
	$easyrule_nettype_flags = [SPECIALNET_ANY, SPECIALNET_SELF, SPECIALNET_CLIENTS];
410

    
411
	if (!empty($host) && !empty($int)) {
412
		$host = trim($host, "[]");
413
		if (!is_ipaddr($host) && !is_subnet($host)) {
414
			return gettext("Tried to unblock invalid address:") . ' ' . htmlspecialchars($host);
415
		}
416
		$real_int = easyrule_find_rule_interface($int);
417
		if ($real_int === false) {
418
			return gettext("Invalid interface for block rule:") . ' ' . htmlspecialchars($int);
419
		}
420

    
421
		/* Try to get the ID - will fail if there are no rules/alias on this interface */
422
		$id = easyrule_block_alias_getid($real_int);
423
		if ($id === false ||
424
		    empty(config_get_path("aliases/alias/{$id}", [])) ||
425
		    empty(config_get_path("aliases/alias/{$id}")['address'])) {
426
			return gettext("No entries are blocked on interface:") . ' ' . htmlspecialchars($int);
427
		}
428

    
429
		$alias = config_get_path("aliases/alias/{$id}", []);
430

    
431
		if (is_subnet($host)) {
432
			list($host, $mask) = explode("/", $host);
433
		} elseif (get_specialnet($host, $easyrule_nettype_flags)) {
434
			$mask = 0;
435
		} elseif (is_ipaddrv6($host)) {
436
			$mask = 128;
437
		} else {
438
			$mask = 32;
439
		}
440

    
441
		// Create the expected string representation
442
		$unblock = $host.'/'.$mask;
443

    
444
		$a_address = explode(" ", $alias['address']);
445
		$a_detail = explode("||", $alias['detail']);
446

    
447
		if (($key = array_search($unblock, $a_address)) !== false) {
448
			unset($a_address[$key]);
449
			unset($a_detail[$key]);
450
			// Write back the result to the config array
451
			$alias['address'] = join(" ", $a_address);
452
			$alias['detail'] = join("||", $a_detail);
453
			config_set_path("aliases/alias/{$id}", $alias);
454

    
455
			// Update config
456
			write_config(sprintf(gettext("Unblocked %s via EasyRule"), $host));
457
			$retval = filter_configure();
458
			if (!empty($_SERVER['DOCUMENT_ROOT'])) {
459
				header("Location: firewall_aliases.php");
460
				exit;
461
			} else {
462
				return gettext("Entry unblocked successfully");
463
			}
464
		} else {
465
			return gettext("Entry is not on block list: " . $host);
466
		}
467
	}
468

    
469
	return gettext("Tried to unblock but had no address or interface");
470

    
471
}
472

    
473
function easyrule_parse_getblock($int = 'wan', $sep = "\n") {
474
	global $blockaliasname, $config;
475

    
476
	$real_int = easyrule_find_rule_interface($int);
477
	if ($real_int === false) {
478
		return gettext("Invalid interface for block rule:") . ' ' . htmlspecialchars($int);
479
	}
480

    
481
	/* Try to get the ID - will fail if there are no rules/alias on this interface */
482
	$id = easyrule_block_alias_getid($real_int);
483

    
484
	if ($id === false ||
485
	    empty(config_get_path("aliases/alias/{$id}", [])) ||
486
	    empty(config_get_path("aliases/alias/{$id}")['address'])) {
487
		return gettext("No entries are blocked on interface:") . ' ' . htmlspecialchars($int);
488
	}
489
	return join($sep, explode(" ", config_get_path("aliases/alias/{$id}")['address']));
490
}
491

    
492
function easyrule_parse_pass($int, $proto, $src, $dst, $dstport = 0, $ipproto = "inet") {
493
	/* Check for valid int, srchost, dsthost, dstport, and proto */
494
	global $protocols_with_ports;
495
	$easyrule_nettype_flags = [SPECIALNET_ANY, SPECIALNET_SELF, SPECIALNET_CLIENTS];
496
	$src = trim($src, "[]");
497
	$dst = trim($dst, "[]");
498

    
499
	if (!empty($int) && !empty($proto) && !empty($src) && !empty($dst)) {
500
		$int = easyrule_find_rule_interface($int);
501
		if ($int === false) {
502
			return gettext("Invalid interface for pass rule:") . ' ' . htmlspecialchars($int);
503
		}
504
		if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6")) {
505
			$proto = "icmp";
506
		}
507
		if (($proto != 'any') &&
508
		    (getprotobyname($proto) === false) &&
509
		    (!is_numericint($proto) || (getprotobynumber($proto) === false))) {
510
			return gettext("Invalid protocol for pass rule:") . ' ' . htmlspecialchars($proto);
511
		}
512
		if (!is_ipaddr($src) && !is_subnet($src) && !is_ipaddroralias($src) && !get_specialnet($src, $easyrule_nettype_flags)) {
513
			return gettext("Tried to pass invalid source IP address:") . ' ' . htmlspecialchars($src);
514
		}
515
		if (!is_ipaddr($dst) && !is_subnet($dst) && !is_ipaddroralias($dst) && !get_specialnet($dst, $easyrule_nettype_flags)) {
516
			return gettext("Tried to pass invalid destination IP address:") . ' ' . htmlspecialchars($dst);
517
		}
518
		if ((is_v6($src) && is_v4($dst)) || (is_v4($src) && is_v6($dst))) {
519
			return gettext("The source IP address family has to match the family of the destination IP address.");
520
		}
521
		if (is_v6($src)) {
522
			$ipproto = 'inet6';
523
		} else {
524
			$ipproto = 'inet';
525
		}
526
		/* If the protocol is by number, change it to a name */
527
		if (($proto != 'any') &&
528
		    (getprotobyname($proto) === false)) {
529
			$proto = getprotobynumber($proto);
530
		}
531
		if (in_array($proto, $protocols_with_ports)) {
532
			if (empty($dstport)) {
533
				return gettext("Missing destination port.");
534
			}
535
			if (!is_port($dstport) && ($dstport != "any")) {
536
				return gettext("Tried to pass invalid destination port:") . ' ' . htmlspecialchars($dstport);
537
			}
538
		} else {
539
			$dstport = 0;
540
		}
541
		/* Should have valid input... */
542
		if (easyrule_pass_rule_add($int, $proto, $src, $dst, $dstport, $ipproto)) {
543
			return gettext("Successfully added pass rule!");
544
		} else {
545
			return gettext("Failed to add pass rule.");
546
		}
547
	} else {
548
		return gettext("Missing parameters for pass rule.");
549
	}
550
	return gettext("Unknown pass error.");
551
}
552

    
553
?>
(16-16/61)