Project

General

Profile

Download (32.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * unbound.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2015 Warren Baker <warren@percol8.co.za>
7
 * Copyright (c) 2015-2016 Electric Sheep Fencing
8
 * Copyright (c) 2015-2021 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of 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
/* include all configuration functions */
29
require_once("config.inc");
30
require_once("functions.inc");
31
require_once("filter.inc");
32
require_once("shaper.inc");
33
require_once("interfaces.inc");
34
require_once("util.inc");
35

    
36
function create_unbound_chroot_path($cfgsubdir = "") {
37
	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
	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
}
55

    
56
/* Optimize Unbound for environment */
57
function unbound_optimization() {
58
	global $config;
59

    
60
	$optimization_settings = array();
61

    
62
	/*
63
	 * 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
	if ($numprocs > 1) {
68
		$optimization['number_threads'] = "num-threads: {$numprocs}";
69
		$optimize_num = pow(2, floor(log($numprocs, 2)));
70
	} else {
71
		$optimization['number_threads'] = "num-threads: 1";
72
		$optimize_num = 4;
73
	}
74

    
75
	// Slabs to help reduce lock contention.
76
	$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

    
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
	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
				$so = floor((intval($tunable['value'])/1024/1024)-4);
89
				// Check to ensure that the number is not a negative
90
				if ($so >= 4) {
91
					// Limit to 32MB, users might set maxsockbuf very high for other reasons.
92
					// We do not want unbound to fail because of that.
93
					$so = min($so, 32);
94
					$optimization['so_rcvbuf'] = "so-rcvbuf: {$so}m";
95
				} else {
96
					unset($optimization['so_rcvbuf']);
97
				}
98
			}
99
		}
100
	}
101
	// Safety check in case kern.ipc.maxsockbuf is not available.
102
	if (!isset($optimization['so_rcvbuf'])) {
103
		$optimization['so_rcvbuf'] = "#so-rcvbuf: 4m";
104
	}
105

    
106
	return $optimization;
107

    
108
}
109

    
110
function test_unbound_config($unboundcfg, &$output) {
111
	global $g;
112

    
113
	$cfgsubdir = "/test";
114
	$cfgdir = "{$g['unbound_chroot_path']}{$cfgsubdir}";
115
	rmdir_recursive($cfgdir);
116

    
117
	unbound_generate_config($unboundcfg, $cfgsubdir);
118
	unbound_remote_control_setup($cfgsubdir);
119
	do_as_unbound_user("unbound-anchor", $cfgsubdir);
120

    
121
	// Copy the Python files to the test folder
122
	if (isset($unboundcfg['python']) && !empty($unboundcfg['python_script'])) {
123
		$python_files = glob("{$g['unbound_chroot_path']}/{$unboundcfg['python_script']}.*");
124
		if (is_array($python_files)) {
125
			foreach ($python_files as $file) {
126
				$file = pathinfo($file, PATHINFO_BASENAME);
127
				@copy("{$g['unbound_chroot_path']}/{$file}", "{$cfgdir}/{$file}");
128
			}
129
		}
130
	}
131

    
132
	$rv = 0;
133
	exec("/usr/local/sbin/unbound-checkconf {$cfgdir}/unbound.conf 2>&1",
134
	    $output, $rv);
135

    
136
	if ($rv == 0) {
137
		rmdir_recursive($cfgdir);
138
	}
139

    
140
	return $rv;
141
}
142

    
143

    
144
function unbound_generate_config($unboundcfg = NULL, $cfgsubdir = "") {
145
	global $g;
146

    
147
	$unboundcfgtxt = unbound_generate_config_text($unboundcfg, $cfgsubdir);
148

    
149
	// Configure static Host entries
150
	unbound_add_host_entries($cfgsubdir);
151

    
152
	// Configure Domain Overrides
153
	unbound_add_domain_overrides("", $cfgsubdir);
154

    
155
	// Configure Unbound access-lists
156
	unbound_acls_config($cfgsubdir);
157

    
158
	create_unbound_chroot_path($cfgsubdir);
159
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound.conf", $unboundcfgtxt);
160
}
161

    
162

    
163
function unbound_generate_config_text($unboundcfg = NULL, $cfgsubdir = "") {
164

    
165
	global $config, $g;
166
	if (is_null($unboundcfg)) {
167
		$unboundcfg = $config['unbound'];
168
	}
169

    
170
	// Setup optimization
171
	$optimization = unbound_optimization();
172

    
173
	$module_config = '';
174

    
175
	// Setup Python module (pre validator)
176
	if (isset($unboundcfg['python']) && !empty($unboundcfg['python_script']) && $unboundcfg['python_order'] == 'pre_validator') {
177
		$module_config .= 'python ';
178
	}
179

    
180
	// Setup DNS64 support
181
	if (isset($unboundcfg['dns64'])) {
182
		$module_config .= 'dns64 ';
183
		$dns64_conf = 'dns64-prefix: ';
184
		if (is_subnetv6($unboundcfg['dns64prefix'] . '/' . $unboundcfg['dns64netbits'])) {
185
			$dns64_conf .= $unboundcfg['dns64prefix'] . '/' . $unboundcfg['dns64netbits'];
186
		} else {
187
			$dns64_conf .= '64:ff9b::/96';
188
		}
189
	}
190

    
191
	// Setup DNSSEC support
192
	if (isset($unboundcfg['dnssec'])) {
193
		$module_config .= 'validator ';
194
		$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}{$cfgsubdir}/root.key";
195
	}
196

    
197
	// Setup Python module (post validator)
198
	if (isset($unboundcfg['python']) && !empty($unboundcfg['python_script']) && $unboundcfg['python_order'] == 'post_validator') {
199
		$module_config .= 'python ';
200
	}
201

    
202
	$module_config .= 'iterator';
203

    
204
	// Setup DNS Rebinding
205
	if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
206
		// Private-addresses for DNS Rebinding
207
		$private_addr = <<<EOF
208
# For DNS Rebinding prevention
209
private-address: 127.0.0.0/8
210
private-address: 10.0.0.0/8
211
private-address: ::ffff:a00:0/104
212
private-address: 172.16.0.0/12
213
private-address: ::ffff:ac10:0/108
214
private-address: 169.254.0.0/16
215
private-address: ::ffff:a9fe:0/112
216
private-address: 192.168.0.0/16
217
private-address: ::ffff:c0a8:0/112
218
private-address: fd00::/8
219
private-address: fe80::/10
220
EOF;
221
	}
222

    
223
	// Determine interfaces where unbound will bind
224
	$tlsport = is_numeric($unboundcfg['tlsport']) ? $unboundcfg['tlsport'] : "853";
225
	$bindintcfg = "";
226
	$bindints = array();
227
	$active_interfaces = explode(",", $unboundcfg['active_interface']);
228
	if (empty($unboundcfg['active_interface']) || in_array("all", $active_interfaces, true)) {
229
		$bindints[] = "0.0.0.0";
230
		$bindints[] = "::0";
231
		$bindintcfg .= "interface-automatic: " . (isset($unboundcfg['enablessl']) ? "no" : "yes") . "\n";
232
	} else {
233
		foreach ($active_interfaces as $ubif) {
234
			/* Do not bind to disabled/nocarrier interfaces,
235
			 * see https://redmine.pfsense.org/issues/11087 */
236
			$ifinfo = get_interface_info($ubif);
237
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
238
				continue;
239
			}
240
			if (is_ipaddr($ubif)) {
241
				$bindints[] = $ubif;
242
			} else {
243
				$intip = get_interface_ip($ubif);
244
				if (is_ipaddrv4($intip)) {
245
					$bindints[] = $intip;
246
				}
247
				$intip = get_interface_ipv6($ubif);
248
				if (is_ipaddrv6($intip)) {
249
					$bindints[] = $intip;
250
				}
251
			}
252
		}
