Project

General

Profile

Download (33 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
	// 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;
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
		$outgoingints = "# Outgoing interfaces to be used\n";
326
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
327
		foreach ($outgoing_interfaces as $outif) {
328
			$ifinfo = get_interface_info($outif);
329
			if ($ifinfo && (($ifinfo['status'] != 'up') || !$ifinfo['enable'])) {
330
				continue;
331
			}
332
			$outip = get_interface_ip($outif);
333
			if (is_ipaddr($outip)) {
334
				$outgoingints .= "outgoing-interface: $outip\n";
335
			}
336
			$outip = get_interface_ipv6($outif);
337
			if (is_ipaddrv6($outip)) {
338
				$outgoingints .= "outgoing-interface: $outip\n";
339
			}
340
		}
341
	}
342

    
343
	// Allow DNS Rebind for forwarded domains
344
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
345
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
346
			$private_domains = "# Set private domains in case authoritative name server returns a Private IP address\n";
347
			$private_domains .= unbound_add_domain_overrides("private");
348
		}
349
		$reverse_zones .= unbound_add_domain_overrides("reverse");
350
	}
351

    
352
	// Configure Unbound statistics
353
	$statistics = unbound_statistics();
354

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

    
364
	// Server configuration variables
365
	$port = (is_port($unboundcfg['port'])) ? $unboundcfg['port'] : "53";
366
	$hide_identity = isset($unboundcfg['hideidentity']) ? "yes" : "no";
367
	$hide_version = isset($unboundcfg['hideversion']) ? "yes" : "no";
368
	$ipv6_allow = isset($config['system']['ipv6allow']) ? "yes" : "no";
369
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
370
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
371
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
372
	$dns_record_cache = isset($unboundcfg['dnsrecordcache']) ? "yes" : "no";
373
	$aggressivensec = isset($unboundcfg['aggressivensec']) ? "yes" : "no";
374
	$outgoing_num_tcp = isset($unboundcfg['outgoing_num_tcp']) ? $unboundcfg['outgoing_num_tcp'] : "10";
375
	$incoming_num_tcp = isset($unboundcfg['incoming_num_tcp']) ? $unboundcfg['incoming_num_tcp'] : "10";
376
	if (empty($unboundcfg['edns_buffer_size']) || ($unboundcfg['edns_buffer_size'] == 'auto')) {
377
		$edns_buffer_size = unbound_auto_ednsbufsize();
378
	} else {
379
		$edns_buffer_size = $unboundcfg['edns_buffer_size'];
380
	}
381
	$num_queries_per_thread = (!empty($unboundcfg['num_queries_per_thread'])) ? $unboundcfg['num_queries_per_thread'] : "4096";
382
	$jostle_timeout = (!empty($unboundcfg['jostle_timeout'])) ? $unboundcfg['jostle_timeout'] : "200";
383
	$cache_max_ttl = (!empty($unboundcfg['cache_max_ttl'])) ? $unboundcfg['cache_max_ttl'] : "86400";
384
	$cache_min_ttl = (!empty($unboundcfg['cache_min_ttl'])) ? $unboundcfg['cache_min_ttl'] : "0";
385
	$infra_host_ttl = (!empty($unboundcfg['infra_host_ttl'])) ? $unboundcfg['infra_host_ttl'] : "900";
386
	$infra_cache_numhosts = (!empty($unboundcfg['infra_cache_numhosts'])) ? $unboundcfg['infra_cache_numhosts'] : "10000";
387
	$unwanted_reply_threshold = (!empty($unboundcfg['unwanted_reply_threshold'])) ? $unboundcfg['unwanted_reply_threshold'] : "0";
388
	if ($unwanted_reply_threshold == "disabled") {
389
		$unwanted_reply_threshold = "0";
390
	}
391
	$msg_cache_size = (!empty($unboundcfg['msgcachesize'])) ? $unboundcfg['msgcachesize'] : "4";
392
	$verbosity = isset($unboundcfg['log_verbosity']) ? $unboundcfg['log_verbosity'] : 1;
393
	$use_caps = isset($unboundcfg['use_caps']) ? "yes" : "no";
