Project

General

Profile

Download (33.3 KB) Statistics
| Branch: | Tag: | Revision:
1 f20afeb6 Warren Baker
<?php
2
/*
3 ac24dc24 Renato Botelho
 * unbound.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 c5d81585 Renato Botelho
 * Copyright (c) 2015 Warren Baker <warren@percol8.co.za>
7 38809d47 Renato Botelho do Couto
 * Copyright (c) 2015-2016 Electric Sheep Fencing
8 8f2f85c3 Luiz Otavio O Souza
 * Copyright (c) 2015-2022 Rubicon Communications, LLC (Netgate)
9 ac24dc24 Renato Botelho
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12 c5d81585 Renato Botelho
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13 ac24dc24 Renato Botelho
 * All rights reserved.
14
 *
15 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 *
19 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
20 ac24dc24 Renato Botelho
 *
21 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 */
27 f20afeb6 Warren Baker
28
/* include all configuration functions */
29
require_once("config.inc");
30
require_once("functions.inc");
31 3bdf2a70 Chris Buechler
require_once("filter.inc");
32
require_once("shaper.inc");
33 09d529a6 Viktor G
require_once("interfaces.inc");
34
require_once("util.inc");
35 f20afeb6 Warren Baker
36 1548bd35 Phil Davis
function create_unbound_chroot_path($cfgsubdir = "") {
37 e318d592 Phil Davis
	global $config, $g;
38
39
	// Configure chroot
40
	if (!is_dir($g['unbound_chroot_path'])) {
41
		mkdir($g['unbound_chroot_path']);
42
		chown($g['unbound_chroot_path'], "unbound");
43
		chgrp($g['unbound_chroot_path'], "unbound");
44
	}
45
46 1548bd35 Phil Davis
	if ($cfgsubdir != "") {
47
		$cfgdir = $g['unbound_chroot_path'] . $cfgsubdir;
48
		if (!is_dir($cfgdir)) {
49
			mkdir($cfgdir);
50
			chown($cfgdir, "unbound");
51
			chgrp($cfgdir, "unbound");
52
		}
53
	}
54 e318d592 Phil Davis
}
55
56 f20afeb6 Warren Baker
/* Optimize Unbound for environment */
57
function unbound_optimization() {
58 fe9d4894 Renato Botelho
	global $config;
59
60
	$optimization_settings = array();
61
62 751533a2 Phil Davis
	/*
63 fe9d4894 Renato Botelho
	 * Set the number of threads equal to number of CPUs.
64
	 * Use 1 to disable threading, if for some reason this sysctl fails.
65
	 */
66
	$numprocs = intval(get_single_sysctl('kern.smp.cpus'));
67 46762efe Warren Baker
	if ($numprocs > 1) {
68 fe9d4894 Renato Botelho
		$optimization['number_threads'] = "num-threads: {$numprocs}";
69 086cf944 Phil Davis
		$optimize_num = pow(2, floor(log($numprocs, 2)));
70 46762efe Warren Baker
	} else {
71 fe9d4894 Renato Botelho
		$optimization['number_threads'] = "num-threads: 1";
72 46762efe Warren Baker
		$optimize_num = 4;
73
	}
74 fe9d4894 Renato Botelho
75
	// Slabs to help reduce lock contention.
76 46762efe Warren Baker
	$optimization['msg_cache_slabs'] = "msg-cache-slabs: {$optimize_num}";
77
	$optimization['rrset_cache_slabs'] = "rrset-cache-slabs: {$optimize_num}";
78
	$optimization['infra_cache_slabs'] = "infra-cache-slabs: {$optimize_num}";
79
	$optimization['key_cache_slabs'] = "key-cache-slabs: {$optimize_num}";
80 fe9d4894 Renato Botelho
81
	/*
82
	 * Larger socket buffer for busy servers
83
	 * Check that it is set to 4MB (by default the OS has it configured to 4MB)
84
	 */
85 d87fcac9 Ermal
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
86
		foreach ($config['sysctl']['item'] as $tunable) {
87
			if ($tunable['tunable'] == 'kern.ipc.maxsockbuf') {
88 3e2e1b2c Steve Beaver
				$so = floor((intval($tunable['value'])/1024/1024)-4);
89 d87fcac9 Ermal
				// Check to ensure that the number is not a negative
90 ad04bbbf Warren Baker
				if ($so >= 4) {
91
					// Limit to 32MB, users might set maxsockbuf very high for other reasons.
92 4708c6f0 Phil Davis
					// We do not want unbound to fail because of that.
93 ad04bbbf Warren Baker
					$so = min($so, 32);
94 d87fcac9 Ermal
					$optimization['so_rcvbuf'] = "so-rcvbuf: {$so}m";
95 ad04bbbf Warren Baker
				} else {
96 d87fcac9 Ermal
					unset($optimization['so_rcvbuf']);
97 ad04bbbf Warren Baker
				}
98 d87fcac9 Ermal
			}
99 fe9d4894 Renato Botelho
		}
100
	}
101
	// Safety check in case kern.ipc.maxsockbuf is not available.
102 751533a2 Phil Davis
	if (!isset($optimization['so_rcvbuf'])) {
103 fe9d4894 Renato Botelho
		$optimization['so_rcvbuf'] = "#so-rcvbuf: 4m";
104 751533a2 Phil Davis
	}
105 fe9d4894 Renato Botelho
106
	return $optimization;