253
	}
254
	foreach ($bindints as $bindint) {
255
		$bindintcfg .= "interface: {$bindint}\n";
256
		if (isset($unboundcfg['enablessl'])) {
257
			$bindintcfg .= "interface: {$bindint}@{$tlsport}\n";
258
		}
259
	}
260

    
261
	// TLS Configuration
262
	$tlsconfig = "tls-cert-bundle: \"/etc/ssl/cert.pem\"\n";
263

    
264
	if (isset($unboundcfg['enablessl'])) {
265
		$tlscert_path = "{$g['unbound_chroot_path']}/sslcert.crt";
266
		$tlskey_path = "{$g['unbound_chroot_path']}/sslcert.key";
267

    
268
		// Enable SSL/TLS on the chosen or default port
269
		$tlsconfig .= "tls-port: {$tlsport}\n";
270

    
271
		// Lookup CA and Server Cert
272
		$cert = lookup_cert($unboundcfg['sslcertref']);
273
		$ca = ca_chain($cert);
274
		$cert_chain = base64_decode($cert['crt']);
275
		if (!empty($ca)) {
276
			$cert_chain .= "\n" . $ca;
277
		}
278

    
279
		// Write CA and Server Cert
280
		file_put_contents($tlscert_path, $cert_chain);
281
		chmod($tlscert_path, 0644);
282
		file_put_contents($tlskey_path, base64_decode($cert['prv']));
283
		chmod($tlskey_path, 0600);
284

    
285
		// Add config for CA and Server Cert
286
		$tlsconfig .= "tls-service-pem: \"{$tlscert_path}\"\n";
287
		$tlsconfig .= "tls-service-key: \"{$tlskey_path}\"\n";
288
	}
289

    
290
	// Determine interfaces to run on
291
	$outgoingints = "";