394

    
395
	if (isset($unboundcfg['regovpnclients'])) {
396
		$openvpn_clients_conf .=<<<EOD
397
# OpenVPN client entries
398
include: {$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf
399
EOD;
400
	} else {
401
		$openvpn_clients_conf = '';
402
		unlink_if_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf");
403
	}
404

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

    
414
EOD;
415
			if (isset($unboundcfg['forward_tls_upstream'])) {
416
				$forward_conf .= "\tforward-tls-upstream: yes\n";
417
			}
418

    
419
			/* Build DNS server hostname list. See https://redmine.pfsense.org/issues/8602 */
420
			$dns_hostnames = array();
421
			$dnshost_counter = 1;
422
			while (isset($config["system"]["dns{$dnshost_counter}host"])) {
423
				$pconfig_dnshost_counter = $dnshost_counter - 1;
424
				if (!empty($config["system"]["dns{$dnshost_counter}host"]) &&
425
				    isset($config["system"]["dnsserver"][$pconfig_dnshost_counter]))
426
				$dns_hostnames[$config["system"]["dnsserver"][$pconfig_dnshost_counter]] = $config["system"]["dns{$dnshost_counter}host"];
427
				$dnshost_counter++;
428
			}
429

    
430
			foreach ($dnsservers as $dnsserver) {
431
				$fwdport = "";
432
				$fwdhost = "";
433
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
434
					if (isset($unboundcfg['forward_tls_upstream'])) {
435
						$fwdport = "@853";
436
						if (array_key_exists($dnsserver, $dns_hostnames)) {
437
							$fwdhost = "#{$dns_hostnames[$dnsserver]}";
438
						}
439
					}
440
					$forward_conf .= "\tforward-addr: {$dnsserver}{$fwdport}{$fwdhost}\n";
441
				}
442
			}
443
		}
444
	} else {
445
		$forward_conf = "";
446
	}
447

    
448
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
449
	$rrset_cache_size = $msg_cache_size * 2;
450

    
451
	/* QNAME Minimization. https://redmine.pfsense.org/issues/8028
452
	 * Unbound uses the British style in the option name so the internal option
453
	 * name follows that, but the user-visible descriptions follow US English.
454
	 */
455
	$qname_min = "";
456
	if (isset($unboundcfg['qname-minimisation'])) {
457
		$qname_min = "qname-minimisation: yes\n";
458
		if (isset($unboundcfg['qname-minimisation-strict'])) {
459
			$qname_min .= "qname-minimisation-strict: yes\n";
460
		}
461
	}
462

    
463
	$python_module = '';
464
	$python_script_file = unbound_get_python_scriptname($unboundcfg, $cfgsubdir);
465
	if (!empty($python_script_file)) {
466
		$python_module = "\n# Python Module\npython:\npython-script: {$python_script_file}";
467
	}
468

    
469
	$unboundconf = <<<EOD
470
##########################
471
# Unbound Configuration
472
##########################
473

    
474
##
475
# Server configuration
476
##
477
server:
478
{$reverse_zones}
479
chroot: {$g['unbound_chroot_path']}
480
username: "unbound"
481
directory: "{$g['unbound_chroot_path']}"
482
pidfile: "/var/run/unbound.pid"
483
use-syslog: yes
484
port: {$port}
485
verbosity: {$verbosity}
486
hide-identity: {$hide_identity}
487
hide-version: {$hide_version}
488
harden-glue: yes
489
do-ip4: yes
490
do-ip6: {$ipv6_allow}
491
do-udp: yes
492
do-tcp: yes
493
do-daemonize: yes
494
module-config: "{$module_config}"
495
unwanted-reply-threshold: {$unwanted_reply_threshold}
496
num-queries-per-thread: {$num_queries_per_thread}
497
jostle-timeout: {$jostle_timeout}
498
infra-host-ttl: {$infra_host_ttl}
499
infra-cache-numhosts: {$infra_cache_numhosts}
500
outgoing-num-tcp: {$outgoing_num_tcp}
501
incoming-num-tcp: {$incoming_num_tcp}
502
edns-buffer-size: {$edns_buffer_size}
503
cache-max-ttl: {$cache_max_ttl}
504
cache-min-ttl: {$cache_min_ttl}
505
harden-dnssec-stripped: {$harden_dnssec_stripped}
506
msg-cache-size: {$msg_cache_size}m
507
rrset-cache-size: {$rrset_cache_size}m
508
{$qname_min}
509
{$optimization['number_threads']}
510
{$optimization['msg_cache_slabs']}
511
{$optimization['rrset_cache_slabs']}
512
{$optimization['infra_cache_slabs']}
513
{$optimization['key_cache_slabs']}
514
outgoing-range: 4096
515
{$optimization['so_rcvbuf']}
516
{$anchor_file}
517
prefetch: {$prefetch}
518
prefetch-key: {$prefetch_key}
519
use-caps-for-id: {$use_caps}
520
serve-expired: {$dns_record_cache}
521
aggressive-nsec: {$aggressivensec}
522
# Statistics
523
{$statistics}
524
# TLS Configuration
525
{$tlsconfig}
526
# Interface IP(s) to bind to
527
{$bindintcfg}
528
{$outgoingints}
529
# DNS Rebinding
530
{$private_addr}
531
{$private_domains}
532
{$dns64_conf}
533

    
534
# Access lists
535
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
536

    
537
# Static host entries
538
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
539

    
540
# dhcp lease entries
541
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
542

    
543
{$openvpn_clients_conf}
544

    
545
# Domain overrides
546
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
547
{$forward_conf}
548

    
549
{$custom_options}
550

    
551
###
552
# Remote Control Config
553
###
554
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
555
{$python_module}
556

    
557
EOD;
558

    
559
	return $unboundconf;