107 f20afeb6 Warren Baker
108
}
109
110 932711c7 Matt Smith
function test_unbound_config($unboundcfg, &$output) {
111
	global $g;
112
113 1548bd35 Phil Davis
	$cfgsubdir = "/test";
114 3d706897 Renato Botelho
	$cfgdir = "{$g['unbound_chroot_path']}{$cfgsubdir}";
115
	rmdir_recursive($cfgdir);
116
117 241c4b58 BBcan177
	// Copy the Python files to the test folder
118 7be7d84e jim-p
	if (isset($unboundcfg['python']) &&
119
	    !empty($unboundcfg['python_script'])) {
120 241c4b58 BBcan177
		$python_files = glob("{$g['unbound_chroot_path']}/{$unboundcfg['python_script']}.*");
121
		if (is_array($python_files)) {
122 7be7d84e jim-p
			create_unbound_chroot_path($cfgsubdir);
123 241c4b58 BBcan177
			foreach ($python_files as $file) {
124
				$file = pathinfo($file, PATHINFO_BASENAME);
125
				@copy("{$g['unbound_chroot_path']}/{$file}", "{$cfgdir}/{$file}");
126
			}
127
		}
128
	}
129
130 7be7d84e jim-p
	unbound_generate_config($unboundcfg, $cfgsubdir);
131
	unbound_remote_control_setup($cfgsubdir);
132
	do_as_unbound_user("unbound-anchor", $cfgsubdir);
133
134 932711c7 Matt Smith
	$rv = 0;
135 3d706897 Renato Botelho
	exec("/usr/local/sbin/unbound-checkconf {$cfgdir}/unbound.conf 2>&1",
136
	    $output, $rv);
137
138
	if ($rv == 0) {
139
		rmdir_recursive($cfgdir);
140
	}
141 932711c7 Matt Smith
142
	return $rv;
143
}
144
145
146 1548bd35 Phil Davis
function unbound_generate_config($unboundcfg = NULL, $cfgsubdir = "") {
147 a569071d Phil Davis
	global $g;
148 932711c7 Matt Smith
149 1548bd35 Phil Davis
	$unboundcfgtxt = unbound_generate_config_text($unboundcfg, $cfgsubdir);
150 932711c7 Matt Smith
151
	// Configure static Host entries
152 1548bd35 Phil Davis
	unbound_add_host_entries($cfgsubdir);
153 932711c7 Matt Smith
154
	// Configure Domain Overrides
155 1548bd35 Phil Davis
	unbound_add_domain_overrides("", $cfgsubdir);
156 932711c7 Matt Smith
157
	// Configure Unbound access-lists
158 1548bd35 Phil Davis
	unbound_acls_config($cfgsubdir);
159 932711c7 Matt Smith
160 1548bd35 Phil Davis
	create_unbound_chroot_path($cfgsubdir);
161
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound.conf", $unboundcfgtxt);
162 932711c7 Matt Smith
}
163
164 7be7d84e jim-p
function unbound_get_python_scriptname($unboundcfg, $cfgsubdir = '') {
165
	global $g;
166
	if (!isset($unboundcfg['python']) ||
167
	    empty($unboundcfg['python_script'])) {
168
		/* Python is not enabled, or no script defined. */
169
		return "";
170
	}
171
172
	$python_path = $g['unbound_chroot_path'];
173
	if (!empty($cfgsubdir)) {
174
		$python_path .= "{$cfgsubdir}";
175
	}
176
177
	/* Full path to the selected script file */
178
	$python_script_file = "{$python_path}/{$unboundcfg['python_script']}.py";
179
180
	if (file_exists($python_script_file)) {
181
		/* If using a subdir (e.g. testing) use the full path, otherwise
182
		 * only use the base filename. */
183
		return empty($cfgsubdir) ? basename($python_script_file) : $python_script_file;
184
	} else {
185
		return '';
186
	}
187
}
188 932711c7 Matt Smith
189 1548bd35 Phil Davis
function unbound_generate_config_text($unboundcfg = NULL, $cfgsubdir = "") {
190 932711c7 Matt Smith
191 283f9e8c jim-p
	global $config, $g, $nooutifs;
192 932711c7 Matt Smith
	if (is_null($unboundcfg)) {
193
		$unboundcfg = $config['unbound'];
194
	}
195 fe9d4894 Renato Botelho
196 051e7db5 Viktor G
	if (platform_booting()) {
197
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
198
	}
199
200 fe9d4894 Renato Botelho
	// Setup optimization
201
	$optimization = unbound_optimization();
202
203 241c4b58 BBcan177
	$module_config = '';
204
205
	// Setup Python module (pre validator)
206 7be7d84e jim-p
	if (!empty(unbound_get_python_scriptname($unboundcfg, $cfgsubdir)) &&
207
	    $unboundcfg['python_order'] == 'pre_validator') {
208 241c4b58 BBcan177
		$module_config .= 'python ';
209
	}
210
211 dc104520 Viktor G
	// Setup DNS64 support
212
	if (isset($unboundcfg['dns64'])) {
213
		$module_config .= 'dns64 ';
214
		$dns64_conf = 'dns64-prefix: ';
215
		if (is_subnetv6($unboundcfg['dns64prefix'] . '/' . $unboundcfg['dns64netbits'])) {
216
			$dns64_conf .= $unboundcfg['dns64prefix'] . '/' . $unboundcfg['dns64netbits'];
217
		} else {
218
			$dns64_conf .= '64:ff9b::/96';
219
		}
220
	}
221
222 fe9d4894 Renato Botelho
	// Setup DNSSEC support
223 932711c7 Matt Smith
	if (isset($unboundcfg['dnssec'])) {
224 241c4b58 BBcan177
		$module_config .= 'validator ';
225 1548bd35 Phil Davis
		$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}{$cfgsubdir}/root.key";
226 751533a2 Phil Davis
	}
227 fe9d4894 Renato Botelho
228 241c4b58 BBcan177
	// Setup Python module (post validator)
229 7be7d84e jim-p
	if (!empty(unbound_get_python_scriptname($unboundcfg, $cfgsubdir)) &&
230
	    $unboundcfg['python_order'] == 'post_validator') {
231 241c4b58 BBcan177
		$module_config .= 'python ';
232
	}
233
234
	$module_config .= 'iterator';
235
236 fe9d4894 Renato Botelho
	// Setup DNS Rebinding
237
	if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
238
		// Private-addresses for DNS Rebinding
239
		$private_addr = <<<EOF
240 f20afeb6 Warren Baker
# For DNS Rebinding prevention
241 afeb18ff jim-p
private-address: 127.0.0.0/8
242 f20afeb6 Warren Baker
private-address: 10.0.0.0/8
243 df0a71cb jim-p
private-address: ::ffff:a00:0/104
244 f20afeb6 Warren Baker
private-address: 172.16.0.0/12
245 df0a71cb jim-p
private-address: ::ffff:ac10:0/108
246 c683f627 Chris Buechler
private-address: 169.254.0.0/16
247 df0a71cb jim-p
private-address: ::ffff:a9fe:0/112
248 f20afeb6 Warren Baker
private-address: 192.168.0.0/16
249 df0a71cb jim-p
private-address: ::ffff:c0a8:0/112
250 f20afeb6 Warren Baker
private-address: fd00::/8
251
private-address: fe80::/10
252
EOF;
253 fe9d4894 Renato Botelho
	}
254
255 1fa69c27 jim-p
	// Determine interfaces where unbound will bind
256 7e8bfed2 jim-p
	$tlsport = is_numeric($unboundcfg['tlsport']) ? $unboundcfg['tlsport'] : "853";
257 1fa69c27 jim-p
	$bindintcfg = "";
258
	$bindints = array();
259
	$active_interfaces = explode(",", $unboundcfg['active_interface']);
260
	if (empty($unboundcfg['active_interface']) || in_array("all", $active_interfaces, true)) {
261
		$bindints[] = "0.0.0.0";
262
		$bindints[] = "::0";
263
		$bindintcfg .= "interface-automatic: " . (isset($unboundcfg['enablessl']) ? "no" : "yes") . "\n";
264
	} else {
265
		foreach ($active_interfaces as $ubif) {
266 e65b646f Viktor G
			/* Do not bind to disabled/nocarrier interfaces,
267
			 * see https://redmine.pfsense.org/issues/11087 */
268
			$ifinfo = get_interface_info($ubif);
269
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
270
				continue;
271
			}
272 1fa69c27 jim-p
			if (is_ipaddr($ubif)) {
273
				$bindints[] = $ubif;
274
			} else {
275
				$intip = get_interface_ip($ubif);
276
				if (is_ipaddrv4($intip)) {
277
					$bindints[] = $intip;
278
				}
279
				$intip = get_interface_ipv6($ubif);
280
				if (is_ipaddrv6($intip)) {
281
					$bindints[] = $intip;
282 a0e9e17d Chris Buechler
				}
283 751533a2 Phil Davis
			}
284 fe9d4894 Renato Botelho
		}