292
	if (!empty($unboundcfg['outgoing_interface'])) {
293
		$outgoingints = "# Outgoing interfaces to be used\n";
294
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
295
		foreach ($outgoing_interfaces as $outif) {
296
			$ifinfo = get_interface_info($outif);
297
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
298
				continue;
299
			}
300
			$outip = get_interface_ip($outif);
301
			if (is_ipaddr($outip)) {
302
				$outgoingints .= "outgoing-interface: $outip\n";
303
			}
304
			$outip = get_interface_ipv6($outif);
305
			if (is_ipaddrv6($outip)) {
306
				$outgoingints .= "outgoing-interface: $outip\n";
307
			}
308
		}
309
	}
310

    
311
	// Allow DNS Rebind for forwarded domains
312
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
313
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
314
			$private_domains = "# Set private domains in case authoritative name server returns a Private IP address\n";
315
			$private_domains .= unbound_add_domain_overrides("private");
316
		}
317
		$reverse_zones .= unbound_add_domain_overrides("reverse");
318
	}
319

    
320
	// Configure Unbound statistics
321
	$statistics = unbound_statistics();
322

    
323
	// Add custom Unbound options
324
	if ($unboundcfg['custom_options']) {
325
		$custom_options_source = explode("\n", base64_decode($unboundcfg['custom_options']));
326
		$custom_options = "# Unbound custom options\n";
327
		foreach ($custom_options_source as $ent) {
328
			$custom_options .= $ent."\n";
329
		}
330
	}
331

    
332
	// Server configuration variables
333
	$port = (is_port($unboundcfg['port'])) ? $unboundcfg['port'] : "53";
334
	$hide_identity = isset($unboundcfg['hideidentity']) ? "yes" : "no";
335
	$hide_version = isset($unboundcfg['hideversion']) ? "yes" : "no";
336
	$ipv6_allow = isset($config['system']['ipv6allow']) ? "yes" : "no";
337
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
338
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
339
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
340
	$dns_record_cache = isset($unboundcfg['dnsrecordcache']) ? "yes" : "no";
341
	$aggressivensec = isset($unboundcfg['aggressivensec']) ? "yes" : "no";
342
	$outgoing_num_tcp = isset($unboundcfg['outgoing_num_tcp']) ? $unboundcfg['outgoing_num_tcp'] : "10";
343
	$incoming_num_tcp = isset($unboundcfg['incoming_num_tcp']) ? $unboundcfg['incoming_num_tcp'] : "10";
344
	if (empty($unboundcfg['edns_buffer_size']) || ($unboundcfg['edns_buffer_size'] == 'auto')) {
345
		$edns_buffer_size = unbound_auto_ednsbufsize();
346
	} else {
347
		$edns_buffer_size = $unboundcfg['edns_buffer_size'];
348
	}
349
	$num_queries_per_thread = (!empty($unboundcfg['num_queries_per_thread'])) ? $unboundcfg['num_queries_per_thread'] : "4096";
350
	$jostle_timeout = (!empty($unboundcfg['jostle_timeout'])) ? $unboundcfg['jostle_timeout'] : "200";
351
	$cache_max_ttl = (!empty($unboundcfg['cache_max_ttl'])) ? $unboundcfg['cache_max_ttl'] : "86400";
352
	$cache_min_ttl = (!empty($unboundcfg['cache_min_ttl'])) ? $unboundcfg['cache_min_ttl'] : "0";
353
	$infra_host_ttl = (!empty($unboundcfg['infra_host_ttl'])) ? $unboundcfg['infra_host_ttl'] : "900";
354
	$infra_cache_numhosts = (!empty($unboundcfg['infra_cache_numhosts'])) ? $unboundcfg['infra_cache_numhosts'] : "10000";
355
	$unwanted_reply_threshold = (!empty($unboundcfg['unwanted_reply_threshold'])) ? $unboundcfg['unwanted_reply_threshold'] : "0";
356
	if ($unwanted_reply_threshold == "disabled") {
357
		$unwanted_reply_threshold = "0";
358
	}
359
	$msg_cache_size = (!empty($unboundcfg['msgcachesize'])) ? $unboundcfg['msgcachesize'] : "4";
360
	$verbosity = isset($unboundcfg['log_verbosity']) ? $unboundcfg['log_verbosity'] : 1;
361
	$use_caps = isset($unboundcfg['use_caps']) ? "yes" : "no";