560
}
561

    
562
function unbound_remote_control_setup($cfgsubdir = "") {
563
	global $g;
564

    
565
	if (!file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") ||
566
	    (filesize("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") == 0) ||
567
	    !file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key")) {
568
		$remotcfg = <<<EOF
569
remote-control:
570
	control-enable: yes
571
	control-interface: 127.0.0.1
572
	control-port: 953
573
	server-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.key"
574
	server-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.pem"
575
	control-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key"
576
	control-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.pem"
577

    
578
EOF;
579

    
580
		create_unbound_chroot_path($cfgsubdir);
581
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
582

    
583
		// Generate our keys
584
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
585

    
586
	}
587
}
588

    
589
function sync_unbound_service() {
590
	global $config, $g;
591

    
592
	create_unbound_chroot_path();
593

    
594
	// Configure our Unbound service
595
	do_as_unbound_user("unbound-anchor");
596
	unbound_remote_control_setup();
597
	unbound_generate_config();
598
	do_as_unbound_user("start");
599
	require_once("service-utils.inc");
600
	if (is_service_running("unbound")) {
601
		do_as_unbound_user("restore_cache");
602
	}
603

    
604
}
605

    
606
function unbound_acl_id_used($id) {
607
	global $config;
608

    
609
	if (is_array($config['unbound']['acls'])) {
610
		foreach ($config['unbound']['acls'] as & $acls) {
611
			if ($id == $acls['aclid']) {
612
				return true;
613
			}
614
		}
615
	}
616

    
617
	return false;
618
}
619

    
620
function unbound_get_next_id() {
621
	$aclid = 0;
622
	while (unbound_acl_id_used($aclid)) {
623
		$aclid++;
624
	}
625
	return $aclid;
626
}
627

    
628
// Execute commands as the user unbound
629
function do_as_unbound_user($cmd, $param1 = "") {
630
	global $g;
631

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

    
666
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
667
	global $config, $g;
668

    
669
	$domains = $config['unbound']['domainoverrides'];
670

    
671
	$sorted_domains = msort($domains, "domain");
672
	$result = array();
673
	$tls_domains = array();
674
	$tls_hostnames = array();
675
	foreach ($sorted_domains as $domain) {
676
		$domain_key = current($domain);
677
		if (!isset($result[$domain_key])) {
678
			$result[$domain_key] = array();
679
		}
680
		$result[$domain_key][] = $domain['ip'];
681
		/* If any entry for a domain has TLS set, it will be active for all entries. */
682
		if (isset($domain['forward_tls_upstream'])) {
683
			$tls_domains[] = $domain_key;
684
			$tls_hostnames[$domain['ip']] = $domain['tls_hostname'];
685
		}
686
	}
687

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

    
722
	if ($pvt_rev != "") {
723
		return $domain_entries;
724
	} else {
725
		create_unbound_chroot_path($cfgsubdir);
726
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
727
	}
728
}
729

    
730
function unbound_generate_zone_data($domain, $hosts, &$added_ptr, $zone_type = "transparent", $write_domain_zone_declaration = false, $always_add_short_names = false) {
731
	global $config;
732
	if ($write_domain_zone_declaration) {
733
		$zone_data = "local-zone: \"{$domain}.\" {$zone_type}\n";
734
	} else {
735
		$zone_data = "";
736
	}
737
	foreach ($hosts as $host) {
738
		if (is_ipaddrv4($host['ipaddr'])) {
739
			$type = 'A';
740
		} else if (is_ipaddrv6($host['ipaddr'])) {
741
			$type = 'AAAA';
742
		} else {
743
			continue;
744
		}
745
		if (!$added_ptr[$host['ipaddr']]) {
746
			$zone_data .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
747
			$added_ptr[$host['ipaddr']] = true;
748
		}
749
		/* For the system localhost entry, write an entry for just the hostname. */
750
		if ((($host['name'] == "localhost") && ($domain == $config['system']['domain'])) || $always_add_short_names) {
751
			$zone_data .= "local-data: \"{$host['name']}. {$type} {$host['ipaddr']}\"\n";
752
		}
753
		/* Redirect zones must have a zone declaration that matches the
754
		 * local-data record exactly, it cannot have entries "under" the
755
		 * domain.
756
		 */
757
		if ($zone_type == "redirect") {
758
			$zone_data .= "local-zone: \"{$host['fqdn']}.\" {$zone_type}\n";;
759
		}
760
		$zone_data .= "local-data: \"{$host['fqdn']}. {$type} {$host['ipaddr']}\"\n";
761
	}
762
	return $zone_data;
763
}
764

    
765
function unbound_add_host_entries($cfgsubdir = "") {
766
	global $config, $g;
767

    
768
	$hosts = system_hosts_entries($config['unbound']);
769

    
770
	/* Pass 1: Build domain list and hosts inside domains */
771
	$hosts_by_domain = array();
772
	foreach ($hosts as $host) {
773
		if (!array_key_exists($host['domain'], $hosts_by_domain)) {
774
			$hosts_by_domain[$host['domain']] = array();
775
		}
776
		$hosts_by_domain[$host['domain']][] = $host;
777
	}
778

    
779
	$added_ptr = array();
780
	/* Build local zone data */
781
	// Check if auto add host entries is not set
782
	$system_domain_local_zone_type = "transparent";
783
	if (!isset($config['unbound']['disable_auto_added_host_entries'])) {
784
		// Make sure the config setting is a valid unbound local zone type.  If not use "transparent".
785
		if (array_key_exists($config['unbound']['system_domain_local_zone_type'], unbound_local_zone_types())) {
786
			$system_domain_local_zone_type = $config['unbound']['system_domain_local_zone_type'];
787
		}
788
	}
789
	/* Add entries for the system domain before all others */
790
	if (array_key_exists($config['system']['domain'], $hosts_by_domain)) {
791
		$unbound_entries .= unbound_generate_zone_data($config['system']['domain'],
792
					$hosts_by_domain[$config['system']['domain']],
793
					$added_ptr,
794
					$system_domain_local_zone_type,
795
					true);
796
		/* Unset this so it isn't processed again by the loop below. */
797
		unset($hosts_by_domain[$config['system']['domain']]);
798
	}
799

    
800
	/* Build zone data for other domain */
801
	foreach ($hosts_by_domain as $domain => $hosts) {
802
		$unbound_entries .= unbound_generate_zone_data($domain,
803
					$hosts,
804
					$added_ptr,
805
					"transparent",
806
					false,
807
					isset($config['unbound']['always_add_short_names']));
808
	}
809

    
810
	// Write out entries
811
	create_unbound_chroot_path($cfgsubdir);
812
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
813

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

    
818
function unbound_control($action) {
819
	global $config, $g;
820

    
821
	$cache_dumpfile = "/var/tmp/unbound_cache";
822

    
823
	switch ($action) {
824
	case "start":
825
		// Start Unbound
826
		if ($config['unbound']['enable'] == "on") {
827
			if (!is_service_running("unbound")) {
828
				do_as_unbound_user("start");
829
			}
830
		}
831
		break;
832
	case "stop":
833
		if ($config['unbound']['enable'] == "on") {
834
			do_as_unbound_user("stop");
835
		}
836
		break;
837
	case "reload":
838
		if ($config['unbound']['enable'] == "on") {
839
			do_as_unbound_user("reload");
840
		}
841
		break;
842
	case "dump_cache":
843
		// Dump Unbound's Cache
844
		if ($config['unbound']['dumpcache'] == "on") {
845
			do_as_unbound_user("dump_cache");
846
		}
847
		break;
848
	case "restore_cache":
849
		// Restore Unbound's Cache
850
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
851
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
852
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
853
			}
854
		}
855
		break;
856
	default:
857
		break;
858

    
859
	}