285 1fa69c27 jim-p
	}
286
	foreach ($bindints as $bindint) {
287
		$bindintcfg .= "interface: {$bindint}\n";
288
		if (isset($unboundcfg['enablessl'])) {
289 7e8bfed2 jim-p
			$bindintcfg .= "interface: {$bindint}@{$tlsport}\n";
290 1fa69c27 jim-p
		}
291
	}
292
293 7e8bfed2 jim-p
	// TLS Configuration
294
	$tlsconfig = "tls-cert-bundle: \"/etc/ssl/cert.pem\"\n";
295
296 1fa69c27 jim-p
	if (isset($unboundcfg['enablessl'])) {
297 7e8bfed2 jim-p
		$tlscert_path = "{$g['unbound_chroot_path']}/sslcert.crt";
298
		$tlskey_path = "{$g['unbound_chroot_path']}/sslcert.key";
299 1fa69c27 jim-p
300 f764f63a jim-p
		// Enable SSL/TLS on the chosen or default port
301 7e8bfed2 jim-p
		$tlsconfig .= "tls-port: {$tlsport}\n";
302 1fa69c27 jim-p
303
		// Lookup CA and Server Cert
304
		$cert = lookup_cert($unboundcfg['sslcertref']);
305
		$ca = ca_chain($cert);
306
		$cert_chain = base64_decode($cert['crt']);
307
		if (!empty($ca)) {
308
			$cert_chain .= "\n" . $ca;
309
		}
310
311
		// Write CA and Server Cert
312 7e8bfed2 jim-p
		file_put_contents($tlscert_path, $cert_chain);
313
		chmod($tlscert_path, 0644);
314
		file_put_contents($tlskey_path, base64_decode($cert['prv']));
315
		chmod($tlskey_path, 0600);
316 1fa69c27 jim-p
317
		// Add config for CA and Server Cert
318 7e8bfed2 jim-p
		$tlsconfig .= "tls-service-pem: \"{$tlscert_path}\"\n";
319
		$tlsconfig .= "tls-service-key: \"{$tlskey_path}\"\n";
320 fe9d4894 Renato Botelho
	}
321
322
	// Determine interfaces to run on
323
	$outgoingints = "";
324 932711c7 Matt Smith
	if (!empty($unboundcfg['outgoing_interface'])) {
325
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
326 751533a2 Phil Davis
		foreach ($outgoing_interfaces as $outif) {
327 e65b646f Viktor G
			$ifinfo = get_interface_info($outif);
328
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
329
				continue;
330
			}
331 fe9d4894 Renato Botelho
			$outip = get_interface_ip($outif);
332 c37ffea8 Chris Buechler
			if (is_ipaddr($outip)) {
333 fe9d4894 Renato Botelho
				$outgoingints .= "outgoing-interface: $outip\n";
334 751533a2 Phil Davis
			}
335 fe9d4894 Renato Botelho
			$outip = get_interface_ipv6($outif);
336 c37ffea8 Chris Buechler
			if (is_ipaddrv6($outip)) {
337 fe9d4894 Renato Botelho
				$outgoingints .= "outgoing-interface: $outip\n";
338 751533a2 Phil Davis
			}
339 fe9d4894 Renato Botelho
		}
340 283f9e8c jim-p
		if (!empty($outgoingints)) {
341
			$outgoingints = "# Outgoing interfaces to be used\n" . $outgoingints;
342
		} else {
343
			$nooutifs = true;
344
		}
345 fe9d4894 Renato Botelho
	}
346
347
	// Allow DNS Rebind for forwarded domains
348 932711c7 Matt Smith
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
349 984abd66 Phil Davis
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
350
			$private_domains = "# Set private domains in case authoritative name server returns a Private IP address\n";
351
			$private_domains .= unbound_add_domain_overrides("private");
352
		}
353
		$reverse_zones .= unbound_add_domain_overrides("reverse");
354 fe9d4894 Renato Botelho
	}
355
356 ab8f10f2 Phil Davis
	// Configure Unbound statistics
357
	$statistics = unbound_statistics();
358
359 fe9d4894 Renato Botelho
	// Add custom Unbound options
360 932711c7 Matt Smith
	if ($unboundcfg['custom_options']) {
361
		$custom_options_source = explode("\n", base64_decode($unboundcfg['custom_options']));
362 b9608ab6 Phil Davis
		$custom_options = "# Unbound custom options\n";
363 751533a2 Phil Davis
		foreach ($custom_options_source as $ent) {
364 b9608ab6 Phil Davis
			$custom_options .= $ent."\n";
365 751533a2 Phil Davis
		}
366 fe9d4894 Renato Botelho
	}
367
368
	// Server configuration variables
369 932711c7 Matt Smith
	$port = (is_port($unboundcfg['port'])) ? $unboundcfg['port'] : "53";
370
	$hide_identity = isset($unboundcfg['hideidentity']) ? "yes" : "no";
371
	$hide_version = isset($unboundcfg['hideversion']) ? "yes" : "no";
372 deb575ab stilez
	$ipv6_allow = isset($config['system']['ipv6allow']) ? "yes" : "no";
373 932711c7 Matt Smith
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
374
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
375
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
376 84ec58b7 marjohn56
	$dns_record_cache = isset($unboundcfg['dnsrecordcache']) ? "yes" : "no";
377 7e9d72cf Viktor Gurov
	$aggressivensec = isset($unboundcfg['aggressivensec']) ? "yes" : "no";
378 f8a475f5 lukehamburg
	$outgoing_num_tcp = isset($unboundcfg['outgoing_num_tcp']) ? $unboundcfg['outgoing_num_tcp'] : "10";
379
	$incoming_num_tcp = isset($unboundcfg['incoming_num_tcp']) ? $unboundcfg['incoming_num_tcp'] : "10";
380 09d529a6 Viktor G
	if (empty($unboundcfg['edns_buffer_size']) || ($unboundcfg['edns_buffer_size'] == 'auto')) {
381
		$edns_buffer_size = unbound_auto_ednsbufsize();
382
	} else {
383
		$edns_buffer_size = $unboundcfg['edns_buffer_size'];
384
	}
385 932711c7 Matt Smith
	$num_queries_per_thread = (!empty($unboundcfg['num_queries_per_thread'])) ? $unboundcfg['num_queries_per_thread'] : "4096";
386
	$jostle_timeout = (!empty($unboundcfg['jostle_timeout'])) ? $unboundcfg['jostle_timeout'] : "200";
387
	$cache_max_ttl = (!empty($unboundcfg['cache_max_ttl'])) ? $unboundcfg['cache_max_ttl'] : "86400";
388
	$cache_min_ttl = (!empty($unboundcfg['cache_min_ttl'])) ? $unboundcfg['cache_min_ttl'] : "0";