362

    
363
	if (isset($unboundcfg['regovpnclients'])) {
364
		$openvpn_clients_conf .=<<<EOD
365
# OpenVPN client entries
366
include: {$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf
367
EOD;
368
	} else {
369
		$openvpn_clients_conf = '';
370
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
371
	}
372

    
373
	// Set up forwarding if it is configured
374
	if (isset($unboundcfg['forwarding'])) {
375
		$dnsservers = get_dns_nameservers(false, true);
376
		if (!empty($dnsservers)) {
377
			$forward_conf .=<<<EOD
378
# Forwarding
379
forward-zone:
380
	name: "."
381

    
382
EOD;
383
			if (isset($unboundcfg['forward_tls_upstream'])) {
384
				$forward_conf .= "\tforward-tls-upstream: yes\n";
385
			}
386

    
387
			/* Build DNS server hostname list. See https://redmine.pfsense.org/issues/8602 */
388
			$dns_hostnames = array();
389
			$dnshost_counter = 1;
390
			while (isset($config["system"]["dns{$dnshost_counter}host"])) {
391
				$pconfig_dnshost_counter = $dnshost_counter - 1;
392
				if (!empty($config["system"]["dns{$dnshost_counter}host"]) &&
393
				    isset($config["system"]["dnsserver"][$pconfig_dnshost_counter]))
394
				$dns_hostnames[$config["system"]["dnsserver"][$pconfig_dnshost_counter]] = $config["system"]["dns{$dnshost_counter}host"];
395
				$dnshost_counter++;
396
			}
397

    
398
			foreach ($dnsservers as $dnsserver) {
399
				$fwdport = "";
400
				$fwdhost = "";
401
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
402
					if (isset($unboundcfg['forward_tls_upstream'])) {
403
						$fwdport = "@853";
404
						if (array_key_exists($dnsserver, $dns_hostnames)) {
405
							$fwdhost = "#{$dns_hostnames[$dnsserver]}";
406
						}
407
					}
408
					$forward_conf .= "\tforward-addr: {$dnsserver}{$fwdport}{$fwdhost}\n";
409
				}
410
			}
411
		}
412
	} else {
413
		$forward_conf = "";
414
	}
415

    
416
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
417
	$rrset_cache_size = $msg_cache_size * 2;
418

    
419
	/* QNAME Minimization. https://redmine.pfsense.org/issues/8028
420
	 * Unbound uses the British style in the option name so the internal option
421
	 * name follows that, but the user-visible descriptions follow US English.
422
	 */
423
	$qname_min = "";
424
	if (isset($unboundcfg['qname-minimisation'])) {
425
		$qname_min = "qname-minimisation: yes\n";
426
		if (isset($unboundcfg['qname-minimisation-strict'])) {
427
			$qname_min .= "qname-minimisation-strict: yes\n";
428
		}
429
	}
430

    
431
	$python_module = '';
432
	if (isset($unboundcfg['python']) && !empty($unboundcfg['python_script'])) {
433
		$python_path = '';
434
		if (!empty($cfgsubdir)) {
435
			$python_path = "{$g['unbound_chroot_path']}{$cfgsubdir}/";
436
		}
437
		$python_module = "\n# Python Module\npython:\npython-script: {$python_path}{$unboundcfg['python_script']}.py";
438
	}
439

    
440
	$unboundconf = <<<EOD
441
##########################
442
# Unbound Configuration
443
##########################
444

    
445
##
446
# Server configuration
447
##
448
server:
449
{$reverse_zones}
450
chroot: {$g['unbound_chroot_path']}
451
username: "unbound"
452
directory: "{$g['unbound_chroot_path']}"
453
pidfile: "/var/run/unbound.pid"
454
use-syslog: yes
455
port: {$port}
456
verbosity: {$verbosity}
457
hide-identity: {$hide_identity}
458
hide-version: {$hide_version}
459
harden-glue: yes
460
do-ip4: yes
461
do-ip6: {$ipv6_allow}
462
do-udp: yes
463
do-tcp: yes
464
do-daemonize: yes
465
module-config: "{$module_config}"
466
unwanted-reply-threshold: {$unwanted_reply_threshold}
467
num-queries-per-thread: {$num_queries_per_thread}
468
jostle-timeout: {$jostle_timeout}
469
infra-host-ttl: {$infra_host_ttl}
470
infra-cache-numhosts: {$infra_cache_numhosts}
471
outgoing-num-tcp: {$outgoing_num_tcp}
472
incoming-num-tcp: {$incoming_num_tcp}
473
edns-buffer-size: {$edns_buffer_size}
474
cache-max-ttl: {$cache_max_ttl}
475
cache-min-ttl: {$cache_min_ttl}
476
harden-dnssec-stripped: {$harden_dnssec_stripped}
477
msg-cache-size: {$msg_cache_size}m
478
rrset-cache-size: {$rrset_cache_size}m
479
{$qname_min}
480
{$optimization['number_threads']}
481
{$optimization['msg_cache_slabs']}
482
{$optimization['rrset_cache_slabs']}
483
{$optimization['infra_cache_slabs']}
484
{$optimization['key_cache_slabs']}
485
outgoing-range: 4096
486
{$optimization['so_rcvbuf']}
487
{$anchor_file}
488
prefetch: {$prefetch}
489
prefetch-key: {$prefetch_key}
490
use-caps-for-id: {$use_caps}
491
serve-expired: {$dns_record_cache}
492
aggressive-nsec: {$aggressivensec}
493
# Statistics
494
{$statistics}
495
# TLS Configuration
496
{$tlsconfig}
497
# Interface IP(s) to bind to
498
{$bindintcfg}
499
{$outgoingints}
500
# DNS Rebinding
501
{$private_addr}
502
{$private_domains}
503
{$dns64_conf}
504

    
505
# Access lists
506
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
507

    
508
# Static host entries
509
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
510

    
511
# dhcp lease entries
512
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
513

    
514
{$openvpn_clients_conf}
515

    
516
# Domain overrides
517
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
518
{$forward_conf}
519

    
520
{$custom_options}
521

    
522
###
523
# Remote Control Config
524
###
525
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
526
{$python_module}
527

    
528
EOD;
529

    
530
	return $unboundconf;