860
}
861

    
862
// Generation of Unbound statistics
863
function unbound_statistics() {
864
	global $config;
865

    
866
	if ($config['stats'] == "on") {
867
		$stats_interval = $config['unbound']['stats_interval'];
868
		$cumulative_stats = $config['cumulative_stats'];
869
		if ($config['extended_stats'] == "on") {
870
			$extended_stats = "yes";
871
		} else {
872
			$extended_stats = "no";
873
		}
874
	} else {
875
		$stats_interval = "0";
876
		$cumulative_stats = "no";
877
		$extended_stats = "no";
878
	}
879
	/* XXX To do - add RRD graphs */
880
	$stats = <<<EOF
881
# Unbound Statistics
882
statistics-interval: {$stats_interval}
883
extended-statistics: yes
884
statistics-cumulative: yes
885

    
886
EOF;
887

    
888
	return $stats;
889
}
890

    
891
// Unbound Access lists
892
function unbound_acls_config($cfgsubdir = "") {
893
	global $g, $config;
894

    
895
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
896
		$aclcfg = "access-control: 127.0.0.1/32 allow_snoop\n";
897
		$aclcfg .= "access-control: ::1 allow_snoop\n";
898
		// Add our networks for active interfaces including localhost
899
		if (!empty($config['unbound']['active_interface'])) {
900
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
901
			if (in_array("all", $active_interfaces)) {
902
				$active_interfaces = get_configured_interface_with_descr();
903
			}
904
		} else {
905
			$active_interfaces = get_configured_interface_with_descr();
906
		}
907

    
908
		$aclnets = array();
909
		foreach ($active_interfaces as $ubif => $ifdesc) {
910
			$ifip = get_interface_ip($ubif);
911
			if (is_ipaddrv4($ifip)) {
912
				// IPv4 is handled via NAT networks below
913
			}
914
			$ifip = get_interface_ipv6($ubif);
915
			if (is_ipaddrv6($ifip)) {
916
				if (!is_linklocal($ifip)) {
917
					$subnet_bits = get_interface_subnetv6($ubif);
918
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
919
					// only add LAN-type interfaces
920
					if (!interface_has_gateway($ubif)) {
921
						$aclnets[] = "{$subnet_ip}/{$subnet_bits}";
922
					}
923
				}
924
				// add for IPv6 static routes to local networks
925
				// for safety, we include only routes reachable on an interface with no
926
				// gateway specified - read: not an Internet connection.
927
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
928
				foreach ($static_routes as $route) {
929
					if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
930
						// route is on this interface, interface doesn't have gateway, add it
931
						$aclnets[] = $route['network'];
932
					}
933
				}
934
			}
935
		}