389
	$infra_host_ttl = (!empty($unboundcfg['infra_host_ttl'])) ? $unboundcfg['infra_host_ttl'] : "900";
390
	$infra_cache_numhosts = (!empty($unboundcfg['infra_cache_numhosts'])) ? $unboundcfg['infra_cache_numhosts'] : "10000";
391
	$unwanted_reply_threshold = (!empty($unboundcfg['unwanted_reply_threshold'])) ? $unboundcfg['unwanted_reply_threshold'] : "0";
392 751533a2 Phil Davis
	if ($unwanted_reply_threshold == "disabled") {
393 b9608ab6 Phil Davis
		$unwanted_reply_threshold = "0";
394 751533a2 Phil Davis
	}
395 932711c7 Matt Smith
	$msg_cache_size = (!empty($unboundcfg['msgcachesize'])) ? $unboundcfg['msgcachesize'] : "4";
396
	$verbosity = isset($unboundcfg['log_verbosity']) ? $unboundcfg['log_verbosity'] : 1;
397
	$use_caps = isset($unboundcfg['use_caps']) ? "yes" : "no";
398 fe9d4894 Renato Botelho
399 203b1110 Lorenz Schori
	if (isset($unboundcfg['regovpnclients'])) {
400
		$openvpn_clients_conf .=<<<EOD
401
# OpenVPN client entries
402
include: {$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf
403
EOD;
404
	} else {
405
		$openvpn_clients_conf = '';
406 c3b39cc4 Viktor G
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
407 203b1110 Lorenz Schori
	}
408
409 a110a0cb Phil Davis
	// Set up forwarding if it is configured
410 932711c7 Matt Smith
	if (isset($unboundcfg['forwarding'])) {
411 f0c51530 jim-p
		$dnsservers = get_dns_nameservers(false, true);
412 fe9d4894 Renato Botelho
		if (!empty($dnsservers)) {
413
			$forward_conf .=<<<EOD
414 75e6d1b2 Warren Baker
# Forwarding
415 be5aa310 Warren Baker
forward-zone:
416 fe9d4894 Renato Botelho
	name: "."
417 be5aa310 Warren Baker
418
EOD;
419 cd738219 jim-p
			if (isset($unboundcfg['forward_tls_upstream'])) {
420
				$forward_conf .= "\tforward-tls-upstream: yes\n";
421
			}
422 7e8bfed2 jim-p
423
			/* Build DNS server hostname list. See https://redmine.pfsense.org/issues/8602 */
424
			$dns_hostnames = array();
425
			$dnshost_counter = 1;
426
			while (isset($config["system"]["dns{$dnshost_counter}host"])) {
427
				$pconfig_dnshost_counter = $dnshost_counter - 1;
428
				if (!empty($config["system"]["dns{$dnshost_counter}host"]) &&
429
				    isset($config["system"]["dnsserver"][$pconfig_dnshost_counter]))
430
				$dns_hostnames[$config["system"]["dnsserver"][$pconfig_dnshost_counter]] = $config["system"]["dns{$dnshost_counter}host"];
431
				$dnshost_counter++;
432
			}
433
434 751533a2 Phil Davis
			foreach ($dnsservers as $dnsserver) {
435 7e8bfed2 jim-p
				$fwdport = "";
436
				$fwdhost = "";
437 84588e00 Chris Buechler
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
438 7e8bfed2 jim-p
					if (isset($unboundcfg['forward_tls_upstream'])) {
439
						$fwdport = "@853";
440
						if (array_key_exists($dnsserver, $dns_hostnames)) {
441
							$fwdhost = "#{$dns_hostnames[$dnsserver]}";
442
						}
443
					}
444
					$forward_conf .= "\tforward-addr: {$dnsserver}{$fwdport}{$fwdhost}\n";
445 84588e00 Chris Buechler
				}
446 751533a2 Phil Davis
			}
447 fe9d4894 Renato Botelho
		}
448 751533a2 Phil Davis
	} else {
449 fe9d4894 Renato Botelho
		$forward_conf = "";
450 751533a2 Phil Davis
	}
451 be5aa310 Warren Baker
452 2597415b Chris Buechler
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
453
	$rrset_cache_size = $msg_cache_size * 2;
454
455 547e51b8 jim-p
	/* QNAME Minimization. https://redmine.pfsense.org/issues/8028
456
	 * Unbound uses the British style in the option name so the internal option
457
	 * name follows that, but the user-visible descriptions follow US English.
458
	 */
459
	$qname_min = "";
460
	if (isset($unboundcfg['qname-minimisation'])) {
461
		$qname_min = "qname-minimisation: yes\n";
462
		if (isset($unboundcfg['qname-minimisation-strict'])) {
463
			$qname_min .= "qname-minimisation-strict: yes\n";
464
		}
465
	}
466
467 241c4b58 BBcan177
	$python_module = '';
468 7be7d84e jim-p
	$python_script_file = unbound_get_python_scriptname($unboundcfg, $cfgsubdir);
469
	if (!empty($python_script_file)) {
470
		$python_module = "\n# Python Module\npython:\npython-script: {$python_script_file}";
471 241c4b58 BBcan177
	}
472
473 fe9d4894 Renato Botelho
	$unboundconf = <<<EOD