531
}
532

    
533
function unbound_remote_control_setup($cfgsubdir = "") {
534
	global $g;
535

    
536
	if (!file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") ||
537
	    (filesize("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") == 0) ||
538
	    !file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key")) {
539
		$remotcfg = <<<EOF
540
remote-control:
541
	control-enable: yes
542
	control-interface: 127.0.0.1
543
	control-port: 953
544
	server-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.key"
545
	server-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.pem"
546
	control-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key"
547
	control-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.pem"
548

    
549
EOF;
550

    
551
		create_unbound_chroot_path($cfgsubdir);
552
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
553

    
554
		// Generate our keys
555
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
556

    
557
	}
558
}
559

    
560
function sync_unbound_service() {
561
	global $config, $g;
562

    
563
	create_unbound_chroot_path();
564

    
565
	// Configure our Unbound service
566
	do_as_unbound_user("unbound-anchor");
567
	unbound_remote_control_setup();
568
	unbound_generate_config();
569
	do_as_unbound_user("start");
570
	require_once("service-utils.inc");
571
	if (is_service_running("unbound")) {
572
		do_as_unbound_user("restore_cache");
573
	}
574

    
575
}
576

    
577
function unbound_acl_id_used($id) {
578
	global $config;
579

    
580
	if (is_array($config['unbound']['acls'])) {
581
		foreach ($config['unbound']['acls'] as & $acls) {
582
			if ($id == $acls['aclid']) {
583
				return true;
584
			}
585
		}
586
	}
587

    
588
	return false;
589
}
590

    
591
function unbound_get_next_id() {
592
	$aclid = 0;
593
	while (unbound_acl_id_used($aclid)) {
594
		$aclid++;
595
	}
596
	return $aclid;
597
}
598

    
599
// Execute commands as the user unbound
600
function do_as_unbound_user($cmd, $param1 = "") {
601
	global $g;
602

    
603
	switch ($cmd) {
604
		case "start":
605
			mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
606
			break;
607
		case "stop":
608
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf stop'", true);
609
			break;
610
		case "reload":
611
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf reload'", true);
612
			break;
613
		case "unbound-anchor":
614
			$root_key_file = "{$g['unbound_chroot_path']}{$param1}/root.key";
615
			// sanity check root.key because unbound-anchor will fail without manual removal otherwise. redmine #5334
616
			if (file_exists($root_key_file)) {
617
				$rootkeycheck = mwexec("/usr/bin/grep 'autotrust trust anchor file' {$root_key_file}", true);
618
				if ($rootkeycheck != "0") {
619
					log_error("Unbound {$root_key_file} file is corrupt, removing and recreating.");
620
					unlink_if_exists($root_key_file);
621
				}
622
			}
623
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-anchor -a {$root_key_file}'", true);
624
			// Only sync the file if this is the real (default) one, not a test one.
625
			if ($param1 == "") {
626
				//pfSense_fsync($root_key_file);
627
			}
628
			break;
629
		case "unbound-control-setup":
630
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}{$param1}'", true);
631
			break;
632
		default:
633
			break;
634
	}
635
}
636

    
637
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
638
	global $config, $g;
639

    
640
	$domains = $config['unbound']['domainoverrides'];
641

    
642
	$sorted_domains = msort($domains, "domain");
643
	$result = array();
644
	$tls_domains = array();
645
	$tls_hostnames = array();
646
	foreach ($sorted_domains as $domain) {
647
		$domain_key = current($domain);
648
		if (!isset($result[$domain_key])) {
649
			$result[$domain_key] = array();
650
		}
651
		$result[$domain_key][] = $domain['ip'];
652
		/* If any entry for a domain has TLS set, it will be active for all entries. */
653
		if (isset($domain['forward_tls_upstream'])) {
654
			$tls_domains[] = $domain_key;
655
			$tls_hostnames[$domain['ip']] = $domain['tls_hostname'];
656
		}
657
	}
658

    
659
	// Domain overrides that have multiple entries need multiple stub-addr: added
660
	$domain_entries = "";