936

    
937
		// OpenVPN IPv6 Tunnel Networks
938
		foreach (array('openvpn-client', 'openvpn-server') as $ovpnentry) {
939
			if (is_array($config['openvpn'][$ovpnentry])) {
940
				foreach ($config['openvpn'][$ovpnentry] as $ovpnent) {
941
					if (!isset($ovpnent['disable']) && !empty($ovpnent['tunnel_networkv6'])) {
942
						$aclnets[] = implode('/', openvpn_gen_tunnel_network($ovpnent['tunnel_networkv6']));
943
					}
944
				}
945
			}
946
		}
947
		// IPsec Mobile Virtual IPv6 Address Pool
948
		if ((isset($config['ipsec']['client']['enable'])) &&
949
		    (!empty($config['ipsec']['client']['pool_address_v6'])) &&
950
		    (!empty($config['ipsec']['client']['pool_netbits_v6']))) {
951
			$aclnets[] = "{$config['ipsec']['client']['pool_address_v6']}/{$config['ipsec']['client']['pool_netbits_v6']}";
952
		}
953

    
954
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
955
		if (empty($FilterIflist)) {
956
			filter_generate_optcfg_array();
957
		}
958
		$aclnets = array_merge($aclnets, filter_nat_rules_automatic_tonathosts());