474 f20afeb6 Warren Baker
##########################
475
# Unbound Configuration
476
##########################
477
478
##
479
# Server configuration
480
##
481
server:
482 984abd66 Phil Davis
{$reverse_zones}
483 f20afeb6 Warren Baker
chroot: {$g['unbound_chroot_path']}
484
username: "unbound"
485 56a87b19 Warren Baker
directory: "{$g['unbound_chroot_path']}"
486 f20afeb6 Warren Baker
pidfile: "/var/run/unbound.pid"
487
use-syslog: yes
488 d12889b0 Warren Baker
port: {$port}
489 56a87b19 Warren Baker
verbosity: {$verbosity}
490 b9608ab6 Phil Davis
hide-identity: {$hide_identity}
491
hide-version: {$hide_version}
492 5c7c369f Chris Buechler
harden-glue: yes
493 f20afeb6 Warren Baker
do-ip4: yes
494 d2ec5844 stilez
do-ip6: {$ipv6_allow}
495 f20afeb6 Warren Baker
do-udp: yes
496
do-tcp: yes
497
do-daemonize: yes
498
module-config: "{$module_config}"
499 b9608ab6 Phil Davis
unwanted-reply-threshold: {$unwanted_reply_threshold}
500
num-queries-per-thread: {$num_queries_per_thread}
501
jostle-timeout: {$jostle_timeout}
502
infra-host-ttl: {$infra_host_ttl}
503
infra-cache-numhosts: {$infra_cache_numhosts}
504
outgoing-num-tcp: {$outgoing_num_tcp}
505
incoming-num-tcp: {$incoming_num_tcp}
506
edns-buffer-size: {$edns_buffer_size}
507 56a87b19 Warren Baker
cache-max-ttl: {$cache_max_ttl}
508
cache-min-ttl: {$cache_min_ttl}
509 b9608ab6 Phil Davis
harden-dnssec-stripped: {$harden_dnssec_stripped}
510
msg-cache-size: {$msg_cache_size}m
511 2597415b Chris Buechler
rrset-cache-size: {$rrset_cache_size}m
512 547e51b8 jim-p
{$qname_min}
513 f20afeb6 Warren Baker
{$optimization['number_threads']}
514
{$optimization['msg_cache_slabs']}
515
{$optimization['rrset_cache_slabs']}
516
{$optimization['infra_cache_slabs']}
517
{$optimization['key_cache_slabs']}
518 2cbcc256 Warren Baker
outgoing-range: 4096
519 f20afeb6 Warren Baker
{$optimization['so_rcvbuf']}
520
{$anchor_file}
521 56a87b19 Warren Baker
prefetch: {$prefetch}
522
prefetch-key: {$prefetch_key}
523 a771a6ae Warren Baker
use-caps-for-id: {$use_caps}
524 84ec58b7 marjohn56
serve-expired: {$dns_record_cache}
525 7e9d72cf Viktor Gurov
aggressive-nsec: {$aggressivensec}
526 f20afeb6 Warren Baker
# Statistics
527
{$statistics}
528 7e8bfed2 jim-p
# TLS Configuration
529
{$tlsconfig}
530 f20afeb6 Warren Baker
# Interface IP(s) to bind to
531 1fa69c27 jim-p
{$bindintcfg}
532 6374fb57 Warren Baker
{$outgoingints}
533 f20afeb6 Warren Baker
# DNS Rebinding
534
{$private_addr}
535
{$private_domains}
536 dc104520 Viktor G
{$dns64_conf}
537 f20afeb6 Warren Baker
538 4e8e8cc8 Warren Baker
# Access lists
539 1548bd35 Phil Davis
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
540 4e8e8cc8 Warren Baker
541 f20afeb6 Warren Baker
# Static host entries
542 1548bd35 Phil Davis
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
543 f20afeb6 Warren Baker
544 b3977493 Renato Botelho
# dhcp lease entries
545 1548bd35 Phil Davis
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
546 b3977493 Renato Botelho
547 203b1110 Lorenz Schori
{$openvpn_clients_conf}
548 0cc17a06 Lorenz Schori
549 f20afeb6 Warren Baker
# Domain overrides
550 1548bd35 Phil Davis
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
551 be5aa310 Warren Baker
{$forward_conf}
552
553 f20afeb6 Warren Baker
{$custom_options}
554
555
###
556
# Remote Control Config
557
###
558 1548bd35 Phil Davis
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
559 241c4b58 BBcan177
{$python_module}
560 f20afeb6 Warren Baker
561
EOD;
562
563 932711c7 Matt Smith
	return $unboundconf;
564 f20afeb6 Warren Baker
}
565
566 1548bd35 Phil Davis
function unbound_remote_control_setup($cfgsubdir = "") {
567 fe9d4894 Renato Botelho
	global $g;
568 f20afeb6 Warren Baker
569 4b70a200 jim-p
	if (!file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") ||
570
	    (filesize("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") == 0) ||
571
	    !file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key")) {
572 fe9d4894 Renato Botelho
		$remotcfg = <<<EOF
573 f20afeb6 Warren Baker
remote-control:
574 fe9d4894 Renato Botelho
	control-enable: yes
575
	control-interface: 127.0.0.1
576
	control-port: 953
577 1548bd35 Phil Davis
	server-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.key"
578
	server-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.pem"
579
	control-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key"
580
	control-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.pem"
581 56a87b19 Warren Baker
582 f20afeb6 Warren Baker
EOF;
583
584 1548bd35 Phil Davis
		create_unbound_chroot_path($cfgsubdir);
585
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
586 f20afeb6 Warren Baker
587 fe9d4894 Renato Botelho
		// Generate our keys
588 1548bd35 Phil Davis
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
589 f20afeb6 Warren Baker
590 fe9d4894 Renato Botelho
	}
591 56a87b19 Warren Baker
}
592 f20afeb6 Warren Baker
593
function sync_unbound_service() {
594 fe9d4894 Renato Botelho
	global $config, $g;
595
596 e318d592 Phil Davis
	create_unbound_chroot_path();
597 fe9d4894 Renato Botelho
598
	// Configure our Unbound service
599
	do_as_unbound_user("unbound-anchor");
600
	unbound_remote_control_setup();
601
	unbound_generate_config();
602
	do_as_unbound_user("start");
603
	require_once("service-utils.inc");
604 751533a2 Phil Davis
	if (is_service_running("unbound")) {
605 fe9d4894 Renato Botelho
		do_as_unbound_user("restore_cache");
606 751533a2 Phil Davis
	}
607 f20afeb6 Warren Baker
608
}
609
610
function unbound_acl_id_used($id) {
611 fe9d4894 Renato Botelho
	global $config;
612 f20afeb6 Warren Baker
613 751533a2 Phil Davis
	if (is_array($config['unbound']['acls'])) {
614
		foreach ($config['unbound']['acls'] as & $acls) {
615
			if ($id == $acls['aclid']) {
616 fe9d4894 Renato Botelho
				return true;
617 751533a2 Phil Davis
			}
618
		}
619
	}
620 f20afeb6 Warren Baker
621 fe9d4894 Renato Botelho
	return false;
622 f20afeb6 Warren Baker
}
623
624
function unbound_get_next_id() {
625 fe9d4894 Renato Botelho
	$aclid = 0;
626 751533a2 Phil Davis
	while (unbound_acl_id_used($aclid)) {
627 fe9d4894 Renato Botelho
		$aclid++;
628 751533a2 Phil Davis
	}
629 fe9d4894 Renato Botelho
	return $aclid;
630 f20afeb6 Warren Baker
}
631
632
// Execute commands as the user unbound
633 1548bd35 Phil Davis
function do_as_unbound_user($cmd, $param1 = "") {
634 fe9d4894 Renato Botelho
	global $g;
635
636
	switch ($cmd) {
637 751533a2 Phil Davis
		case "start":
638
			mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
639
			break;
640
		case "stop":
641 495bfb5d Viktor G
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf stop'", true);
642 751533a2 Phil Davis
			break;
643
		case "reload":
644 495bfb5d Viktor G
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf reload'", true);
645 751533a2 Phil Davis
			break;
646
		case "unbound-anchor":
647 1548bd35 Phil Davis
			$root_key_file = "{$g['unbound_chroot_path']}{$param1}/root.key";
648 4eeb2809 Chris Buechler
			// sanity check root.key because unbound-anchor will fail without manual removal otherwise. redmine #5334
649 1548bd35 Phil Davis
			if (file_exists($root_key_file)) {
650
				$rootkeycheck = mwexec("/usr/bin/grep 'autotrust trust anchor file' {$root_key_file}", true);
651 4eeb2809 Chris Buechler
				if ($rootkeycheck != "0") {
652 1548bd35 Phil Davis
					log_error("Unbound {$root_key_file} file is corrupt, removing and recreating.");
653
					unlink_if_exists($root_key_file);
654 4eeb2809 Chris Buechler
				}
655
			}
656 495bfb5d Viktor G
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-anchor -a {$root_key_file}'", true);
657 1548bd35 Phil Davis
			// Only sync the file if this is the real (default) one, not a test one.
658
			if ($param1 == "") {
659 c5663bf5 Renato Botelho
				//pfSense_fsync($root_key_file);
660 1548bd35 Phil Davis
			}
661 751533a2 Phil Davis
			break;
662
		case "unbound-control-setup":
663 495bfb5d Viktor G
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}{$param1}'", true);
664 751533a2 Phil Davis
			break;
665
		default:
666
			break;
667 fe9d4894 Renato Botelho
	}