661
	foreach ($result as $domain=>$ips) {
662
		if ($pvt_rev == "private") {
663
			$domain_entries .= "private-domain: \"$domain\"\n";
664
			$domain_entries .= "domain-insecure: \"$domain\"\n";
665
		} else if ($pvt_rev == "reverse") {
666
			if ((substr($domain, -14) == ".in-addr.arpa.") || (substr($domain, -13) == ".in-addr.arpa")) {
667
				$domain_entries .= "local-zone: \"$domain\" typetransparent\n";
668
			}
669
		} else {
670
			$use_tls = in_array($domain, $tls_domains);
671
			$domain_entries .= "forward-zone:\n";
672
			$domain_entries .= "\tname: \"$domain\"\n";
673
			$fwdport = "";
674
			/* Enable TLS forwarding for this domain if needed. */
675
			if ($use_tls) {
676
				$domain_entries .= "\tforward-tls-upstream: yes\n";
677
				$fwdport = "@853";
678
			}
679
			foreach ($ips as $ip) {
680
				$fwdhost = "";
681
				/* If an IP address already contains a port specification, do not add another. */
682
				if (strstr($ip, '@') !== false) {
683
					$fwdport = "";
684
				}
685
				if ($use_tls && array_key_exists($ip, $tls_hostnames)) {
686
					$fwdhost = "#{$tls_hostnames[$ip]}";
687
				}
688
				$domain_entries .= "\tforward-addr: {$ip}{$fwdport}{$fwdhost}\n";
689
			}
690
		}
691
	}
692

    
693
	if ($pvt_rev != "") {
694
		return $domain_entries;
695
	} else {
696
		create_unbound_chroot_path($cfgsubdir);
697
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
698
	}
699
}
700

    
701
function unbound_generate_zone_data($domain, $hosts, &$added_ptr, $zone_type = "transparent", $write_domain_zone_declaration = false, $always_add_short_names = false) {
702
	global $config;
703
	if ($write_domain_zone_declaration) {
704
		$zone_data = "local-zone: \"{$domain}.\" {$zone_type}\n";
705
	} else {
706
		$zone_data = "";
707
	}
708
	foreach ($hosts as $host) {
709
		if (is_ipaddrv4($host['ipaddr'])) {
710
			$type = 'A';
711
		} else if (is_ipaddrv6($host['ipaddr'])) {
712
			$type = 'AAAA';
713
		} else {
714
			continue;
715
		}
716
		if (!$added_ptr[$host['ipaddr']]) {
717
			$zone_data .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
718
			$added_ptr[$host['ipaddr']] = true;
719
		}
720
		/* For the system localhost entry, write an entry for just the hostname. */
721
		if ((($host['name'] == "localhost") && ($domain == $config['system']['domain'])) || $always_add_short_names) {
722
			$zone_data .= "local-data: \"{$host['name']}. {$type} {$host['ipaddr']}\"\n";
723
		}
724
		/* Redirect zones must have a zone declaration that matches the
725
		 * local-data record exactly, it cannot have entries "under" the
726
		 * domain.
727
		 */
728
		if ($zone_type == "redirect") {
729
			$zone_data .= "local-zone: \"{$host['fqdn']}.\" {$zone_type}\n";;
730
		}
731
		$zone_data .= "local-data: \"{$host['fqdn']}. {$type} {$host['ipaddr']}\"\n";
732
	}
733
	return $zone_data;
734
}
735

    
736
function unbound_add_host_entries($cfgsubdir = "") {
737
	global $config, $g;
738

    
739
	$hosts = system_hosts_entries($config['unbound']);
740

    
741
	/* Pass 1: Build domain list and hosts inside domains */
742
	$hosts_by_domain = array();
743
	foreach ($hosts as $host) {
744
		if (!array_key_exists($host['domain'], $hosts_by_domain)) {
745
			$hosts_by_domain[$host['domain']] = array();
746
		}
747
		$hosts_by_domain[$host['domain']][] = $host;
748
	}
749

    
750
	$added_ptr = array();
751
	/* Build local zone data */
752
	// Check if auto add host entries is not set
753
	$system_domain_local_zone_type = "transparent";
754
	if (!isset($config['unbound']['disable_auto_added_host_entries'])) {
755
		// Make sure the config setting is a valid unbound local zone type.  If not use "transparent".
756
		if (array_key_exists($config['unbound']['system_domain_local_zone_type'], unbound_local_zone_types())) {
757
			$system_domain_local_zone_type = $config['unbound']['system_domain_local_zone_type'];
758
		}
759
	}
760
	/* Add entries for the system domain before all others */
761
	if (array_key_exists($config['system']['domain'], $hosts_by_domain)) {
762
		$unbound_entries .= unbound_generate_zone_data($config['system']['domain'],
763
					$hosts_by_domain[$config['system']['domain']],
764
					$added_ptr,
765
					$system_domain_local_zone_type,
766
					true);
767
		/* Unset this so it isn't processed again by the loop below. */
768
		unset($hosts_by_domain[$config['system']['domain']]);
769
	}
770

    
771
	/* Build zone data for other domain */
772
	foreach ($hosts_by_domain as $domain => $hosts) {
773
		$unbound_entries .= unbound_generate_zone_data($domain,
774
					$hosts,
775
					$added_ptr,
776
					"transparent",
777
					false,
778
					isset($config['unbound']['always_add_short_names']));
779
	}
780

    
781
	// Write out entries
782
	create_unbound_chroot_path($cfgsubdir);
783
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
784

    
785
	/* dhcpleases will write to this config file, make sure it exists */
786
	@touch("{$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf");
787
}
788

    
789
function unbound_control($action) {
790
	global $config, $g;
791

    
792
	$cache_dumpfile = "/var/tmp/unbound_cache";
793

    
794
	switch ($action) {
795
	case "start":
796
		// Start Unbound
797
		if ($config['unbound']['enable'] == "on") {
798
			if (!is_service_running("unbound")) {
799
				do_as_unbound_user("start");
800
			}
801
		}
802
		break;
803
	case "stop":
804
		if ($config['unbound']['enable'] == "on") {
805
			do_as_unbound_user("stop");
806
		}
807
		break;
808
	case "reload":
809
		if ($config['unbound']['enable'] == "on") {
810
			do_as_unbound_user("reload");
811
		}
812
		break;
813
	case "dump_cache":
814
		// Dump Unbound's Cache
815
		if ($config['unbound']['dumpcache'] == "on") {
816
			do_as_unbound_user("dump_cache");
817
		}
818
		break;
819
	case "restore_cache":
820
		// Restore Unbound's Cache
821
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
822
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
823
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
824
			}
825
		}