959

    
960
		/* Automatic ACL networks deduplication and sorting
961
		 * https://redmine.pfsense.org/issues/11309 */
962
		$aclnets4 = array();
963
		$aclnets6 = array();
964
		foreach (array_unique($aclnets) as $acln) {
965
			if (is_v4($acln)) {
966
				$aclnets4[] = $acln;
967
			} else {
968
				$aclnets6[] = $acln;
969
			}
970
		}
971
		/* ipcmp only supports IPv4 */
972
		usort($aclnets4, "ipcmp");
973
		sort($aclnets6);
974

    
975
		foreach (array_merge($aclnets4, $aclnets6) as $acln) {
976
			/* Do not form an invalid directive with an empty address */
977
			if (empty($acln)) {
978
				continue;
979
			}
980
			$aclcfg .= "access-control: {$acln} allow \n";
981
		}
982
	}
983

    
984
	// Configure the custom ACLs
985
	if (is_array($config['unbound']['acls'])) {
986
		foreach ($config['unbound']['acls'] as $unbound_acl) {
987
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
988
			foreach ($unbound_acl['row'] as $network) {
989
				if ($unbound_acl['aclaction'] == "allow snoop") {
990
					$unbound_acl['aclaction'] = "allow_snoop";
991
				} elseif ($unbound_acl['aclaction'] == "deny nonlocal") {
992
					$unbound_acl['aclaction'] = "deny_non_local";
993
				} elseif ($unbound_acl['aclaction'] == "refuse nonlocal") {
994
					$unbound_acl['aclaction'] = "refuse_non_local";
995
				}
996
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
997
			}
998
		}
999
	}
1000
	// Write out Access list
1001
	create_unbound_chroot_path($cfgsubdir);
1002
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
1003

    
1004
}
1005

    
1006
// Generate hosts and reload services
1007
function unbound_hosts_generate() {
1008
	// Generate our hosts file
1009
	unbound_add_host_entries();
1010

    
1011
	// Reload our service to read the updates
1012
	unbound_control("reload");
1013
}
1014

    
1015
// Array of valid unbound local zone types
1016
function unbound_local_zone_types() {
1017
	return array(
1018
		"deny" => gettext("Deny"),
1019
		"refuse" => gettext("Refuse"),
1020
		"static" => gettext("Static"),
1021
		"transparent" => gettext("Transparent"),
1022
		"typetransparent" => gettext("Type Transparent"),
1023
		"redirect" => gettext("Redirect"),
1024
		"inform" => gettext("Inform"),
1025
		"inform_deny" => gettext("Inform Deny"),
1026
		"nodefault" => gettext("No Default")
1027
	);
1028
}
1029

    
1030
// Autoconfig EDNS buffer size
1031
function unbound_auto_ednsbufsize() {
1032
	global $config;
1033

    
1034
	$active_ipv6_inf = false;
1035
	if ($config['unbound']['active_interface'] != 'all') {
1036
		$active_interfaces = explode(",", $config['unbound']['active_interface']);
1037
	} else {
1038
		$active_interfaces = get_configured_interface_list();
1039
	}
1040

    
1041
	$min_mtu = get_interface_mtu(get_real_interface($active_interfaces[0]));
1042
	foreach ($active_interfaces as $ubif) {
1043
		$ubif_mtu = get_interface_mtu(get_real_interface($ubif));
1044
		if (get_interface_ipv6($ubif)) {
1045
			$active_ipv6_inf = true;
1046
		}
1047
		if ($ubif_mtu < $min_mtu) {
1048
			$min_mtu = $ubif_mtu;
1049
		}
1050
	}
1051

    
1052
	// maximum IPv4 + UDP header = 68 bytes
1053
	$min_mtu = $min_mtu - 68;
1054

    
1055
	if (($min_mtu < 1232) && $active_ipv6_inf) {
1056
		$min_mtu = 1232;
1057
	} elseif ($min_mtu < 512) {
1058
		$min_mtu = 512;
1059
	}	
1060

    
1061
	return $min_mtu;
1062
}
1063

    
1064
?>
(51-51/61)