Project

General

Profile

Download (33.3 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-2022 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
	// Copy the Python files to the test folder
118
	if (isset($unboundcfg['python']) &&
119
	    !empty($unboundcfg['python_script'])) {
120
		$python_files = glob("{$g['unbound_chroot_path']}/{$unboundcfg['python_script']}.*");
121
		if (is_array($python_files)) {
122
			create_unbound_chroot_path($cfgsubdir);
123
			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
	unbound_generate_config($unboundcfg, $cfgsubdir);
131
	unbound_remote_control_setup($cfgsubdir);
132
	do_as_unbound_user("unbound-anchor", $cfgsubdir);
133

    
134
	$rv = 0;
135
	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

    
142
	return $rv;
143
}
144

    
145

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

    
149
	$unboundcfgtxt = unbound_generate_config_text($unboundcfg, $cfgsubdir);
150

    
151
	// Configure static Host entries
152
	unbound_add_host_entries($cfgsubdir);
153

    
154
	// Configure Domain Overrides
155
	unbound_add_domain_overrides("", $cfgsubdir);
156

    
157
	// Configure Unbound access-lists
158
	unbound_acls_config($cfgsubdir);
159

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

    
164
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

    
189
function unbound_generate_config_text($unboundcfg = NULL, $cfgsubdir = "") {
190

    
191
	global $config, $g, $nooutifs;
192
	if (is_null($unboundcfg)) {
193
		$unboundcfg = $config['unbound'];
194
	}
195

    
196
	if (platform_booting()) {
197
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
198
	}
199

    
200
	// Setup optimization
201
	$optimization = unbound_optimization();
202

    
203
	$module_config = '';
204

    
205
	// Setup Python module (pre validator)
206
	if (!empty(unbound_get_python_scriptname($unboundcfg, $cfgsubdir)) &&
207
	    $unboundcfg['python_order'] == 'pre_validator') {
208
		$module_config .= 'python ';
209
	}
210

    
211
	// 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
	// Setup DNSSEC support
223
	if (isset($unboundcfg['dnssec'])) {
224
		$module_config .= 'validator ';
225
		$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}{$cfgsubdir}/root.key";
226
	}
227

    
228
	// Setup Python module (post validator)
229
	if (!empty(unbound_get_python_scriptname($unboundcfg, $cfgsubdir)) &&
230
	    $unboundcfg['python_order'] == 'post_validator') {
231
		$module_config .= 'python ';
232
	}
233

    
234
	$module_config .= 'iterator';
235

    
236
	// Setup DNS Rebinding
237
	if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
238
		// Private-addresses for DNS Rebinding
239
		$private_addr = <<<EOF
240
# For DNS Rebinding prevention
241
private-address: 127.0.0.0/8
242
private-address: 10.0.0.0/8
243
private-address: ::ffff:a00:0/104
244
private-address: 172.16.0.0/12
245
private-address: ::ffff:ac10:0/108
246
private-address: 169.254.0.0/16
247
private-address: ::ffff:a9fe:0/112
248
private-address: 192.168.0.0/16
249
private-address: ::ffff:c0a8:0/112
250
private-address: fd00::/8
251
private-address: fe80::/10
252
EOF;
253
	}
254

    
255
	// Determine interfaces where unbound will bind
256
	$tlsport = is_numeric($unboundcfg['tlsport']) ? $unboundcfg['tlsport'] : "853";
257
	$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
			/* 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
			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
				}
283
			}
284
		}
285
	}
286
	foreach ($bindints as $bindint) {
287
		$bindintcfg .= "interface: {$bindint}\n";
288
		if (isset($unboundcfg['enablessl'])) {
289
			$bindintcfg .= "interface: {$bindint}@{$tlsport}\n";
290
		}
291
	}
292

    
293
	// TLS Configuration
294
	$tlsconfig = "tls-cert-bundle: \"/etc/ssl/cert.pem\"\n";
295

    
296
	if (isset($unboundcfg['enablessl'])) {
297
		$tlscert_path = "{$g['unbound_chroot_path']}/sslcert.crt";
298
		$tlskey_path = "{$g['unbound_chroot_path']}/sslcert.key";
299

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

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

    
317
		// Add config for CA and Server Cert
318
		$tlsconfig .= "tls-service-pem: \"{$tlscert_path}\"\n";
319
		$tlsconfig .= "tls-service-key: \"{$tlskey_path}\"\n";
320
	}
321

    
322
	// Determine interfaces to run on
323
	$outgoingints = "";
324
	if (!empty($unboundcfg['outgoing_interface'])) {
325
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
326
		foreach ($outgoing_interfaces as $outif) {
327
			$ifinfo = get_interface_info($outif);
328
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
329
				continue;
330
			}
331
			$outip = get_interface_ip($outif);
332
			if (is_ipaddr($outip)) {
333
				$outgoingints .= "outgoing-interface: $outip\n";
334
			}
335
			$outip = get_interface_ipv6($outif);
336
			if (is_ipaddrv6($outip)) {
337
				$outgoingints .= "outgoing-interface: $outip\n";
338
			}
339
		}
340
		if (!empty($outgoingints)) {
341
			$outgoingints = "# Outgoing interfaces to be used\n" . $outgoingints;
342
		} else {
343
			$nooutifs = true;
344
		}
345
	}
346

    
347
	// Allow DNS Rebind for forwarded domains
348
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
349
		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
	}
355

    
356
	// Configure Unbound statistics
357
	$statistics = unbound_statistics();
358

    
359
	// Add custom Unbound options
360
	if ($unboundcfg['custom_options']) {
361
		$custom_options_source = explode("\n", base64_decode($unboundcfg['custom_options']));
362
		$custom_options = "# Unbound custom options\n";
363
		foreach ($custom_options_source as $ent) {
364
			$custom_options .= $ent."\n";
365
		}
366
	}
367

    
368
	// Server configuration variables
369
	$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
	$ipv6_allow = isset($config['system']['ipv6allow']) ? "yes" : "no";
373
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
374
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
375
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
376
	$dns_record_cache = isset($unboundcfg['dnsrecordcache']) ? "yes" : "no";
377
	$aggressivensec = isset($unboundcfg['aggressivensec']) ? "yes" : "no";
378
	$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
	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
	$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
	if ($unwanted_reply_threshold == "disabled") {
393
		$unwanted_reply_threshold = "0";
394
	}
395
	$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

    
399
	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
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
407
	}
408

    
409
	// Set up forwarding if it is configured
410
	if (isset($unboundcfg['forwarding'])) {
411
		$dnsservers = get_dns_nameservers(false, true);
412
		if (!empty($dnsservers)) {
413
			$forward_conf .=<<<EOD
414
# Forwarding
415
forward-zone:
416
	name: "."
417

    
418
EOD;
419
			if (isset($unboundcfg['forward_tls_upstream'])) {
420
				$forward_conf .= "\tforward-tls-upstream: yes\n";
421
			}
422

    
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
			foreach ($dnsservers as $dnsserver) {
435
				$fwdport = "";
436
				$fwdhost = "";
437
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
438
					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
				}
446
			}
447
		}
448
	} else {
449
		$forward_conf = "";
450
	}
451

    
452
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
453
	$rrset_cache_size = $msg_cache_size * 2;
454

    
455
	/* 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
	$python_module = '';
468
	$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
	}
472

    
473
	$unboundconf = <<<EOD
474
##########################
475
# Unbound Configuration
476
##########################
477

    
478
##
479
# Server configuration
480
##
481
server:
482
{$reverse_zones}
483
chroot: {$g['unbound_chroot_path']}
484
username: "unbound"
485
directory: "{$g['unbound_chroot_path']}"
486
pidfile: "/var/run/unbound.pid"
487
use-syslog: yes
488
port: {$port}
489
verbosity: {$verbosity}
490
hide-identity: {$hide_identity}
491
hide-version: {$hide_version}
492
harden-glue: yes
493
do-ip4: yes
494
do-ip6: {$ipv6_allow}
495
do-udp: yes
496
do-tcp: yes
497
do-daemonize: yes
498
module-config: "{$module_config}"
499
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
cache-max-ttl: {$cache_max_ttl}
508
cache-min-ttl: {$cache_min_ttl}
509
harden-dnssec-stripped: {$harden_dnssec_stripped}
510
msg-cache-size: {$msg_cache_size}m
511
rrset-cache-size: {$rrset_cache_size}m
512
{$qname_min}
513
{$optimization['number_threads']}
514
{$optimization['msg_cache_slabs']}
515
{$optimization['rrset_cache_slabs']}
516
{$optimization['infra_cache_slabs']}
517
{$optimization['key_cache_slabs']}
518
outgoing-range: 4096
519
{$optimization['so_rcvbuf']}
520
{$anchor_file}
521
prefetch: {$prefetch}
522
prefetch-key: {$prefetch_key}
523
use-caps-for-id: {$use_caps}
524
serve-expired: {$dns_record_cache}
525
aggressive-nsec: {$aggressivensec}
526
# Statistics
527
{$statistics}
528
# TLS Configuration
529
{$tlsconfig}
530
# Interface IP(s) to bind to
531
{$bindintcfg}
532
{$outgoingints}
533
# DNS Rebinding
534
{$private_addr}
535
{$private_domains}
536
{$dns64_conf}
537

    
538
# Access lists
539
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
540

    
541
# Static host entries
542
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
543

    
544
# dhcp lease entries
545
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
546

    
547
{$openvpn_clients_conf}
548

    
549
# Domain overrides
550
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
551
{$forward_conf}
552

    
553
{$custom_options}
554

    
555
###
556
# Remote Control Config
557
###
558
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
559
{$python_module}
560

    
561
EOD;
562

    
563
	return $unboundconf;
564
}
565

    
566
function unbound_remote_control_setup($cfgsubdir = "") {
567
	global $g;
568

    
569
	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
		$remotcfg = <<<EOF
573
remote-control:
574
	control-enable: yes
575
	control-interface: 127.0.0.1
576
	control-port: 953
577
	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

    
582
EOF;
583

    
584
		create_unbound_chroot_path($cfgsubdir);
585
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
586

    
587
		// Generate our keys
588
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
589

    
590
	}
591
}
592

    
593
function sync_unbound_service() {
594
	global $config, $g;
595

    
596
	create_unbound_chroot_path();
597

    
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
	if (is_service_running("unbound")) {
605
		do_as_unbound_user("restore_cache");
606
	}
607

    
608
}
609

    
610
function unbound_acl_id_used($id) {
611
	global $config;
612

    
613
	if (is_array($config['unbound']['acls'])) {
614
		foreach ($config['unbound']['acls'] as & $acls) {
615
			if ($id == $acls['aclid']) {
616
				return true;
617
			}
618
		}
619
	}
620

    
621
	return false;
622
}
623

    
624
function unbound_get_next_id() {
625
	$aclid = 0;
626
	while (unbound_acl_id_used($aclid)) {
627
		$aclid++;
628
	}
629
	return $aclid;
630
}
631

    
632
// Execute commands as the user unbound
633
function do_as_unbound_user($cmd, $param1 = "") {
634
	global $g;
635

    
636
	switch ($cmd) {
637
		case "start":
638
			mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
639
			break;
640
		case "stop":
641
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf stop'", true);
642
			break;
643
		case "reload":
644
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf reload'", true);
645
			break;
646
		case "unbound-anchor":
647
			$root_key_file = "{$g['unbound_chroot_path']}{$param1}/root.key";
648
			// sanity check root.key because unbound-anchor will fail without manual removal otherwise. redmine #5334
649
			if (file_exists($root_key_file)) {
650
				$rootkeycheck = mwexec("/usr/bin/grep 'autotrust trust anchor file' {$root_key_file}", true);
651
				if ($rootkeycheck != "0") {
652
					log_error("Unbound {$root_key_file} file is corrupt, removing and recreating.");
653
					unlink_if_exists($root_key_file);
654
				}
655
			}
656
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-anchor -a {$root_key_file}'", true);
657
			// Only sync the file if this is the real (default) one, not a test one.
658
			if ($param1 == "") {
659
				//pfSense_fsync($root_key_file);
660
			}
661
			break;
662
		case "unbound-control-setup":
663
			mwexec("/usr/bin/su -m unbound -c '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}{$param1}'", true);
664
			break;
665
		default:
666
			break;
667
	}
668
}
669

    
670
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
671
	global $config, $g;
672

    
673
	$domains = $config['unbound']['domainoverrides'];
674

    
675
	$sorted_domains = msort($domains, "domain");
676
	$result = array();
677
	$tls_domains = array();
678
	$tls_hostnames = array();
679
	foreach ($sorted_domains as $domain) {
680
		$domain_key = current($domain);
681
		if (!isset($result[$domain_key])) {
682
			$result[$domain_key] = array();
683
		}
684
		$result[$domain_key][] = $domain['ip'];
685
		/* 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
			$tls_hostnames[$domain['ip']] = $domain['tls_hostname'];
689
		}
690
	}
691

    
692
	// Domain overrides that have multiple entries need multiple stub-addr: added
693
	$domain_entries = "";
694
	foreach ($result as $domain=>$ips) {
695
		if ($pvt_rev == "private") {
696
			$domain_entries .= "private-domain: \"$domain\"\n";
697
			$domain_entries .= "domain-insecure: \"$domain\"\n";
698
		} else if ($pvt_rev == "reverse") {
699
			if (preg_match("/.+\.(in-addr|ip6)\.arpa\.?$/", $domain)) {
700
				$domain_entries .= "local-zone: \"$domain\" typetransparent\n";
701
			}
702
		} else {
703
			$use_tls = in_array($domain, $tls_domains);
704
			$domain_entries .= "forward-zone:\n";
705
			$domain_entries .= "\tname: \"$domain\"\n";
706
			$fwdport = "";
707
			/* Enable TLS forwarding for this domain if needed. */
708
			if ($use_tls) {
709
				$domain_entries .= "\tforward-tls-upstream: yes\n";
710
				$fwdport = "@853";
711
			}
712
			foreach ($ips as $ip) {
713
				$fwdhost = "";
714
				/* If an IP address already contains a port specification, do not add another. */
715
				if (strstr($ip, '@') !== false) {
716
					$fwdport = "";
717
				}
718
				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
			}
723
		}