668 f20afeb6 Warren Baker
}
669
670 1548bd35 Phil Davis
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
671 fe9d4894 Renato Botelho
	global $config, $g;
672
673
	$domains = $config['unbound']['domainoverrides'];
674
675
	$sorted_domains = msort($domains, "domain");
676
	$result = array();
677 f39ba24b jim-p
	$tls_domains = array();
678 7e8bfed2 jim-p
	$tls_hostnames = array();
679 751533a2 Phil Davis
	foreach ($sorted_domains as $domain) {
680 fe9d4894 Renato Botelho
		$domain_key = current($domain);
681 751533a2 Phil Davis
		if (!isset($result[$domain_key])) {
682 fe9d4894 Renato Botelho
			$result[$domain_key] = array();
683 751533a2 Phil Davis
		}
684 fe9d4894 Renato Botelho
		$result[$domain_key][] = $domain['ip'];
685 f39ba24b jim-p
		/* If any entry for a domain has TLS set, it will be active for all entries. */
686
		if (isset($domain['forward_tls_upstream'])) {
687
			$tls_domains[] = $domain_key;
688 7e8bfed2 jim-p
			$tls_hostnames[$domain['ip']] = $domain['tls_hostname'];
689 f39ba24b jim-p
		}
690 fe9d4894 Renato Botelho
	}
691
692
	// Domain overrides that have multiple entries need multiple stub-addr: added
693
	$domain_entries = "";
694 751533a2 Phil Davis
	foreach ($result as $domain=>$ips) {
695 984abd66 Phil Davis
		if ($pvt_rev == "private") {
696 fe9d4894 Renato Botelho
			$domain_entries .= "private-domain: \"$domain\"\n";
697
			$domain_entries .= "domain-insecure: \"$domain\"\n";
698 984abd66 Phil Davis
		} else if ($pvt_rev == "reverse") {
699 8673ae11 Viktor G
			if (preg_match("/.+\.(in-addr|ip6)\.arpa\.?$/", $domain)) {
700 984abd66 Phil Davis
				$domain_entries .= "local-zone: \"$domain\" typetransparent\n";
701
			}
702 fe9d4894 Renato Botelho
		} else {
703 7e8bfed2 jim-p
			$use_tls = in_array($domain, $tls_domains);
704 0bde07b7 Chris Buechler
			$domain_entries .= "forward-zone:\n";
705 fe9d4894 Renato Botelho
			$domain_entries .= "\tname: \"$domain\"\n";
706 f39ba24b jim-p
			$fwdport = "";
707
			/* Enable TLS forwarding for this domain if needed. */
708 7e8bfed2 jim-p
			if ($use_tls) {
709 f39ba24b jim-p
				$domain_entries .= "\tforward-tls-upstream: yes\n";
710
				$fwdport = "@853";
711
			}
712 751533a2 Phil Davis
			foreach ($ips as $ip) {
713 7e8bfed2 jim-p
				$fwdhost = "";
714 f39ba24b jim-p
				/* If an IP address already contains a port specification, do not add another. */
715
				if (strstr($ip, '@') !== false) {
716
					$fwdport = "";
717
				}
718 7e8bfed2 jim-p
				if ($use_tls && array_key_exists($ip, $tls_hostnames)) {
719
					$fwdhost = "#{$tls_hostnames[$ip]}";
720
				}
721
				$domain_entries .= "\tforward-addr: {$ip}{$fwdport}{$fwdhost}\n";
722 751533a2 Phil Davis
			}
723 fe9d4894 Renato Botelho
		}
724
	}
725
726 751533a2 Phil Davis
	if ($pvt_rev != "") {
727 fe9d4894 Renato Botelho
		return $domain_entries;
728 751533a2 Phil Davis
	} else {
729 1548bd35 Phil Davis
		create_unbound_chroot_path($cfgsubdir);
730
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
731 e318d592 Phil Davis
	}