826
		break;
827
	default:
828
		break;
829

    
830
	}
831
}
832

    
833
// Generation of Unbound statistics
834
function unbound_statistics() {
835
	global $config;
836

    
837
	if ($config['stats'] == "on") {
838
		$stats_interval = $config['unbound']['stats_interval'];
839
		$cumulative_stats = $config['cumulative_stats'];
840
		if ($config['extended_stats'] == "on") {
841
			$extended_stats = "yes";
842
		} else {
843
			$extended_stats = "no";
844
		}
845
	} else {
846
		$stats_interval = "0";
847
		$cumulative_stats = "no";
848
		$extended_stats = "no";
849
	}
850
	/* XXX To do - add RRD graphs */
851
	$stats = <<<EOF
852
# Unbound Statistics
853
statistics-interval: {$stats_interval}
854
extended-statistics: yes
855
statistics-cumulative: yes
856

    
857
EOF;
858

    
859
	return $stats;
860
}
861

    
862
// Unbound Access lists
863
function unbound_acls_config($cfgsubdir = "") {
864
	global $g, $config;
865

    
866
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
867
		$aclcfg = "access-control: 127.0.0.1/32 allow_snoop\n";
868
		$aclcfg .= "access-control: ::1 allow_snoop\n";
869
		// Add our networks for active interfaces including localhost
870
		if (!empty($config['unbound']['active_interface'])) {
871
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
872
			if (in_array("all", $active_interfaces)) {
873
				$active_interfaces = get_configured_interface_with_descr();
874
			}
875
		} else {
876
			$active_interfaces = get_configured_interface_with_descr();
877
		}
878

    
879
		$aclnets = array();
880
		foreach ($active_interfaces as $ubif => $ifdesc) {
881
			$ifip = get_interface_ip($ubif);
882
			if (is_ipaddrv4($ifip)) {
883
				// IPv4 is handled via NAT networks below
884
			}
885
			$ifip = get_interface_ipv6($ubif);
886
			if (is_ipaddrv6($ifip)) {
887
				if (!is_linklocal($ifip)) {
888
					$subnet_bits = get_interface_subnetv6($ubif);
889
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
890
					// only add LAN-type interfaces
891
					if (!interface_has_gateway($ubif)) {
892
						$aclnets[] = "{$subnet_ip}/{$subnet_bits}";
893
					}
894
				}
895
				// add for IPv6 static routes to local networks
896
				// for safety, we include only routes reachable on an interface with no
897
				// gateway specified - read: not an Internet connection.
898
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
899
				foreach ($static_routes as $route) {
900
					if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
901
						// route is on this interface, interface doesn't have gateway, add it
902
						$aclnets[] = $route['network'];
903
					}
904
				}
905
			}
906
		}
907

    
908
		// OpenVPN IPv6 Tunnel Networks
909
		foreach (array('openvpn-client', 'openvpn-server') as $ovpnentry) {
910
			if (is_array($config['openvpn'][$ovpnentry])) {
911
				foreach ($config['openvpn'][$ovpnentry] as $ovpnent) {
912
					if (!isset($ovpnent['disable']) && !empty($ovpnent['tunnel_networkv6'])) {
913
						$aclnets[] = $ovpnent['tunnel_networkv6'];
914
					}
915
				}
916
			}
917
		}