724
	}
725

    
726
	if ($pvt_rev != "") {
727
		return $domain_entries;
728
	} else {
729
		create_unbound_chroot_path($cfgsubdir);
730
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
731
	}
732
}
733

    
734
function unbound_generate_zone_data($domain, $hosts, &$added_ptr, $zone_type = "transparent", $write_domain_zone_declaration = false, $always_add_short_names = false) {
735
	global $config;
736
	if ($write_domain_zone_declaration) {
737
		$zone_data = "local-zone: \"{$domain}.\" {$zone_type}\n";
738
	} else {
739
		$zone_data = "";
740
	}
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
			$zone_data .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
751
			$added_ptr[$host['ipaddr']] = true;
752
		}
753
		/* 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
	global $config, $g, $nooutifs;
771

    
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
	/* 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
	/* 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
	}
818

    
819
	// Write out entries
820
	create_unbound_chroot_path($cfgsubdir);
821
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
822

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

    
827
function unbound_control($action) {
828
	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
			if (!is_service_running("unbound")) {
837
				do_as_unbound_user("start");
838
			}
839
		}
840
		break;
841
	case "stop":
842
		if ($config['unbound']['enable'] == "on") {
843
			do_as_unbound_user("stop");
844
		}
845
		break;
846
	case "reload":
847
		if ($config['unbound']['enable'] == "on") {
848
			do_as_unbound_user("reload");
849
		}
850
		break;
851
	case "dump_cache":
852
		// Dump Unbound's Cache
853
		if ($config['unbound']['dumpcache'] == "on") {
854
			do_as_unbound_user("dump_cache");
855
		}
856
		break;
857
	case "restore_cache":
858
		// Restore Unbound's Cache
859
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
860
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
861
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
862
			}
863
		}
864
		break;
865
	default:
866
		break;
867

    
868
	}
869
}
870

    
871
// Generation of Unbound statistics
872
function unbound_statistics() {
873
	global $config;
874

    
875
	if ($config['stats'] == "on") {
876
		$stats_interval = $config['unbound']['stats_interval'];
877
		$cumulative_stats = $config['cumulative_stats'];
878
		if ($config['extended_stats'] == "on") {
879
			$extended_stats = "yes";
880
		} else {
881
			$extended_stats = "no";
882
		}
883
	} 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
# Unbound Statistics
891
statistics-interval: {$stats_interval}
892
extended-statistics: yes
893
statistics-cumulative: yes
894

    
895
EOF;
896

    
897
	return $stats;
898
}
899

    
900
// Unbound Access lists
901
function unbound_acls_config($cfgsubdir = "") {
902
	global $g, $config;
903

    
904
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
905
		$aclcfg = "access-control: 127.0.0.1/32 allow_snoop\n";
906
		$aclcfg .= "access-control: ::1 allow_snoop\n";
907
		// Add our networks for active interfaces including localhost
908
		if (!empty($config['unbound']['active_interface'])) {
909
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
910
			if (in_array("all", $active_interfaces)) {
911
				$active_interfaces = get_configured_interface_with_descr();
912
			}
913
		} else {
914
			$active_interfaces = get_configured_interface_with_descr();
915
		}
916

    
917
		$aclnets = array();
918
		foreach ($active_interfaces as $ubif => $ifdesc) {
919
			$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
				if (!is_linklocal($ifip)) {
926
					$subnet_bits = get_interface_subnetv6($ubif);
927
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
928
					// only add LAN-type interfaces
929
					if (!interface_has_gateway($ubif)) {
930
						$aclnets[] = "{$subnet_ip}/{$subnet_bits}";
931
					}
932
				}
933
				// add for IPv6 static routes to local networks
934
				// for safety, we include only routes reachable on an interface with no
935
				// gateway specified - read: not an Internet connection.
936
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
937
				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
						$aclnets[] = $route['network'];
941
					}
942
				}
943
			}
944
		}
945

    
946
		// 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
						$aclnets[] = implode('/', openvpn_gen_tunnel_network($ovpnent['tunnel_networkv6']));
952
					}
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
			$aclnets[] = "{$config['ipsec']['client']['pool_address_v6']}/{$config['ipsec']['client']['pool_netbits_v6']}";
961
		}
962

    
963
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
964
		if (empty($FilterIflist)) {
965
			filter_generate_optcfg_array();
966
		}
967
		$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
			/* Do not form an invalid directive with an empty address */
986
			if (empty($acln)) {
987
				continue;
988
			}
989
			$aclcfg .= "access-control: {$acln} allow \n";
990
		}
991
	}
992

    
993
	// Configure the custom ACLs
994
	if (is_array($config['unbound']['acls'])) {
995
		foreach ($config['unbound']['acls'] as $unbound_acl) {
996
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
997
			foreach ($unbound_acl['row'] as $network) {
998
				if ($unbound_acl['aclaction'] == "allow snoop") {
999
					$unbound_acl['aclaction'] = "allow_snoop";
1000
				} 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
				}
1005
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
1006
			}
1007
		}
1008
	}
1009
	// Write out Access list
1010
	create_unbound_chroot_path($cfgsubdir);
1011
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
1012

    
1013
}
1014

    
1015
// Generate hosts and reload services
1016
function unbound_hosts_generate() {
1017
	// Generate our hosts file
1018
	unbound_add_host_entries();
1019

    
1020
	// Reload our service to read the updates
1021
	unbound_control("reload");
1022
}
1023

    
1024
// 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
// 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
?>
(51-51/61)