732 f20afeb6 Warren Baker
}
733
734 2c3b9ac5 jim-p
function unbound_generate_zone_data($domain, $hosts, &$added_ptr, $zone_type = "transparent", $write_domain_zone_declaration = false, $always_add_short_names = false) {
735 4541f84d jim-p
	global $config;
736 2c3b9ac5 jim-p
	if ($write_domain_zone_declaration) {
737 4541f84d jim-p
		$zone_data = "local-zone: \"{$domain}.\" {$zone_type}\n";
738
	} else {
739
		$zone_data = "";
740 49d9b45f Robbert Rijkse
	}
741
	foreach ($hosts as $host) {
742
		if (is_ipaddrv4($host['ipaddr'])) {
743
			$type = 'A';
744
		} else if (is_ipaddrv6($host['ipaddr'])) {
745
			$type = 'AAAA';
746
		} else {
747
			continue;
748
		}
749
		if (!$added_ptr[$host['ipaddr']]) {
750 4541f84d jim-p
			$zone_data .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
751 49d9b45f Robbert Rijkse
			$added_ptr[$host['ipaddr']] = true;
752 06266c34 Lorenz Schori
		}
753 4541f84d jim-p
		/* For the system localhost entry, write an entry for just the hostname. */
754
		if ((($host['name'] == "localhost") && ($domain == $config['system']['domain'])) || $always_add_short_names) {
755
			$zone_data .= "local-data: \"{$host['name']}. {$type} {$host['ipaddr']}\"\n";
756
		}
757
		/* Redirect zones must have a zone declaration that matches the
758
		 * local-data record exactly, it cannot have entries "under" the
759
		 * domain.
760
		 */
761
		if ($zone_type == "redirect") {
762
			$zone_data .= "local-zone: \"{$host['fqdn']}.\" {$zone_type}\n";;
763
		}
764
		$zone_data .= "local-data: \"{$host['fqdn']}. {$type} {$host['ipaddr']}\"\n";
765
	}
766
	return $zone_data;
767
}
768
769
function unbound_add_host_entries($cfgsubdir = "") {
770 283f9e8c jim-p
	global $config, $g, $nooutifs;
771 4541f84d jim-p
772
	$hosts = system_hosts_entries($config['unbound']);
773
774
	/* Pass 1: Build domain list and hosts inside domains */
775
	$hosts_by_domain = array();
776
	foreach ($hosts as $host) {
777
		if (!array_key_exists($host['domain'], $hosts_by_domain)) {
778
			$hosts_by_domain[$host['domain']] = array();
779
		}
780
		$hosts_by_domain[$host['domain']][] = $host;
781
	}
782
783
	$added_ptr = array();
784
	/* Build local zone data */
785
	// Check if auto add host entries is not set
786
	$system_domain_local_zone_type = "transparent";
787
	if (!isset($config['unbound']['disable_auto_added_host_entries'])) {
788
		// Make sure the config setting is a valid unbound local zone type.  If not use "transparent".
789
		if (array_key_exists($config['unbound']['system_domain_local_zone_type'], unbound_local_zone_types())) {
790
			$system_domain_local_zone_type = $config['unbound']['system_domain_local_zone_type'];
791
		}
792
	}
793 283f9e8c jim-p
	/* disable recursion if the selected outgoing interfaces are available,
794
	 * see https://redmine.pfsense.org/issues/12460 */
795
	if ($nooutifs && isset($config['unbound']['strictout'])) {
796
		$unbound_entries = "local-zone: \".\" refuse\n";
797
	}
798 4541f84d jim-p
	/* Add entries for the system domain before all others */
799
	if (array_key_exists($config['system']['domain'], $hosts_by_domain)) {
800
		$unbound_entries .= unbound_generate_zone_data($config['system']['domain'],
801
					$hosts_by_domain[$config['system']['domain']],
802
					$added_ptr,
803
					$system_domain_local_zone_type,
804
					true);
805
		/* Unset this so it isn't processed again by the loop below. */
806
		unset($hosts_by_domain[$config['system']['domain']]);
807
	}
808
809
	/* Build zone data for other domain */
810
	foreach ($hosts_by_domain as $domain => $hosts) {
811
		$unbound_entries .= unbound_generate_zone_data($domain,
812
					$hosts,
813
					$added_ptr,
814
					"transparent",
815
					false,
816
					isset($config['unbound']['always_add_short_names']));
817 fe9d4894 Renato Botelho
	}
818
819
	// Write out entries
820 1548bd35 Phil Davis
	create_unbound_chroot_path($cfgsubdir);
821
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
822 b3977493 Renato Botelho
823
	/* dhcpleases will write to this config file, make sure it exists */
824 1548bd35 Phil Davis
	@touch("{$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf");
825 f20afeb6 Warren Baker
}
826
827 56a87b19 Warren Baker
function unbound_control($action) {
828 fe9d4894 Renato Botelho
	global $config, $g;
829
830
	$cache_dumpfile = "/var/tmp/unbound_cache";
831
832
	switch ($action) {
833
	case "start":
834
		// Start Unbound
835
		if ($config['unbound']['enable'] == "on") {
836 751533a2 Phil Davis
			if (!is_service_running("unbound")) {
837 fe9d4894 Renato Botelho
				do_as_unbound_user("start");
838 751533a2 Phil Davis
			}
839 fe9d4894 Renato Botelho
		}
840
		break;
841
	case "stop":
842 751533a2 Phil Davis
		if ($config['unbound']['enable'] == "on") {
843 fe9d4894 Renato Botelho
			do_as_unbound_user("stop");
844 751533a2 Phil Davis
		}
845 fe9d4894 Renato Botelho
		break;
846
	case "reload":
847 751533a2 Phil Davis
		if ($config['unbound']['enable'] == "on") {
848 fe9d4894 Renato Botelho
			do_as_unbound_user("reload");
849 751533a2 Phil Davis
		}
850 fe9d4894 Renato Botelho
		break;
851
	case "dump_cache":
852
		// Dump Unbound's Cache
853 751533a2 Phil Davis
		if ($config['unbound']['dumpcache'] == "on") {
854 fe9d4894 Renato Botelho
			do_as_unbound_user("dump_cache");
855 751533a2 Phil Davis
		}
856 fe9d4894 Renato Botelho
		break;
857
	case "restore_cache":
858
		// Restore Unbound's Cache
859
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
860 751533a2 Phil Davis
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
861 fe9d4894 Renato Botelho
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
862 751533a2 Phil Davis
			}
863 fe9d4894 Renato Botelho
		}
864
		break;
865
	default:
866
		break;
867
868
	}
869 56a87b19 Warren Baker
}
870
871
// Generation of Unbound statistics
872
function unbound_statistics() {
873 fe9d4894 Renato Botelho
	global $config;
874
875
	if ($config['stats'] == "on") {
876
		$stats_interval = $config['unbound']['stats_interval'];
877
		$cumulative_stats = $config['cumulative_stats'];
878 751533a2 Phil Davis
		if ($config['extended_stats'] == "on") {
879 fe9d4894 Renato Botelho
			$extended_stats = "yes";
880 751533a2 Phil Davis
		} else {
881 fe9d4894 Renato Botelho
			$extended_stats = "no";
882 751533a2 Phil Davis
		}
883 fe9d4894 Renato Botelho
	} else {
884
		$stats_interval = "0";
885
		$cumulative_stats = "no";
886
		$extended_stats = "no";
887
	}
888
	/* XXX To do - add RRD graphs */
889
	$stats = <<<EOF
890 56a87b19 Warren Baker
# Unbound Statistics
891
statistics-interval: {$stats_interval}
892
extended-statistics: yes
893
statistics-cumulative: yes
894
895
EOF;
896
897 fe9d4894 Renato Botelho
	return $stats;
898 56a87b19 Warren Baker
}
899
900 8fccab67 Warren Baker
// Unbound Access lists
901 1548bd35 Phil Davis
function unbound_acls_config($cfgsubdir = "") {
902 fe9d4894 Renato Botelho
	global $g, $config;
903
904 f8f5ba1a Chris Buechler
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
905 0266efa6 doktornotor
		$aclcfg = "access-control: 127.0.0.1/32 allow_snoop\n";
906
		$aclcfg .= "access-control: ::1 allow_snoop\n";
907 f8f5ba1a Chris Buechler
		// Add our networks for active interfaces including localhost
908 8c2a5a73 Phil Davis
		if (!empty($config['unbound']['active_interface'])) {
909 f8f5ba1a Chris Buechler
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
910 751533a2 Phil Davis
			if (in_array("all", $active_interfaces)) {
911 80075b9e Chris Buechler
				$active_interfaces = get_configured_interface_with_descr();
912 751533a2 Phil Davis
			}
913
		} else {
914 f8f5ba1a Chris Buechler
			$active_interfaces = get_configured_interface_with_descr();
915 751533a2 Phil Davis
		}
916
917 0c3fff67 jim-p
		$aclnets = array();
918 751533a2 Phil Davis
		foreach ($active_interfaces as $ubif => $ifdesc) {
919 f8f5ba1a Chris Buechler
			$ifip = get_interface_ip($ubif);
920
			if (is_ipaddrv4($ifip)) {
921
				// IPv4 is handled via NAT networks below
922
			}
923
			$ifip = get_interface_ipv6($ubif);
924
			if (is_ipaddrv6($ifip)) {
925 f302a333 Jean Cyr
				if (!is_linklocal($ifip)) {
926
					$subnet_bits = get_interface_subnetv6($ubif);
927
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
928 751533a2 Phil Davis
					// only add LAN-type interfaces
929
					if (!interface_has_gateway($ubif)) {
930 0c3fff67 jim-p
						$aclnets[] = "{$subnet_ip}/{$subnet_bits}";
931 751533a2 Phil Davis
					}
932 f302a333 Jean Cyr
				}
933 f8f5ba1a Chris Buechler
				// add for IPv6 static routes to local networks
934
				// for safety, we include only routes reachable on an interface with no
935 751533a2 Phil Davis
				// gateway specified - read: not an Internet connection.
936 cf08b49e Phil Davis
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
937 f8f5ba1a Chris Buechler
				foreach ($static_routes as $route) {
938
					if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
939
						// route is on this interface, interface doesn't have gateway, add it
940 0c3fff67 jim-p
						$aclnets[] = $route['network'];
941 f8f5ba1a Chris Buechler
					}
942 e3045c51 Chris Buechler
				}
943
			}
944 fe9d4894 Renato Botelho
		}