918
		// IPsec Mobile Virtual IPv6 Address Pool
919
		if ((isset($config['ipsec']['client']['enable'])) &&
920
		    (!empty($config['ipsec']['client']['pool_address_v6'])) &&
921
		    (!empty($config['ipsec']['client']['pool_netbits_v6']))) {
922
			$aclnets[] = "{$config['ipsec']['client']['pool_address_v6']}/{$config['ipsec']['client']['pool_netbits_v6']}";
923
		}
924

    
925
		// WireGuard Interface Networks
926
		$aclnets = array_merge($aclnets, wg_get_tunnel_networks());
927

    
928
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
929
		if (empty($FilterIflist)) {
930
			filter_generate_optcfg_array();
931
		}
932
		$aclnets = array_merge($aclnets, filter_nat_rules_automatic_tonathosts());
933

    
934
		/* Automatic ACL networks deduplication and sorting
935
		 * https://redmine.pfsense.org/issues/11309 */
936
		$aclnets4 = array();
937
		$aclnets6 = array();
938
		foreach (array_unique($aclnets) as $acln) {
939
			if (is_v4($acln)) {
940
				$aclnets4[] = $acln;
941
			} else {
942
				$aclnets6[] = $acln;
943
			}
944
		}
945
		/* ipcmp only supports IPv4 */
946
		usort($aclnets4, "ipcmp");
947
		sort($aclnets6);
948

    
949
		foreach (array_merge($aclnets4, $aclnets6) as $acln) {
950
			$aclcfg .= "access-control: {$acln} allow \n";
951
		}
952
	}
953

    
954
	// Configure the custom ACLs
955
	if (is_array($config['unbound']['acls'])) {
956
		foreach ($config['unbound']['acls'] as $unbound_acl) {
957
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
958
			foreach ($unbound_acl['row'] as $network) {
959
				if ($unbound_acl['aclaction'] == "allow snoop") {
960
					$unbound_acl['aclaction'] = "allow_snoop";
961
				} elseif ($unbound_acl['aclaction'] == "deny nonlocal") {
962
					$unbound_acl['aclaction'] = "deny_non_local";
963
				} elseif ($unbound_acl['aclaction'] == "refuse nonlocal") {
964
					$unbound_acl['aclaction'] = "refuse_non_local";
965
				}
966
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
967
			}
968
		}
969
	}
970
	// Write out Access list
971
	create_unbound_chroot_path($cfgsubdir);
972
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
973

    
974
}
975

    
976
// Generate hosts and reload services
977
function unbound_hosts_generate() {
978
	// Generate our hosts file
979
	unbound_add_host_entries();
980

    
981
	// Reload our service to read the updates
982
	unbound_control("reload");
983
}
984

    
985
// Array of valid unbound local zone types
986
function unbound_local_zone_types() {
987
	return array(
988
		"deny" => gettext("Deny"),
989
		"refuse" => gettext("Refuse"),
990
		"static" => gettext("Static"),
991
		"transparent" => gettext("Transparent"),
992
		"typetransparent" => gettext("Type Transparent"),
993
		"redirect" => gettext("Redirect"),
994
		"inform" => gettext("Inform"),
995
		"inform_deny" => gettext("Inform Deny"),
996
		"nodefault" => gettext("No Default")
997
	);
998
}
999

    
1000
// Autoconfig EDNS buffer size
1001
function unbound_auto_ednsbufsize() {
1002
	global $config;
1003

    
1004
	$active_ipv6_inf = false;
1005
	if ($config['unbound']['active_interface'] != 'all') {
1006
		$active_interfaces = explode(",", $config['unbound']['active_interface']);
1007
	} else {
1008
		$active_interfaces = get_configured_interface_list();
1009
	}
1010

    
1011
	$min_mtu = get_interface_mtu(get_real_interface($active_interfaces[0]));
1012
	foreach ($active_interfaces as $ubif) {
1013
		$ubif_mtu = get_interface_mtu(get_real_interface($ubif));
1014
		if (get_interface_ipv6($ubif)) {
1015
			$active_ipv6_inf = true;
1016
		}
1017
		if ($ubif_mtu < $min_mtu) {
1018
			$min_mtu = $ubif_mtu;
1019
		}
1020
	}
1021

    
1022
	// maximum IPv4 + UDP header = 68 bytes
1023
	$min_mtu = $min_mtu - 68;
1024

    
1025
	if (($min_mtu < 1232) && $active_ipv6_inf) {
1026
		$min_mtu = 1232;
1027
	} elseif ($min_mtu < 512) {
1028
		$min_mtu = 512;
1029
	}	
1030

    
1031
	return $min_mtu;
1032
}
1033

    
1034
?>
(51-51/61)