Project

General

Profile

« Previous | Next » 

Revision bff96b22

Added by Steve Beaver almost 5 years ago

Moved controller logic out of display file and into .inc file

View differences:

src/etc/inc/alias.inc
1
<?php
2
/*
3
 * firewall_aliases.php
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2020 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally based on m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

  
28
require_once("config.gui.inc");
29
require_once("functions.inc");
30
require_once("filter.inc");
31
require_once("shaper.inc");
32

  
33
init_config_arr(array('aliases', 'alias'));
34
$a_aliases = &$config['aliases']['alias'];
35

  
36
function deleteAlias($id, $apply = false) {
37
	global $config;
38

  
39
	/* make sure rule is not being referenced by any nat or filter rules */
40
	init_config_arr(array('aliases', 'alias'));
41
	$a_aliases = &$config['aliases']['alias'];
42

  
43
	$delete_error = "";
44
	$is_alias_referenced = false;
45
	$referenced_by = false;
46
	$alias_name = $a_aliases[$id]['name'];
47
	// Firewall rules
48
	find_alias_reference(array('filter', 'rule'), array('source', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
49
	find_alias_reference(array('filter', 'rule'), array('destination', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
50
	find_alias_reference(array('filter', 'rule'), array('source', 'port'), $alias_name, $is_alias_referenced, $referenced_by);
51
	find_alias_reference(array('filter', 'rule'), array('destination', 'port'), $alias_name, $is_alias_referenced, $referenced_by);
52
	// NAT Rules
53
	find_alias_reference(array('nat', 'rule'), array('source', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
54
	find_alias_reference(array('nat', 'rule'), array('source', 'port'), $alias_name, $is_alias_referenced, $referenced_by);
55
	find_alias_reference(array('nat', 'rule'), array('destination', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
56
	find_alias_reference(array('nat', 'rule'), array('destination', 'port'), $alias_name, $is_alias_referenced, $referenced_by);
57
	find_alias_reference(array('nat', 'rule'), array('target'), $alias_name, $is_alias_referenced, $referenced_by);
58
	find_alias_reference(array('nat', 'rule'), array('local-port'), $alias_name, $is_alias_referenced, $referenced_by);
59
	// NAT 1:1 Rules
60
	//find_alias_reference(array('nat', 'onetoone'), array('external'), $alias_name, $is_alias_referenced, $referenced_by);
61
	//find_alias_reference(array('nat', 'onetoone'), array('source', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
62
	find_alias_reference(array('nat', 'onetoone'), array('destination', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
63
	// NAT Outbound Rules
64
	find_alias_reference(array('nat', 'outbound', 'rule'), array('source', 'network'), $alias_name, $is_alias_referenced, $referenced_by);
65
	find_alias_reference(array('nat', 'outbound', 'rule'), array('sourceport'), $alias_name, $is_alias_referenced, $referenced_by);
66
	find_alias_reference(array('nat', 'outbound', 'rule'), array('destination', 'address'), $alias_name, $is_alias_referenced, $referenced_by);
67
	find_alias_reference(array('nat', 'outbound', 'rule'), array('dstport'), $alias_name, $is_alias_referenced, $referenced_by);
68
	find_alias_reference(array('nat', 'outbound', 'rule'), array('target'), $alias_name, $is_alias_referenced, $referenced_by);
69
	// Alias in an alias
70
	find_alias_reference(array('aliases', 'alias'), array('address'), $alias_name, $is_alias_referenced, $referenced_by);
71
	// Static routes
72
	find_alias_reference(array('staticroutes', 'route'), array('network'), $alias_name, $is_alias_referenced, $referenced_by);
73
	if ($is_alias_referenced == true) {
74
		$delete_error = sprintf(gettext("Cannot delete alias. Currently in use by %s."), htmlspecialchars($referenced_by));
75
	} else {
76
		if (preg_match("/urltable/i", $a_aliases[$id]['type'])) {
77
			// this is a URL table type alias, delete its file as well
78
			unlink_if_exists("/var/db/aliastables/" . $a_aliases[$id]['name'] . ".txt");
79
		}
80
		unset($a_aliases[$id]);
81
		if (write_config(gettext("Deleted firewall alias " . $a_aliases[$id]['name']))) {
82
			filter_configure();
83

  
84
			if (!$apply) {
85
				mark_subsystem_dirty('aliases');
86
			} 
87
		}
88
	}
89

  
90
	return $delete_error;
91
}
92

  
93
function find_alias_reference($section, $field, $origname, &$is_alias_referenced, &$referenced_by) {
94
	global $config;
95
	if (!$origname || $is_alias_referenced) {
96
		return;
97
	}
98

  
99
	$sectionref = &$config;
100
	foreach ($section as $sectionname) {
101
		if (is_array($sectionref) && isset($sectionref[$sectionname])) {
102
			$sectionref = &$sectionref[$sectionname];
103
		} else {
104
			return;
105
		}
106
	}
107

  
108
	if (is_array($sectionref)) {
109
		foreach ($sectionref as $itemkey => $item) {
110
			$fieldfound = true;
111
			$fieldref = &$sectionref[$itemkey];
112
			foreach ($field as $fieldname) {
113
				if (is_array($fieldref) && isset($fieldref[$fieldname])) {
114
					$fieldref = &$fieldref[$fieldname];
115
				} else {
116
					$fieldfound = false;
117
					break;
118
				}
119
			}
120
			if ($fieldfound && $fieldref == $origname) {
121
				$is_alias_referenced = true;
122
				if (is_array($item)) {
123
					$referenced_by = $item['descr'];
124
				}
125
				break;
126
			}
127
		}
128
	}
129
}
130

  
131
function alias_same_type($name, $type) {
132
	global $config;
133

  
134
	foreach ($config['aliases']['alias'] as $alias) {
135
		if ($name == $alias['name']) {
136
			if (in_array($type, array("host", "network")) &&
137
			    in_array($alias['type'], array("host", "network"))) {
138
				return true;
139
			}
140

  
141
			if ($type == $alias['type']) {
142
				return true;
143
			} else {
144
				return false;
145
			}
146
		}
147
	}
148
	return true;
149
}
150

  
151
function saveAlias($post, $id) {
152
	global $config, $pf_reserved_keywords, $reserved_table_names;
153

  
154
	$reserved_ifs = get_configured_interface_list(true);
155
	$pf_reserved_keywords = array_merge($pf_reserved_keywords, $reserved_ifs, $reserved_table_names);
156
	$max_alias_addresses = 5000;
157

  
158
	init_config_arr(array('aliases', 'alias'));
159
	$a_aliases = &$config['aliases']['alias'];
160

  
161
	$data_errors = array();
162

  
163
	$vertical_bar_err_text = gettext("Vertical bars (|) at start or end, or double in the middle of descriptions not allowed. Descriptions have been cleaned. Check and save again.");
164

  
165
	/* input validation */
166

  
167
	$reqdfields = explode(" ", "name");
168
	$reqdfieldsn = array(gettext("Name"));
169

  
170
	do_local_input_validation($post, $reqdfields, $reqdfieldsn, $data_errors);
171

  
172
	if (!is_validaliasname($post['name'])) {
173
		$data_errors[] = invalidaliasnamemsg($post['name']);
174
	}
175

  
176
	/* check for name conflicts */
177
	foreach ($a_aliases as $key => $alias) {
178
		if (($alias['name'] == $post['name']) && (empty($a_aliases[$id]) || ($key != $id))) {
179
			$data_errors[] = gettext("An alias with this name already exists.");
180
			break;
181
		}
182
	}
183

  
184
	/* Check for reserved keyword names */
185
	foreach ($pf_reserved_keywords as $rk) {
186
		if (strcasecmp($rk, $post['name']) == 0) {
187
			$data_errors[] = sprintf(gettext("Cannot use a reserved keyword as an alias name: %s"), $rk);
188
		}
189
	}
190

  
191
	/*
192
	 * Packages (e.g. tinc) create interface groups, reserve this
193
	 * namespace pkg_ for them.
194
	 * One namespace is shared by Interfaces, Interface Groups and Aliases.
195
	 */
196
	if (substr($post['name'], 0, 4) == 'pkg_') {
197
		$data_errors[] = gettext("The alias name cannot start with pkg_");
198
	}
199

  
200
	/* check for name interface description conflicts */
201
	foreach ($config['interfaces'] as $interface) {
202
		if (strcasecmp($interface['descr'], $post['name']) == 0) {
203
			$data_errors[] = gettext("An interface description with this name already exists.");
204
			break;
205
		}
206
	}
207

  
208
	/* Is the description already used as an interface group name? */
209
	if (is_array($config['ifgroups']['ifgroupentry'])) {
210
		foreach ($config['ifgroups']['ifgroupentry'] as $ifgroupentry) {
211
			if ($ifgroupentry['ifname'] == $post['name']) {
212
				$data_errors[] = gettext("Sorry, an interface group with this name already exists.");
213
			}
214
		}
215
	}
216

  
217
	/* To prevent infinite loops make sure the alias name does not equal the value. */
218
	for($i = 0; isset($post['address' . $i]); $i++) {
219
			if($post['address' . $i] == $post['name']){
220
				$data_errors[] = gettext("Alias value cannot be the same as the alias name: `" . $post['name'] . " and " . $post['address' . $i] . "`");
221
			}
222
	}
223

  
224
	$alias = array();
225
	$address = array();
226
	$final_address_details = array();
227
	$alias['name'] = $post['name'];
228
	$alias['type'] = $post['type'];
229

  
230
	if (preg_match("/urltable/i", $post['type'])) {
231
		$address = array();
232

  
233
		/* item is a url table type */
234
		if ($post['address0']) {
235
			/* fetch down and add in */
236
			$post['address0'] = trim(idn_to_ascii($post['address0']));
237
			$address[] = $post['address0'];
238
			$alias['url'] = $post['address0'];
239
			$alias['updatefreq'] = $post['address_subnet0'] ? $post['address_subnet0'] : 7;
240
			if (!is_URL($alias['url']) || empty($alias['url'])) {
241
				$data_errors[] = gettext("A valid URL must be provided.");
242
			} elseif (!process_alias_urltable($alias['name'], $alias['type'], $alias['url'], 0, true, true)) {
243
				$data_errors[] = sprintf(gettext("Unable to fetch usable data from URL %s"), htmlspecialchars($alias['url']));
244
			}
245
			if ($post["detail0"] <> "") {
246
				if ((strpos($post["detail0"], "||") === false) && (substr($post["detail0"], 0, 1) != "|") && (substr($post["detail0"], -1, 1) != "|")) {
247
					$final_address_details[] = $post["detail0"];
248
				} else {
249
					/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
250
					/* and put in the output array so the text is at least redisplayed for the user. */
251
					$final_address_details[] = preg_replace('/\|\|+/', '|', trim($post["detail0"], "|"));
252
					$data_errors[] = $vertical_bar_err_text;
253
				}
254
			} else {
255
				$final_address_details[] = sprintf(gettext("Entry added %s"), date('r'));
256
			}
257
		}
258
	} elseif (($post['type'] == "url") || ($post['type'] == "url_ports")) {
259
		$desc_fmt_err_found = false;
260

  
261
		/* item is a url type */
262
		for ($x = 0; $x < $max_alias_addresses - 1; $x++) {
263
			$post['address' . $x] = trim(idn_to_ascii($post['address' . $x]));
264
			if ($post['address' . $x]) {
265
				/* fetch down and add in */
266
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
267
				unlink_if_exists($temp_filename);
268
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
269
				mkdir($temp_filename);
270
				if (!download_file($post['address' . $x], $temp_filename . "/aliases", $verify_ssl)) {
271
					$data_errors[] = sprintf(gettext("Could not fetch the URL '%s'."), $post['address' . $x]);
272
					continue;
273
				}
274

  
275
				/* if the item is tar gzipped then extract */
276
				if (stristr($post['address' . $x], ".tgz")) {
277
					process_alias_tgz($temp_filename);
278
				}
279

  
280
				if (!isset($alias['aliasurl'])) {
281
					$alias['aliasurl'] = array();
282
				}
283

  
284
				$alias['aliasurl'][] = $post['address' . $x];
285
				if ($post["detail{$x}"] <> "") {
286
					if ((strpos($post["detail{$x}"], "||") === false) && (substr($post["detail{$x}"], 0, 1) != "|") && (substr($post["detail{$x}"], -1, 1) != "|")) {
287
						$final_address_details[] = $post["detail{$x}"];
288
					} else {
289
						/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
290
						/* and put in the output array so the text is at least redisplayed for the user. */
291
						$final_address_details[] = preg_replace('/\|\|+/', '|', trim($post["detail{$x}"], "|"));
292
						if (!$desc_fmt_err_found) {
293
							$data_errors[] = $vertical_bar_err_text;
294
							$desc_fmt_err_found = true;
295
						}
296
					}
297
				} else {
298
					$final_address_details[] = sprintf(gettext("Entry added %s"), date('r'));
299
				}
300

  
301
				if (file_exists("{$temp_filename}/aliases")) {
302
					$t_address = parse_aliases_file("{$temp_filename}/aliases", $post['type'], 5000);
303
					if ($t_address == null) {
304
						/* nothing was found */
305
						$data_errors[] = sprintf(gettext("A valid URL must be provided. Could not fetch usable data from '%s'."), $post['address' . $x]);
306
					} else {
307
						array_push($address, ...$t_address);
308
					}
309
					unset($t_address);
310
					mwexec("/bin/rm -rf " . escapeshellarg($temp_filename));
311
				} else {
312
					$data_errors[] = sprintf(gettext("URL '%s' is not valid."), $post['address' . $x]);
313
				}
314
			}
315
		}
316
		unset($desc_fmt_err_found);
317
		if ($post['type'] == "url_ports") {
318
			$address = group_ports($address);
319
		}
320
	} else {
321
		/* item is a normal alias type */
322
		$wrongaliases = "";
323
		$desc_fmt_err_found = false;
324
		$alias_address_count = 0;
325
		$input_addresses = array();
326

  
327
		// First trim and expand the input data.
328
		// Users can paste strings like "10.1.2.0/24 10.3.0.0/16 9.10.11.0/24" into an address box.
329
		// They can also put an IP range.
330
		// This loop expands out that stuff so it can easily be validated.
331
		for ($x = 0; $x < ($max_alias_addresses - 1); $x++) {
332
			if ($post["address{$x}"] <> "") {
333
				if ($post["detail{$x}"] <> "") {
334
					if ((strpos($post["detail{$x}"], "||") === false) && (substr($post["detail{$x}"], 0, 1) != "|") && (substr($post["detail{$x}"], -1, 1) != "|")) {
335
						$detail_text = $post["detail{$x}"];
336
					} else {
337
						/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
338
						/* and put in the output array so the text is at least redisplayed for the user. */
339
						$detail_text = preg_replace('/\|\|+/', '|', trim($post["detail{$x}"], "|"));
340
						if (!$desc_fmt_err_found) {
341
							$data_errors[] = $vertical_bar_err_text;
342
							$desc_fmt_err_found = true;
343
						}
344
					}
345
				} else {
346
					$detail_text = sprintf(gettext("Entry added %s"), date('r'));
347
				}
348

  
349
				$address_items = explode(" ", trim(idn_to_ascii($post["address{$x}"])));
350
				foreach ($address_items as $address_item) {
351
					$iprange_type = is_iprange($address_item);
352
					if ($iprange_type == 4) {
353
						list($startip, $endip) = explode('-', $address_item);
354
						if ($post['type'] == "network") {
355
							// For network type aliases, expand an IPv4 range into an array of subnets.
356
							$rangesubnets = ip_range_to_subnet_array($startip, $endip);
357
							foreach ($rangesubnets as $rangesubnet) {
358
								if ($alias_address_count > $max_alias_addresses) {
359
									break;
360
								}
361
								list($address_part, $subnet_part) = explode("/", $rangesubnet);
362
								$input_addresses[] = $address_part;
363
								$input_address_subnet[] = $subnet_part;
364
								$final_address_details[] = $detail_text;
365
								$alias_address_count++;
366
							}
367
						} else {
368
							// For host type aliases, expand an IPv4 range into a list of individual IPv4 addresses.
369
							$rangeaddresses = ip_range_to_address_array($startip, $endip, $max_alias_addresses - $alias_address_count);
370
							if (is_array($rangeaddresses)) {
371
								foreach ($rangeaddresses as $rangeaddress) {
372
									$input_addresses[] = $rangeaddress;
373
									$input_address_subnet[] = "";
374
									$final_address_details[] = $detail_text;
375
									$alias_address_count++;
376
								}
377
							} else {
378
								$data_errors[] = sprintf(gettext('Range is too large to expand into individual host IP addresses (%s)'), $address_item);
379
								$data_errors[] = sprintf(gettext('The maximum number of entries in an alias is %s'), $max_alias_addresses);
380
								// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
381
								$input_addresses[] = $address_item;
382
								$input_address_subnet[] = "";
383
								$final_address_details[] = $detail_text;
384
							}
385
						}
386
					} else if ($iprange_type == 6) {
387
						$data_errors[] = sprintf(gettext('IPv6 address ranges are not supported (%s)'), $address_item);
388
						// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
389
						$input_addresses[] = $address_item;
390
						$input_address_subnet[] = "";
391
						$final_address_details[] = $detail_text;
392
					} else {
393
						$subnet_type = is_subnet($address_item);
394
						if (($post['type'] == "host") && $subnet_type) {
395
							if ($subnet_type == 4) {
396
								// For host type aliases, if the user enters an IPv4 subnet, expand it into a list of individual IPv4 addresses.
397
								$subnet_size = subnet_size($address_item);
398
								if ($subnet_size > 0 &&
399
								    $subnet_size <= ($max_alias_addresses - $alias_address_count)) {
400
									$rangeaddresses = subnetv4_expand($address_item);
401
									foreach ($rangeaddresses as $rangeaddress) {
402
										$input_addresses[] = $rangeaddress;
403
										$input_address_subnet[] = "";
404
										$final_address_details[] = $detail_text;
405
										$alias_address_count++;
406
									}
407
								} else {
408
									$data_errors[] = sprintf(gettext('Subnet is too large to expand into individual host IP addresses (%s)'), $address_item);
409
									$data_errors[] = sprintf(gettext('The maximum number of entries in an alias is %s'), $max_alias_addresses);
410
									// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
411
									$input_addresses[] = $address_item;
412
									$input_address_subnet[] = "";
413
									$final_address_details[] = $detail_text;
414
								}
415
							} else {
416
								$data_errors[] = sprintf(gettext('IPv6 subnets are not supported in host aliases (%s)'), $address_item);
417
								// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
418
								$input_addresses[] = $address_item;
419
								$input_address_subnet[] = "";
420
								$final_address_details[] = $detail_text;
421
							}
422
						} else {
423
							list($address_part, $subnet_part) = explode("/", $address_item);
424
							if (!empty($subnet_part)) {
425
								if (is_subnet($address_item)) {
426
									$input_addresses[] = $address_part;
427
									$input_address_subnet[] = $subnet_part;
428
								} else {
429
									// The user typed something like "1.2.3.444/24" or "1.2.3.0/36" or similar rubbish.
430
									// Feed it through without splitting it apart, then it will be caught by the validation loop below.
431
									$input_addresses[] = $address_item;
432
									$input_address_subnet[] = "";
433
								}
434
							} else {
435
								$input_addresses[] = $address_part;
436
								$input_address_subnet[] = $post["address_subnet{$x}"];
437
							}
438
							$final_address_details[] = $detail_text;
439
							$alias_address_count++;
440
						}
441
					}
442
					if ($alias_address_count > $max_alias_addresses) {
443
						$data_errors[] = sprintf(gettext('The maximum number of entries in an alias has been exceeded (%s)'), $max_alias_addresses);
444
						break;
445
					}
446
				}
447
			}
448
		}
449

  
450
		// Validate the input data expanded above.
451
		foreach ($input_addresses as $idx => $input_address) {
452
			if (is_alias($input_address)) {
453
				if (!alias_same_type($input_address, $post['type'])) {
454
					// But alias type network can include alias type urltable. Feature#1603.
455
					if (!($post['type'] == 'network' &&
456
					    preg_match("/urltable/i", alias_get_type($input_address)))) {
457
						$wrongaliases .= " " . $input_address;
458
					}
459
				}
460
			} else if ($post['type'] == "port") {
461
				if (!is_port_or_range($input_address)) {
462
					$data_errors[] = sprintf(gettext("%s is not a valid port or alias."), $input_address);
463
				}
464
			} else if (($post['type'] == "host") || ($post['type'] == "network")) {
465
				if (is_subnet($input_address) ||
466
				    (!is_ipaddr($input_address) && !is_hostname($input_address))) {
467
					$data_errors[] = sprintf(gettext('%1$s is not a valid %2$s address, FQDN or alias.'), $input_address, $singular_types[$post['type']]);
468
				}
469
			}
470
			$tmpaddress = $input_address;
471
			if (($post['type'] != "host") && is_ipaddr($input_address) && ($input_address_subnet[$idx] <> "")) {
472
				if (!is_subnet($input_address . "/" . $input_address_subnet[$idx])) {
473
					$data_errors[] = sprintf(gettext('%1$s/%2$s is not a valid subnet.'), $input_address, $input_address_subnet[$idx]);
474
				} else {
475
					$tmpaddress .= "/" . $input_address_subnet[$idx];
476
				}
477
			}
478
			$address[] = addrtolower($tmpaddress);
479
		}
480
		unset($desc_fmt_err_found);
481
		if ($wrongaliases <> "") {
482
			$data_errors[] = sprintf(gettext('The alias(es): %s cannot be nested because they are not of the same type.'), $wrongaliases);
483
		}
484
	}
485

  
486
	unset($vertical_bar_err_text);
487

  
488
	// Allow extending of the firewall edit page and include custom input validation
489
	pfSense_handle_custom_code("/usr/local/pkg/firewall_aliases_edit/input_validation");
490

  
491
	if (!$data_errors) {
492
		$alias['address'] = is_array($address) ? implode(" ", $address) : $address;
493
		$alias['descr'] = $post['descr'];
494
		$alias['type'] = $post['type'];
495
		$alias['detail'] = implode("||", $final_address_details);
496

  
497
		/*	 Check to see if alias name needs to be
498
		 *	 renamed on referenced rules and such
499
		 */
500
		if ($post['name'] <> $origname) {
501
			update_alias_name($post['name'], $origname);
502
		}
503

  
504
		pfSense_handle_custom_code("/usr/local/pkg/firewall_aliases_edit/pre_write_config");
505

  
506
		if (isset($id) && $a_aliases[$id]) {
507
			if ($a_aliases[$id]['name'] <> $alias['name']) {
508
				foreach ($a_aliases as $aliasid => $aliasd) {
509
					if ($aliasd['address'] <> "") {
510
						$tmpdirty = false;
511
						$tmpaddr = explode(" ", $aliasd['address']);
512
						foreach ($tmpaddr as $tmpidx => $tmpalias) {
513
							if ($tmpalias == $a_aliases[$id]['name']) {
514
								$tmpaddr[$tmpidx] = $alias['name'];
515
								$tmpdirty = true;
516
							}
517
						}
518
						if ($tmpdirty == true) {
519
							$a_aliases[$aliasid]['address'] = implode(" ", $tmpaddr);
520
						}
521
					}
522
				}
523
			}
524
			$a_aliases[$id] = $alias;
525
		} else {
526
			$a_aliases[] = $alias;
527
		}
528

  
529
		// Sort list
530
		$a_aliases = msort($a_aliases, "name");
531

  
532
		write_config(gettext("Edited a firewall alias.")) {
533
		}
534
	} else {
535
		//we received input errors, copy data to prevent retype
536
		$pconfig['name'] = $post['name'];
537
		$pconfig['descr'] = $post['descr'];
538
		if (isset($alias['aliasurl']) && ($post['type'] == 'url') || ($post['type'] == 'url_ports')) {
539
			$pconfig['address'] = implode(" ", $alias['aliasurl']);
540
		} else {
541
			$pconfig['address'] = implode(" ", $address);
542
		}
543
		$pconfig['type'] = $post['type'];
544
		$pconfig['detail'] = implode("||", $final_address_details);
545
	}
546

  
547
	return $data_errors;
548
}
549

  
550
function do_local_input_validation($postdata, $reqdfields, $reqdfieldsn, &$input_errors) {
551

  
552
	/* check for bad control characters */
553
	foreach ($postdata as $pn => $pd) {
554
		if (is_string($pd) && preg_match("/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/", $pd)) {
555
			$input_errors[] = sprintf(gettext("The field %s contains invalid characters."), $pn);
556
		}
557
	}
558

  
559
	if (is_array($reqdfields)) {
560
		for ($i = 0; $i < count($reqdfields); $i++) {
561
			if ($postdata[$reqdfields[$i]] == "") {
562
				$input_errors[] = sprintf(gettext("The field %s is required."), $reqdfieldsn[$i]);
563
			}
564
		}
565
	}
566
}
567

  
568
?>
src/usr/local/www/firewall_aliases_edit.php
36 36
require_once("functions.inc");
37 37
require_once("filter.inc");
38 38
require_once("shaper.inc");
39
require_Once("alias.inc");
39 40

  
40 41
if (isset($_POST['referer'])) {
41 42
	$referer = $_POST['referer'];
......
68 69
	'urltable_ports' => gettext("URL Table (Port)"),
69 70
);
70 71

  
71
function alias_same_type($name, $type) {
72
	global $config;
73

  
74
	foreach ($config['aliases']['alias'] as $alias) {
75
		if ($name == $alias['name']) {
76
			if (in_array($type, array("host", "network")) &&
77
			    in_array($alias['type'], array("host", "network"))) {
78
				return true;
79
			}
80

  
81
			if ($type == $alias['type']) {
82
				return true;
83
			} else {
84
				return false;
85
			}
86
		}
87
	}
88
	return true;
89
}
90

  
91 72
if (isset($_REQUEST['id']) && is_numericint($_REQUEST['id'])) {
92 73
	$id = $_REQUEST['id'];
93 74
}
......
156 137
$pglinks = array("", "firewall_aliases.php?tab=" . $tab, "@self");
157 138

  
158 139
if ($_POST['save']) {
159

  
160
	unset($input_errors);
161
	$vertical_bar_err_text = gettext("Vertical bars (|) at start or end, or double in the middle of descriptions not allowed. Descriptions have been cleaned. Check and save again.");
162

  
163
	/* input validation */
164

  
165
	$reqdfields = explode(" ", "name");
166
	$reqdfieldsn = array(gettext("Name"));
167

  
168
	do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
169

  
170
	if (!is_validaliasname($_POST['name'])) {
171
		$input_errors[] = invalidaliasnamemsg($_POST['name']);
172
	}
173

  
174
	/* check for name conflicts */
175
	foreach ($a_aliases as $key => $alias) {
176
		if (($alias['name'] == $_POST['name']) && (empty($a_aliases[$id]) || ($key != $id))) {
177
			$input_errors[] = gettext("An alias with this name already exists.");
178
			break;
179
		}
180
	}
181

  
182
	/* Check for reserved keyword names */
183
	foreach ($pf_reserved_keywords as $rk) {
184
		if (strcasecmp($rk, $_POST['name']) == 0) {
185
			$input_errors[] = sprintf(gettext("Cannot use a reserved keyword as an alias name: %s"), $rk);
186
		}
187
	}
188

  
189
	/*
190
	 * Packages (e.g. tinc) create interface groups, reserve this
191
	 * namespace pkg_ for them.
192
	 * One namespace is shared by Interfaces, Interface Groups and Aliases.
193
	 */
194
	if (substr($_POST['name'], 0, 4) == 'pkg_') {
195
		$input_errors[] = gettext("The alias name cannot start with pkg_");
196
	}
197

  
198
	/* check for name interface description conflicts */
199
	foreach ($config['interfaces'] as $interface) {
200
		if (strcasecmp($interface['descr'], $_POST['name']) == 0) {
201
			$input_errors[] = gettext("An interface description with this name already exists.");
202
			break;
203
		}
204
	}
205

  
206
	/* Is the description already used as an interface group name? */
207
	if (is_array($config['ifgroups']['ifgroupentry'])) {
208
		foreach ($config['ifgroups']['ifgroupentry'] as $ifgroupentry) {
209
			if ($ifgroupentry['ifname'] == $_POST['name']) {
210
				$input_errors[] = gettext("Sorry, an interface group with this name already exists.");
211
			}
212
		}
213
	}
214

  
215
	/* To prevent infinite loops make sure the alias name does not equal the value. */
216
	for($i = 0; isset($_POST['address' . $i]); $i++) {
217
			if($_POST['address' . $i] == $_POST['name']){
218
				$input_errors[] = gettext("Alias value cannot be the same as the alias name: `" . $_POST['name'] . " and " . $_POST['address' . $i] . "`");
219
			}
220
	}
221

  
222
	$alias = array();
223
	$address = array();
224
	$final_address_details = array();
225
	$alias['name'] = $_POST['name'];
226
	$alias['type'] = $_POST['type'];
227

  
228
	if (preg_match("/urltable/i", $_POST['type'])) {
229
		$address = array();
230

  
231
		/* item is a url table type */
232
		if ($_POST['address0']) {
233
			/* fetch down and add in */
234
			$_POST['address0'] = trim(idn_to_ascii($_POST['address0']));
235
			$address[] = $_POST['address0'];
236
			$alias['url'] = $_POST['address0'];
237
			$alias['updatefreq'] = $_POST['address_subnet0'] ? $_POST['address_subnet0'] : 7;
238
			if (!is_URL($alias['url']) || empty($alias['url'])) {
239
				$input_errors[] = gettext("A valid URL must be provided.");
240
			} elseif (!process_alias_urltable($alias['name'], $alias['type'], $alias['url'], 0, true, true)) {
241
				$input_errors[] = sprintf(gettext("Unable to fetch usable data from URL %s"), htmlspecialchars($alias['url']));
242
			}
243
			if ($_POST["detail0"] <> "") {
244
				if ((strpos($_POST["detail0"], "||") === false) && (substr($_POST["detail0"], 0, 1) != "|") && (substr($_POST["detail0"], -1, 1) != "|")) {
245
					$final_address_details[] = $_POST["detail0"];
246
				} else {
247
					/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
248
					/* and put in the output array so the text is at least redisplayed for the user. */
249
					$final_address_details[] = preg_replace('/\|\|+/', '|', trim($_POST["detail0"], "|"));
250
					$input_errors[] = $vertical_bar_err_text;
251
				}
252
			} else {
253
				$final_address_details[] = sprintf(gettext("Entry added %s"), date('r'));
254
			}
255
		}
256
	} elseif (($_POST['type'] == "url") || ($_POST['type'] == "url_ports")) {
257
		$desc_fmt_err_found = false;
258

  
259
		/* item is a url type */
260
		for ($x = 0; $x < $max_alias_addresses - 1; $x++) {
261
			$_POST['address' . $x] = trim(idn_to_ascii($_POST['address' . $x]));
262
			if ($_POST['address' . $x]) {
263
				/* fetch down and add in */
264
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
265
				unlink_if_exists($temp_filename);
266
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
267
				mkdir($temp_filename);
268
				if (!download_file($_POST['address' . $x], $temp_filename . "/aliases", $verify_ssl)) {
269
					$input_errors[] = sprintf(gettext("Could not fetch the URL '%s'."), $_POST['address' . $x]);
270
					continue;
271
				}
272

  
273
				/* if the item is tar gzipped then extract */
274
				if (stristr($_POST['address' . $x], ".tgz")) {
275
					process_alias_tgz($temp_filename);
276
				}
277

  
278
				if (!isset($alias['aliasurl'])) {
279
					$alias['aliasurl'] = array();
280
				}
281

  
282
				$alias['aliasurl'][] = $_POST['address' . $x];
283
				if ($_POST["detail{$x}"] <> "") {
284
					if ((strpos($_POST["detail{$x}"], "||") === false) && (substr($_POST["detail{$x}"], 0, 1) != "|") && (substr($_POST["detail{$x}"], -1, 1) != "|")) {
285
						$final_address_details[] = $_POST["detail{$x}"];
286
					} else {
287
						/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
288
						/* and put in the output array so the text is at least redisplayed for the user. */
289
						$final_address_details[] = preg_replace('/\|\|+/', '|', trim($_POST["detail{$x}"], "|"));
290
						if (!$desc_fmt_err_found) {
291
							$input_errors[] = $vertical_bar_err_text;
292
							$desc_fmt_err_found = true;
293
						}
294
					}
295
				} else {
296
					$final_address_details[] = sprintf(gettext("Entry added %s"), date('r'));
297
				}
298

  
299
				if (file_exists("{$temp_filename}/aliases")) {
300
					$t_address = parse_aliases_file("{$temp_filename}/aliases", $_POST['type'], 5000);
301
					if ($t_address == null) {
302
						/* nothing was found */
303
						$input_errors[] = sprintf(gettext("A valid URL must be provided. Could not fetch usable data from '%s'."), $_POST['address' . $x]);
304
					} else {
305
						array_push($address, ...$t_address);
306
					}
307
					unset($t_address);
308
					mwexec("/bin/rm -rf " . escapeshellarg($temp_filename));
309
				} else {
310
					$input_errors[] = sprintf(gettext("URL '%s' is not valid."), $_POST['address' . $x]);
311
				}
312
			}
313
		}
314
		unset($desc_fmt_err_found);
315
		if ($_POST['type'] == "url_ports") {
316
			$address = group_ports($address);
317
		}
318
	} else {
319
		/* item is a normal alias type */
320
		$wrongaliases = "";
321
		$desc_fmt_err_found = false;
322
		$alias_address_count = 0;
323
		$input_addresses = array();
324

  
325
		// First trim and expand the input data.
326
		// Users can paste strings like "10.1.2.0/24 10.3.0.0/16 9.10.11.0/24" into an address box.
327
		// They can also put an IP range.
328
		// This loop expands out that stuff so it can easily be validated.
329
		for ($x = 0; $x < ($max_alias_addresses - 1); $x++) {
330
			if ($_POST["address{$x}"] <> "") {
331
				if ($_POST["detail{$x}"] <> "") {
332
					if ((strpos($_POST["detail{$x}"], "||") === false) && (substr($_POST["detail{$x}"], 0, 1) != "|") && (substr($_POST["detail{$x}"], -1, 1) != "|")) {
333
						$detail_text = $_POST["detail{$x}"];
334
					} else {
335
						/* Remove leading and trailing vertical bars and replace multiple vertical bars with single, */
336
						/* and put in the output array so the text is at least redisplayed for the user. */
337
						$detail_text = preg_replace('/\|\|+/', '|', trim($_POST["detail{$x}"], "|"));
338
						if (!$desc_fmt_err_found) {
339
							$input_errors[] = $vertical_bar_err_text;
340
							$desc_fmt_err_found = true;
341
						}
342
					}
343
				} else {
344
					$detail_text = sprintf(gettext("Entry added %s"), date('r'));
345
				}
346
				$address_items = explode(" ", trim(idn_to_ascii($_POST["address{$x}"])));
347
				foreach ($address_items as $address_item) {
348
					$iprange_type = is_iprange($address_item);
349
					if ($iprange_type == 4) {
350
						list($startip, $endip) = explode('-', $address_item);
351
						if ($_POST['type'] == "network") {
352
							// For network type aliases, expand an IPv4 range into an array of subnets.
353
							$rangesubnets = ip_range_to_subnet_array($startip, $endip);
354
							foreach ($rangesubnets as $rangesubnet) {
355
								if ($alias_address_count > $max_alias_addresses) {
356
									break;
357
								}
358
								list($address_part, $subnet_part) = explode("/", $rangesubnet);
359
								$input_addresses[] = $address_part;
360
								$input_address_subnet[] = $subnet_part;
361
								$final_address_details[] = $detail_text;
362
								$alias_address_count++;
363
							}
364
						} else {
365
							// For host type aliases, expand an IPv4 range into a list of individual IPv4 addresses.
366
							$rangeaddresses = ip_range_to_address_array($startip, $endip, $max_alias_addresses - $alias_address_count);
367
							if (is_array($rangeaddresses)) {
368
								foreach ($rangeaddresses as $rangeaddress) {
369
									$input_addresses[] = $rangeaddress;
370
									$input_address_subnet[] = "";
371
									$final_address_details[] = $detail_text;
372
									$alias_address_count++;
373
								}
374
							} else {
375
								$input_errors[] = sprintf(gettext('Range is too large to expand into individual host IP addresses (%s)'), $address_item);
376
								$input_errors[] = sprintf(gettext('The maximum number of entries in an alias is %s'), $max_alias_addresses);
377
								// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
378
								$input_addresses[] = $address_item;
379
								$input_address_subnet[] = "";
380
								$final_address_details[] = $detail_text;
381
							}
382
						}
383
					} else if ($iprange_type == 6) {
384
						$input_errors[] = sprintf(gettext('IPv6 address ranges are not supported (%s)'), $address_item);
385
						// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
386
						$input_addresses[] = $address_item;
387
						$input_address_subnet[] = "";
388
						$final_address_details[] = $detail_text;
389
					} else {
390
						$subnet_type = is_subnet($address_item);
391
						if (($_POST['type'] == "host") && $subnet_type) {
392
							if ($subnet_type == 4) {
393
								// For host type aliases, if the user enters an IPv4 subnet, expand it into a list of individual IPv4 addresses.
394
								$subnet_size = subnet_size($address_item);
395
								if ($subnet_size > 0 &&
396
								    $subnet_size <= ($max_alias_addresses - $alias_address_count)) {
397
									$rangeaddresses = subnetv4_expand($address_item);
398
									foreach ($rangeaddresses as $rangeaddress) {
399
										$input_addresses[] = $rangeaddress;
400
										$input_address_subnet[] = "";
401
										$final_address_details[] = $detail_text;
402
										$alias_address_count++;
403
									}
404
								} else {
405
									$input_errors[] = sprintf(gettext('Subnet is too large to expand into individual host IP addresses (%s)'), $address_item);
406
									$input_errors[] = sprintf(gettext('The maximum number of entries in an alias is %s'), $max_alias_addresses);
407
									// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
408
									$input_addresses[] = $address_item;
409
									$input_address_subnet[] = "";
410
									$final_address_details[] = $detail_text;
411
								}
412
							} else {
413
								$input_errors[] = sprintf(gettext('IPv6 subnets are not supported in host aliases (%s)'), $address_item);
414
								// Put the user-entered data in the output anyway, so it will be re-displayed for correction.
415
								$input_addresses[] = $address_item;
416
								$input_address_subnet[] = "";
417
								$final_address_details[] = $detail_text;
418
							}
419
						} else {
420
							list($address_part, $subnet_part) = explode("/", $address_item);
421
							if (!empty($subnet_part)) {
422
								if (is_subnet($address_item)) {
423
									$input_addresses[] = $address_part;
424
									$input_address_subnet[] = $subnet_part;
425
								} else {
426
									// The user typed something like "1.2.3.444/24" or "1.2.3.0/36" or similar rubbish.
427
									// Feed it through without splitting it apart, then it will be caught by the validation loop below.
428
									$input_addresses[] = $address_item;
429
									$input_address_subnet[] = "";
430
								}
431
							} else {
432
								$input_addresses[] = $address_part;
433
								$input_address_subnet[] = $_POST["address_subnet{$x}"];
434
							}
435
							$final_address_details[] = $detail_text;
436
							$alias_address_count++;
437
						}
438
					}
439
					if ($alias_address_count > $max_alias_addresses) {
440
						$input_errors[] = sprintf(gettext('The maximum number of entries in an alias has been exceeded (%s)'), $max_alias_addresses);
441
						break;
442
					}
443
				}
444
			}
445
		}
446

  
447
		// Validate the input data expanded above.
448
		foreach ($input_addresses as $idx => $input_address) {
449
			if (is_alias($input_address)) {
450
				if (!alias_same_type($input_address, $_POST['type'])) {
451
					// But alias type network can include alias type urltable. Feature#1603.
452
					if (!($_POST['type'] == 'network' &&
453
					    preg_match("/urltable/i", alias_get_type($input_address)))) {
454
						$wrongaliases .= " " . $input_address;
455
					}
456
				}
457
			} else if ($_POST['type'] == "port") {
458
				if (!is_port_or_range($input_address)) {
459
					$input_errors[] = sprintf(gettext("%s is not a valid port or alias."), $input_address);
460
				}
461
			} else if (($_POST['type'] == "host") || ($_POST['type'] == "network")) {
462
				if (is_subnet($input_address) ||
463
				    (!is_ipaddr($input_address) && !is_hostname($input_address))) {
464
					$input_errors[] = sprintf(gettext('%1$s is not a valid %2$s address, FQDN or alias.'), $input_address, $singular_types[$_POST['type']]);
465
				}
466
			}
467
			$tmpaddress = $input_address;
468
			if (($_POST['type'] != "host") && is_ipaddr($input_address) && ($input_address_subnet[$idx] <> "")) {
469
				if (!is_subnet($input_address . "/" . $input_address_subnet[$idx])) {
470
					$input_errors[] = sprintf(gettext('%1$s/%2$s is not a valid subnet.'), $input_address, $input_address_subnet[$idx]);
471
				} else {
472
					$tmpaddress .= "/" . $input_address_subnet[$idx];
473
				}
474
			}
475
			$address[] = addrtolower($tmpaddress);
476
		}
477
		unset($desc_fmt_err_found);
478
		if ($wrongaliases <> "") {
479
			$input_errors[] = sprintf(gettext('The alias(es): %s cannot be nested because they are not of the same type.'), $wrongaliases);
480
		}
481
	}
482

  
483
	unset($vertical_bar_err_text);
484

  
485
	// Allow extending of the firewall edit page and include custom input validation
486
	pfSense_handle_custom_code("/usr/local/pkg/firewall_aliases_edit/input_validation");
140
	$input_errors = saveAlias($_POST, $id);
487 141

  
488 142
	if (!$input_errors) {
489
		$alias['address'] = is_array($address) ? implode(" ", $address) : $address;
490
		$alias['descr'] = $_POST['descr'];
491
		$alias['type'] = $_POST['type'];
492
		$alias['detail'] = implode("||", $final_address_details);
493

  
494
		/*	 Check to see if alias name needs to be
495
		 *	 renamed on referenced rules and such
496
		 */
497
		if ($_POST['name'] <> $origname) {
498
			update_alias_name($_POST['name'], $origname);
499
		}
500

  
501
		pfSense_handle_custom_code("/usr/local/pkg/firewall_aliases_edit/pre_write_config");
502

  
503
		if (isset($id) && $a_aliases[$id]) {
504
			if ($a_aliases[$id]['name'] <> $alias['name']) {
505
				foreach ($a_aliases as $aliasid => $aliasd) {
506
					if ($aliasd['address'] <> "") {
507
						$tmpdirty = false;
508
						$tmpaddr = explode(" ", $aliasd['address']);
509
						foreach ($tmpaddr as $tmpidx => $tmpalias) {
510
							if ($tmpalias == $a_aliases[$id]['name']) {
511
								$tmpaddr[$tmpidx] = $alias['name'];
512
								$tmpdirty = true;
513
							}
514
						}
515
						if ($tmpdirty == true) {
516
							$a_aliases[$aliasid]['address'] = implode(" ", $tmpaddr);
517
						}
518
					}
519
				}
520
			}
521
			$a_aliases[$id] = $alias;
522
		} else {
523
			$a_aliases[] = $alias;
524
		}
525

  
526
		// Sort list
527
		$a_aliases = msort($a_aliases, "name");
528

  
529
		if (write_config(gettext("Edited a firewall alias."))) {
530
			mark_subsystem_dirty('aliases');
531
		}
143
		mark_subsystem_dirty('aliases');
532 144

  
533 145
		if (!empty($tab)) {
534 146
			header("Location: firewall_aliases.php?tab=" . htmlspecialchars ($tab));
535 147
		} else {
536 148
			header("Location: firewall_aliases.php");
537 149
		}
538
		exit;
539 150

  
540
	} else {
541
		//we received input errors, copy data to prevent retype
542
		$pconfig['name'] = $_POST['name'];
543
		$pconfig['descr'] = $_POST['descr'];
544
		if (isset($alias['aliasurl']) && ($_POST['type'] == 'url') || ($_POST['type'] == 'url_ports')) {
545
			$pconfig['address'] = implode(" ", $alias['aliasurl']);
546
		} else {
547
			$pconfig['address'] = implode(" ", $address);
548
		}
549
		$pconfig['type'] = $_POST['type'];
550
		$pconfig['detail'] = implode("||", $final_address_details);
151
		exit;
551 152
	}
552 153
}
553 154

  
554

  
555 155
include("head.inc");
556 156

  
557 157
$section_str = array(

Also available in: Unified diff