945 751533a2 Phil Davis
946 79eef195 Viktor Gurov
		// OpenVPN IPv6 Tunnel Networks
947
		foreach (array('openvpn-client', 'openvpn-server') as $ovpnentry) {
948
			if (is_array($config['openvpn'][$ovpnentry])) {
949
				foreach ($config['openvpn'][$ovpnentry] as $ovpnent) {
950
					if (!isset($ovpnent['disable']) && !empty($ovpnent['tunnel_networkv6'])) {
951 e9705a77 jim-p
						$aclnets[] = implode('/', openvpn_gen_tunnel_network($ovpnent['tunnel_networkv6']));
952 79eef195 Viktor Gurov
					}
953
				}
954
			}
955
		}
956
		// IPsec Mobile Virtual IPv6 Address Pool
957
		if ((isset($config['ipsec']['client']['enable'])) &&
958
		    (!empty($config['ipsec']['client']['pool_address_v6'])) &&
959
		    (!empty($config['ipsec']['client']['pool_netbits_v6']))) {
960 0c3fff67 jim-p
			$aclnets[] = "{$config['ipsec']['client']['pool_address_v6']}/{$config['ipsec']['client']['pool_netbits_v6']}";
961 79eef195 Viktor Gurov
		}
962
963 f8f5ba1a Chris Buechler
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
964
		if (empty($FilterIflist)) {
965
			filter_generate_optcfg_array();
966
		}
967 0c3fff67 jim-p
		$aclnets = array_merge($aclnets, filter_nat_rules_automatic_tonathosts());
968
969
		/* Automatic ACL networks deduplication and sorting
970
		 * https://redmine.pfsense.org/issues/11309 */
971
		$aclnets4 = array();
972
		$aclnets6 = array();
973
		foreach (array_unique($aclnets) as $acln) {
974
			if (is_v4($acln)) {
975
				$aclnets4[] = $acln;
976
			} else {
977
				$aclnets6[] = $acln;
978
			}
979
		}
980
		/* ipcmp only supports IPv4 */
981
		usort($aclnets4, "ipcmp");
982
		sort($aclnets6);
983
984
		foreach (array_merge($aclnets4, $aclnets6) as $acln) {
985 e9705a77 jim-p
			/* Do not form an invalid directive with an empty address */
986
			if (empty($acln)) {
987
				continue;
988
			}
989 0c3fff67 jim-p
			$aclcfg .= "access-control: {$acln} allow \n";
990 751533a2 Phil Davis
		}
991 3bdf2a70 Chris Buechler
	}
992 fe9d4894 Renato Botelho
993
	// Configure the custom ACLs
994
	if (is_array($config['unbound']['acls'])) {
995 751533a2 Phil Davis
		foreach ($config['unbound']['acls'] as $unbound_acl) {
996 fe9d4894 Renato Botelho
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
997 751533a2 Phil Davis
			foreach ($unbound_acl['row'] as $network) {
998
				if ($unbound_acl['aclaction'] == "allow snoop") {
999 fe9d4894 Renato Botelho
					$unbound_acl['aclaction'] = "allow_snoop";
1000 6a827f69 doktornotor
				} elseif ($unbound_acl['aclaction'] == "deny nonlocal") {
1001
					$unbound_acl['aclaction'] = "deny_non_local";
1002
				} elseif ($unbound_acl['aclaction'] == "refuse nonlocal") {
1003
					$unbound_acl['aclaction'] = "refuse_non_local";
1004 751533a2 Phil Davis
				}
1005 fe9d4894 Renato Botelho
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
1006
			}
1007
		}
1008
	}
1009
	// Write out Access list
1010 1548bd35 Phil Davis
	create_unbound_chroot_path($cfgsubdir);
1011
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
1012 58d00e65 Warren Baker
1013 8fccab67 Warren Baker
}
1014
1015 f6248774 Warren Baker
// Generate hosts and reload services
1016
function unbound_hosts_generate() {
1017 fe9d4894 Renato Botelho
	// Generate our hosts file
1018
	unbound_add_host_entries();
1019 f6248774 Warren Baker
1020 fe9d4894 Renato Botelho
	// Reload our service to read the updates
1021
	unbound_control("reload");
1022 f6248774 Warren Baker
}
1023
1024 9a83872f NOYB
// Array of valid unbound local zone types
1025
function unbound_local_zone_types() {
1026
	return array(
1027
		"deny" => gettext("Deny"),
1028
		"refuse" => gettext("Refuse"),
1029
		"static" => gettext("Static"),
1030
		"transparent" => gettext("Transparent"),
1031
		"typetransparent" => gettext("Type Transparent"),
1032
		"redirect" => gettext("Redirect"),
1033
		"inform" => gettext("Inform"),
1034
		"inform_deny" => gettext("Inform Deny"),
1035
		"nodefault" => gettext("No Default")
1036
	);
1037
}
1038
1039 09d529a6 Viktor G
// Autoconfig EDNS buffer size
1040
function unbound_auto_ednsbufsize() {
1041
	global $config;
1042
1043
	$active_ipv6_inf = false;
1044
	if ($config['unbound']['active_interface'] != 'all') {
1045
		$active_interfaces = explode(",", $config['unbound']['active_interface']);
1046
	} else {
1047
		$active_interfaces = get_configured_interface_list();
1048
	}
1049
1050
	$min_mtu = get_interface_mtu(get_real_interface($active_interfaces[0]));
1051
	foreach ($active_interfaces as $ubif) {
1052
		$ubif_mtu = get_interface_mtu(get_real_interface($ubif));
1053
		if (get_interface_ipv6($ubif)) {
1054
			$active_ipv6_inf = true;
1055
		}
1056
		if ($ubif_mtu < $min_mtu) {
1057
			$min_mtu = $ubif_mtu;
1058
		}
1059
	}
1060
1061
	// maximum IPv4 + UDP header = 68 bytes
1062
	$min_mtu = $min_mtu - 68;
1063
1064
	if (($min_mtu < 1232) && $active_ipv6_inf) {
1065
		$min_mtu = 1232;
1066
	} elseif ($min_mtu < 512) {
1067
		$min_mtu = 512;
1068
	}	
1069
1070
	return $min_mtu;
1071
}
1072
1073 3f0c20c3 Renato Botelho
?>