Project

General

Profile

Download (27.4 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-2018 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * originally part of m0n0wall (http://m0n0.ch/wall)
11
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
12
 * All rights reserved.
13
 *
14
 * Licensed under the Apache License, Version 2.0 (the "License");
15
 * you may not use this file except in compliance with the License.
16
 * You may obtain a copy of the License at
17
 *
18
 * http://www.apache.org/licenses/LICENSE-2.0
19
 *
20
 * Unless required by applicable law or agreed to in writing, software
21
 * distributed under the License is distributed on an "AS IS" BASIS,
22
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
 * See the License for the specific language governing permissions and
24
 * limitations under the License.
25
 */
26

    
27
/* include all configuration functions */
28
require_once("config.inc");
29
require_once("functions.inc");
30
require_once("filter.inc");
31
require_once("shaper.inc");
32

    
33
function create_unbound_chroot_path($cfgsubdir = "") {
34
	global $config, $g;
35

    
36
	// Configure chroot
37
	if (!is_dir($g['unbound_chroot_path'])) {
38
		mkdir($g['unbound_chroot_path']);
39
		chown($g['unbound_chroot_path'], "unbound");
40
		chgrp($g['unbound_chroot_path'], "unbound");
41
	}
42

    
43
	if ($cfgsubdir != "") {
44
		$cfgdir = $g['unbound_chroot_path'] . $cfgsubdir;
45
		if (!is_dir($cfgdir)) {
46
			mkdir($cfgdir);
47
			chown($cfgdir, "unbound");
48
			chgrp($cfgdir, "unbound");
49
		}
50
	}
51
}
52

    
53
/* Optimize Unbound for environment */
54
function unbound_optimization() {
55
	global $config;
56

    
57
	$optimization_settings = array();
58

    
59
	/*
60
	 * Set the number of threads equal to number of CPUs.
61
	 * Use 1 to disable threading, if for some reason this sysctl fails.
62
	 */
63
	$numprocs = intval(get_single_sysctl('kern.smp.cpus'));
64
	if ($numprocs > 1) {
65
		$optimization['number_threads'] = "num-threads: {$numprocs}";
66
		$optimize_num = pow(2, floor(log($numprocs, 2)));
67
	} else {
68
		$optimization['number_threads'] = "num-threads: 1";
69
		$optimize_num = 4;
70
	}
71

    
72
	// Slabs to help reduce lock contention.
73
	$optimization['msg_cache_slabs'] = "msg-cache-slabs: {$optimize_num}";
74
	$optimization['rrset_cache_slabs'] = "rrset-cache-slabs: {$optimize_num}";
75
	$optimization['infra_cache_slabs'] = "infra-cache-slabs: {$optimize_num}";
76
	$optimization['key_cache_slabs'] = "key-cache-slabs: {$optimize_num}";
77

    
78
	/*
79
	 * Larger socket buffer for busy servers
80
	 * Check that it is set to 4MB (by default the OS has it configured to 4MB)
81
	 */
82
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
83
		foreach ($config['sysctl']['item'] as $tunable) {
84
			if ($tunable['tunable'] == 'kern.ipc.maxsockbuf') {
85
				$so = floor((intval($tunable['value'])/1024/1024)-4);
86
				// Check to ensure that the number is not a negative
87
				if ($so >= 4) {
88
					// Limit to 32MB, users might set maxsockbuf very high for other reasons.
89
					// We do not want unbound to fail because of that.
90
					$so = min($so, 32);
91
					$optimization['so_rcvbuf'] = "so-rcvbuf: {$so}m";
92
				} else {
93
					unset($optimization['so_rcvbuf']);
94
				}
95
			}
96
		}
97
	}
98
	// Safety check in case kern.ipc.maxsockbuf is not available.
99
	if (!isset($optimization['so_rcvbuf'])) {
100
		$optimization['so_rcvbuf'] = "#so-rcvbuf: 4m";
101
	}
102

    
103
	return $optimization;
104

    
105
}
106

    
107
function test_unbound_config($unboundcfg, &$output) {
108
	global $g;
109

    
110
	$cfgsubdir = "/test";
111
	$cfgdir = "{$g['unbound_chroot_path']}{$cfgsubdir}";
112
	rmdir_recursive($cfgdir);
113

    
114
	unbound_generate_config($unboundcfg, $cfgsubdir);
115
	unbound_remote_control_setup($cfgsubdir);
116
	do_as_unbound_user("unbound-anchor", $cfgsubdir);
117

    
118
	$rv = 0;
119
	exec("/usr/local/sbin/unbound-checkconf {$cfgdir}/unbound.conf 2>&1",
120
	    $output, $rv);
121

    
122
	if ($rv == 0) {
123
		rmdir_recursive($cfgdir);
124
	}
125

    
126
	return $rv;
127
}
128

    
129

    
130
function unbound_generate_config($unboundcfg = NULL, $cfgsubdir = "") {
131
	global $g;
132

    
133
	$unboundcfgtxt = unbound_generate_config_text($unboundcfg, $cfgsubdir);
134

    
135
	// Configure static Host entries
136
	unbound_add_host_entries($cfgsubdir);
137

    
138
	// Configure Domain Overrides
139
	unbound_add_domain_overrides("", $cfgsubdir);
140

    
141
	// Configure Unbound access-lists
142
	unbound_acls_config($cfgsubdir);
143

    
144
	create_unbound_chroot_path($cfgsubdir);
145
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound.conf", $unboundcfgtxt);
146
}
147

    
148

    
149
function unbound_generate_config_text($unboundcfg = NULL, $cfgsubdir = "") {
150

    
151
	global $config, $g;
152
	if (is_null($unboundcfg)) {
153
		$unboundcfg = $config['unbound'];
154
	}
155

    
156
	// Setup optimization
157
	$optimization = unbound_optimization();
158

    
159
	// Setup DNSSEC support
160
	if (isset($unboundcfg['dnssec'])) {
161
		$module_config = "validator iterator";
162
		$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}{$cfgsubdir}/root.key";
163
	} else {
164
		$module_config = "iterator";
165
	}
166

    
167
	// Setup DNS Rebinding
168
	if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
169
		// Private-addresses for DNS Rebinding
170
		$private_addr = <<<EOF
171
# For DNS Rebinding prevention
172
private-address: 10.0.0.0/8
173
private-address: ::ffff:a00:0/104
174
private-address: 172.16.0.0/12
175
private-address: ::ffff:ac10:0/108
176
private-address: 169.254.0.0/16
177
private-address: ::ffff:a9fe:0/112
178
private-address: 192.168.0.0/16
179
private-address: ::ffff:c0a8:0/112
180
private-address: fd00::/8
181
private-address: fe80::/10
182
EOF;
183
	}
184

    
185
	// Determine interfaces where unbound will bind
186
	$sslport = is_numeric($unboundcfg['sslport']) ? $unboundcfg['sslport'] : "853";
187
	$bindintcfg = "";
188
	$bindints = array();
189
	$active_interfaces = explode(",", $unboundcfg['active_interface']);
190
	if (empty($unboundcfg['active_interface']) || in_array("all", $active_interfaces, true)) {
191
		$bindints[] = "0.0.0.0";
192
		$bindints[] = "::0";
193
		$bindintcfg .= "interface-automatic: " . (isset($unboundcfg['enablessl']) ? "no" : "yes") . "\n";
194
	} else {
195
		foreach ($active_interfaces as $ubif) {
196
			if (is_ipaddr($ubif)) {
197
				$bindints[] = $ubif;
198
			} else {
199
				$intip = get_interface_ip($ubif);
200
				if (is_ipaddrv4($intip)) {
201
					$bindints[] = $intip;
202
				}
203
				$intip = get_interface_ipv6($ubif);
204
				if (is_ipaddrv6($intip)) {
205
					$bindints[] = $intip;
206
				}
207
			}
208
		}
209
	}
210
	foreach ($bindints as $bindint) {
211
		$bindintcfg .= "interface: {$bindint}\n";
212
		if (isset($unboundcfg['enablessl'])) {
213
			$bindintcfg .= "interface: {$bindint}@{$sslport}\n";
214
		}
215
	}
216

    
217
	// SSL Configuration
218
	$sslconfig = "";
219
	if (isset($unboundcfg['enablessl'])) {
220
		$sslcert_path = "{$g['unbound_chroot_path']}/sslcert.crt";
221
		$sslkey_path = "{$g['unbound_chroot_path']}/sslcert.key";
222

    
223
		// Enable SSL on the chosen or default port
224
		$sslconfig .= "ssl-port: {$sslport}\n";
225

    
226
		// Lookup CA and Server Cert
227
		$cert = lookup_cert($unboundcfg['sslcertref']);
228
		$ca = ca_chain($cert);
229
		$cert_chain = base64_decode($cert['crt']);
230
		if (!empty($ca)) {
231
			$cert_chain .= "\n" . $ca;
232
		}
233

    
234
		// Write CA and Server Cert
235
		file_put_contents($sslcert_path, $cert_chain);
236
		chmod($sslcert_path, 0644);
237
		file_put_contents($sslkey_path, base64_decode($cert['prv']));
238
		chmod($sslkey_path, 0600);
239

    
240
		// Add config for CA and Server Cert
241
		$sslconfig .= "ssl-service-pem: \"{$sslcert_path}\"\n";
242
		$sslconfig .= "ssl-service-key: \"{$sslkey_path}\"\n";
243
	}
244

    
245
	// Determine interfaces to run on
246
	$outgoingints = "";
247
	if (!empty($unboundcfg['outgoing_interface'])) {
248
		$outgoingints = "# Outgoing interfaces to be used\n";
249
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
250
		foreach ($outgoing_interfaces as $outif) {
251
			$outip = get_interface_ip($outif);
252
			if (is_ipaddr($outip)) {
253
				$outgoingints .= "outgoing-interface: $outip\n";
254
			}
255
			$outip = get_interface_ipv6($outif);
256
			if (is_ipaddrv6($outip)) {
257
				$outgoingints .= "outgoing-interface: $outip\n";
258
			}
259
		}
260
	}
261

    
262
	// Allow DNS Rebind for forwarded domains
263
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
264
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
265
			$private_domains = "# Set private domains in case authoritative name server returns a Private IP address\n";
266
			$private_domains .= unbound_add_domain_overrides("private");
267
		}
268
		$reverse_zones .= unbound_add_domain_overrides("reverse");
269
	}
270

    
271
	// Configure Unbound statistics
272
	$statistics = unbound_statistics();
273

    
274
	// Add custom Unbound options
275
	if ($unboundcfg['custom_options']) {
276
		$custom_options_source = explode("\n", base64_decode($unboundcfg['custom_options']));
277
		$custom_options = "# Unbound custom options\n";
278
		foreach ($custom_options_source as $ent) {
279
			$custom_options .= $ent."\n";
280
		}
281
	}
282

    
283
	// Server configuration variables
284
	$port = (is_port($unboundcfg['port'])) ? $unboundcfg['port'] : "53";
285
	$hide_identity = isset($unboundcfg['hideidentity']) ? "yes" : "no";
286
	$hide_version = isset($unboundcfg['hideversion']) ? "yes" : "no";
287
	$ipv6_allow = isset($config['system']['ipv6allow']) ? "yes" : "no";
288
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
289
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
290
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
291
	$dns_record_cache = isset($unboundcfg['dnsrecordcache']) ? "yes" : "no";
292
	$outgoing_num_tcp = isset($unboundcfg['outgoing_num_tcp']) ? $unboundcfg['outgoing_num_tcp'] : "10";
293
	$incoming_num_tcp = isset($unboundcfg['incoming_num_tcp']) ? $unboundcfg['incoming_num_tcp'] : "10";
294
	$edns_buffer_size = (!empty($unboundcfg['edns_buffer_size'])) ? $unboundcfg['edns_buffer_size'] : "4096";
295
	$num_queries_per_thread = (!empty($unboundcfg['num_queries_per_thread'])) ? $unboundcfg['num_queries_per_thread'] : "4096";
296
	$jostle_timeout = (!empty($unboundcfg['jostle_timeout'])) ? $unboundcfg['jostle_timeout'] : "200";
297
	$cache_max_ttl = (!empty($unboundcfg['cache_max_ttl'])) ? $unboundcfg['cache_max_ttl'] : "86400";
298
	$cache_min_ttl = (!empty($unboundcfg['cache_min_ttl'])) ? $unboundcfg['cache_min_ttl'] : "0";
299
	$infra_host_ttl = (!empty($unboundcfg['infra_host_ttl'])) ? $unboundcfg['infra_host_ttl'] : "900";
300
	$infra_cache_numhosts = (!empty($unboundcfg['infra_cache_numhosts'])) ? $unboundcfg['infra_cache_numhosts'] : "10000";
301
	$unwanted_reply_threshold = (!empty($unboundcfg['unwanted_reply_threshold'])) ? $unboundcfg['unwanted_reply_threshold'] : "0";
302
	if ($unwanted_reply_threshold == "disabled") {
303
		$unwanted_reply_threshold = "0";
304
	}
305
	$msg_cache_size = (!empty($unboundcfg['msgcachesize'])) ? $unboundcfg['msgcachesize'] : "4";
306
	$verbosity = isset($unboundcfg['log_verbosity']) ? $unboundcfg['log_verbosity'] : 1;
307
	$use_caps = isset($unboundcfg['use_caps']) ? "yes" : "no";
308

    
309
	if (isset($unboundcfg['regovpnclients'])) {
310
		$openvpn_clients_conf .=<<<EOD
311
# OpenVPN client entries
312
include: {$g['unbound_chroot_path']}{$cfgsubdir}/openvpn.*.conf
313
EOD;
314
	} else {
315
		$openvpn_clients_conf = '';
316
	}
317

    
318
	// Set up forwarding if it is configured
319
	if (isset($unboundcfg['forwarding'])) {
320
		$dnsservers = array();
321
		if (isset($config['system']['dnsallowoverride'])) {
322
			$ns = array_unique(get_nameservers());
323
			foreach ($ns as $nameserver) {
324
				if ($nameserver) {
325
					$dnsservers[] = $nameserver;
326
				}
327
			}
328
		} else {
329
			$ns = array();
330
		}
331
		$sys_dnsservers = array_unique(get_dns_servers());
332
		foreach ($sys_dnsservers as $sys_dnsserver) {
333
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
334
				$dnsservers[] = $sys_dnsserver;
335
			}
336
		}
337

    
338
		if (!empty($dnsservers)) {
339
			$forward_conf .=<<<EOD
340
# Forwarding
341
forward-zone:
342
	name: "."
343

    
344
EOD;
345
			if (isset($unboundcfg['forward_tls_upstream'])) {
346
				$forward_conf .= "\tforward-tls-upstream: yes\n";
347
			}
348
			foreach ($dnsservers as $dnsserver) {
349
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
350
					$fwdport = isset($unboundcfg['forward_tls_upstream']) ? "@853" : "";
351
					$forward_conf .= "\tforward-addr: {$dnsserver}{$fwdport}\n";
352
				}
353
			}
354
		}
355
	} else {
356
		$forward_conf = "";
357
	}
358

    
359
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
360
	$rrset_cache_size = $msg_cache_size * 2;
361

    
362
	/* QNAME Minimization. https://redmine.pfsense.org/issues/8028
363
	 * Unbound uses the British style in the option name so the internal option
364
	 * name follows that, but the user-visible descriptions follow US English.
365
	 */
366
	$qname_min = "";
367
	if (isset($unboundcfg['qname-minimisation'])) {
368
		$qname_min = "qname-minimisation: yes\n";
369
		if (isset($unboundcfg['qname-minimisation-strict'])) {
370
			$qname_min .= "qname-minimisation-strict: yes\n";
371
		}
372
	}
373

    
374
	$unboundconf = <<<EOD
375
##########################
376
# Unbound Configuration
377
##########################
378

    
379
##
380
# Server configuration
381
##
382
server:
383
{$reverse_zones}
384
chroot: {$g['unbound_chroot_path']}
385
username: "unbound"
386
directory: "{$g['unbound_chroot_path']}"
387
pidfile: "/var/run/unbound.pid"
388
use-syslog: yes
389
port: {$port}
390
verbosity: {$verbosity}
391
hide-identity: {$hide_identity}
392
hide-version: {$hide_version}
393
harden-glue: yes
394
do-ip4: yes
395
do-ip6: {$ipv6_allow}
396
do-udp: yes
397
do-tcp: yes
398
do-daemonize: yes
399
module-config: "{$module_config}"
400
unwanted-reply-threshold: {$unwanted_reply_threshold}
401
num-queries-per-thread: {$num_queries_per_thread}
402
jostle-timeout: {$jostle_timeout}
403
infra-host-ttl: {$infra_host_ttl}
404
infra-cache-numhosts: {$infra_cache_numhosts}
405
outgoing-num-tcp: {$outgoing_num_tcp}
406
incoming-num-tcp: {$incoming_num_tcp}
407
edns-buffer-size: {$edns_buffer_size}
408
cache-max-ttl: {$cache_max_ttl}
409
cache-min-ttl: {$cache_min_ttl}
410
harden-dnssec-stripped: {$harden_dnssec_stripped}
411
msg-cache-size: {$msg_cache_size}m
412
rrset-cache-size: {$rrset_cache_size}m
413
{$qname_min}
414
{$optimization['number_threads']}
415
{$optimization['msg_cache_slabs']}
416
{$optimization['rrset_cache_slabs']}
417
{$optimization['infra_cache_slabs']}
418
{$optimization['key_cache_slabs']}
419
outgoing-range: 4096
420
{$optimization['so_rcvbuf']}
421
{$anchor_file}
422
prefetch: {$prefetch}
423
prefetch-key: {$prefetch_key}
424
use-caps-for-id: {$use_caps}
425
serve-expired: {$dns_record_cache}
426
# Statistics
427
{$statistics}
428
# SSL Configuration
429
{$sslconfig}
430
# Interface IP(s) to bind to
431
{$bindintcfg}
432
{$outgoingints}
433
# DNS Rebinding
434
{$private_addr}
435
{$private_domains}
436

    
437
# Access lists
438
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
439

    
440
# Static host entries
441
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
442

    
443
# dhcp lease entries
444
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
445

    
446
{$openvpn_clients_conf}
447

    
448
# Domain overrides
449
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
450
{$forward_conf}
451

    
452
{$custom_options}
453

    
454
###
455
# Remote Control Config
456
###
457
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
458

    
459
EOD;
460

    
461
	return $unboundconf;
462
}
463

    
464
function unbound_remote_control_setup($cfgsubdir = "") {
465
	global $g;
466

    
467
	if (!file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") || !file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key")) {
468
		$remotcfg = <<<EOF
469
remote-control:
470
	control-enable: yes
471
	control-interface: 127.0.0.1
472
	control-port: 953
473
	server-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.key"
474
	server-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.pem"
475
	control-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key"
476
	control-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.pem"
477

    
478
EOF;
479

    
480
		create_unbound_chroot_path($cfgsubdir);
481
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
482

    
483
		// Generate our keys
484
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
485

    
486
	}
487
}
488

    
489
function sync_unbound_service() {
490
	global $config, $g;
491

    
492
	create_unbound_chroot_path();
493

    
494
	// Configure our Unbound service
495
	do_as_unbound_user("unbound-anchor");
496
	unbound_remote_control_setup();
497
	unbound_generate_config();
498
	do_as_unbound_user("start");
499
	require_once("service-utils.inc");
500
	if (is_service_running("unbound")) {
501
		do_as_unbound_user("restore_cache");
502
	}
503

    
504
}
505

    
506
function unbound_acl_id_used($id) {
507
	global $config;
508

    
509
	if (is_array($config['unbound']['acls'])) {
510
		foreach ($config['unbound']['acls'] as & $acls) {
511
			if ($id == $acls['aclid']) {
512
				return true;
513
			}
514
		}
515
	}
516

    
517
	return false;
518
}
519

    
520
function unbound_get_next_id() {
521
	$aclid = 0;
522
	while (unbound_acl_id_used($aclid)) {
523
		$aclid++;
524
	}
525
	return $aclid;
526
}
527

    
528
// Execute commands as the user unbound
529
function do_as_unbound_user($cmd, $param1 = "") {
530
	global $g;
531

    
532
	switch ($cmd) {
533
		case "start":
534
			mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
535
			break;
536
		case "stop":
537
			mwexec("echo '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf stop' | /usr/bin/su -m unbound", true);
538
			break;
539
		case "reload":
540
			mwexec("echo '/usr/local/sbin/unbound-control -c {$g['unbound_chroot_path']}/unbound.conf reload' | /usr/bin/su -m unbound", true);
541
			break;
542
		case "unbound-anchor":
543
			$root_key_file = "{$g['unbound_chroot_path']}{$param1}/root.key";
544
			// sanity check root.key because unbound-anchor will fail without manual removal otherwise. redmine #5334
545
			if (file_exists($root_key_file)) {
546
				$rootkeycheck = mwexec("/usr/bin/grep 'autotrust trust anchor file' {$root_key_file}", true);
547
				if ($rootkeycheck != "0") {
548
					log_error("Unbound {$root_key_file} file is corrupt, removing and recreating.");
549
					unlink_if_exists($root_key_file);
550
				}
551
			}
552
			mwexec("echo '/usr/local/sbin/unbound-anchor -a {$root_key_file}' | /usr/bin/su -m unbound", true);
553
			// Only sync the file if this is the real (default) one, not a test one.
554
			if ($param1 == "") {
555
				pfSense_fsync($root_key_file);
556
			}
557
			break;
558
		case "unbound-control-setup":
559
			mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}{$param1}' | /usr/bin/su -m unbound", true);
560
			break;
561
		default:
562
			break;
563
	}
564
}
565

    
566
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
567
	global $config, $g;
568

    
569
	$domains = $config['unbound']['domainoverrides'];
570

    
571
	$sorted_domains = msort($domains, "domain");
572
	$result = array();
573
	$tls_domains = array();
574
	foreach ($sorted_domains as $domain) {
575
		$domain_key = current($domain);
576
		if (!isset($result[$domain_key])) {
577
			$result[$domain_key] = array();
578
		}
579
		$result[$domain_key][] = $domain['ip'];
580
		/* If any entry for a domain has TLS set, it will be active for all entries. */
581
		if (isset($domain['forward_tls_upstream'])) {
582
			$tls_domains[] = $domain_key;
583
		}
584
	}
585

    
586
	// Domain overrides that have multiple entries need multiple stub-addr: added
587
	$domain_entries = "";
588
	foreach ($result as $domain=>$ips) {
589
		if ($pvt_rev == "private") {
590
			$domain_entries .= "private-domain: \"$domain\"\n";
591
			$domain_entries .= "domain-insecure: \"$domain\"\n";
592
		} else if ($pvt_rev == "reverse") {
593
			if ((substr($domain, -14) == ".in-addr.arpa.") || (substr($domain, -13) == ".in-addr.arpa")) {
594
				$domain_entries .= "local-zone: \"$domain\" typetransparent\n";
595
			}
596
		} else {
597
			$domain_entries .= "forward-zone:\n";
598
			$domain_entries .= "\tname: \"$domain\"\n";
599
			$fwdport = "";
600
			/* Enable TLS forwarding for this domain if needed. */
601
			if (in_array($domain, $tls_domains)) {
602
				$domain_entries .= "\tforward-tls-upstream: yes\n";
603
				$fwdport = "@853";
604
			}
605
			foreach ($ips as $ip) {
606
				/* If an IP address already contains a port specification, do not add another. */
607
				if (strstr($ip, '@') !== false) {
608
					$fwdport = "";
609
				}
610
				$domain_entries .= "\tforward-addr: {$ip}{$fwdport}\n";
611
			}
612
		}
613
	}
614

    
615
	if ($pvt_rev != "") {
616
		return $domain_entries;
617
	} else {
618
		create_unbound_chroot_path($cfgsubdir);
619
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
620
	}
621
}
622

    
623
function unbound_generate_zone_data($domain, $hosts, &$added_ptr, $zone_type = "transparent", $write_domain_zone_declaration = false, $always_add_short_names = false) {
624
	global $config;
625
	if ($write_domain_zone_declaration) {
626
		$zone_data = "local-zone: \"{$domain}.\" {$zone_type}\n";
627
	} else {
628
		$zone_data = "";
629
	}
630
	foreach ($hosts as $host) {
631
		if (is_ipaddrv4($host['ipaddr'])) {
632
			$type = 'A';
633
		} else if (is_ipaddrv6($host['ipaddr'])) {
634
			$type = 'AAAA';
635
		} else {
636
			continue;
637
		}
638
		if (!$added_ptr[$host['ipaddr']]) {
639
			$zone_data .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
640
			$added_ptr[$host['ipaddr']] = true;
641
		}
642
		/* For the system localhost entry, write an entry for just the hostname. */
643
		if ((($host['name'] == "localhost") && ($domain == $config['system']['domain'])) || $always_add_short_names) {
644
			$zone_data .= "local-data: \"{$host['name']}. {$type} {$host['ipaddr']}\"\n";
645
		}
646
		/* Redirect zones must have a zone declaration that matches the
647
		 * local-data record exactly, it cannot have entries "under" the
648
		 * domain.
649
		 */
650
		if ($zone_type == "redirect") {
651
			$zone_data .= "local-zone: \"{$host['fqdn']}.\" {$zone_type}\n";;
652
		}
653
		$zone_data .= "local-data: \"{$host['fqdn']}. {$type} {$host['ipaddr']}\"\n";
654
	}
655
	return $zone_data;
656
}
657

    
658
function unbound_add_host_entries($cfgsubdir = "") {
659
	global $config, $g;
660

    
661
	$hosts = system_hosts_entries($config['unbound']);
662

    
663
	/* Pass 1: Build domain list and hosts inside domains */
664
	$hosts_by_domain = array();
665
	foreach ($hosts as $host) {
666
		if (!array_key_exists($host['domain'], $hosts_by_domain)) {
667
			$hosts_by_domain[$host['domain']] = array();
668
		}
669
		$hosts_by_domain[$host['domain']][] = $host;
670
	}
671

    
672
	$added_ptr = array();
673
	/* Build local zone data */
674
	// Check if auto add host entries is not set
675
	$system_domain_local_zone_type = "transparent";
676
	if (!isset($config['unbound']['disable_auto_added_host_entries'])) {
677
		// Make sure the config setting is a valid unbound local zone type.  If not use "transparent".
678
		if (array_key_exists($config['unbound']['system_domain_local_zone_type'], unbound_local_zone_types())) {
679
			$system_domain_local_zone_type = $config['unbound']['system_domain_local_zone_type'];
680
		}
681
	}
682
	/* Add entries for the system domain before all others */
683
	if (array_key_exists($config['system']['domain'], $hosts_by_domain)) {
684
		$unbound_entries .= unbound_generate_zone_data($config['system']['domain'],
685
					$hosts_by_domain[$config['system']['domain']],
686
					$added_ptr,
687
					$system_domain_local_zone_type,
688
					true);
689
		/* Unset this so it isn't processed again by the loop below. */
690
		unset($hosts_by_domain[$config['system']['domain']]);
691
	}
692

    
693
	/* Build zone data for other domain */
694
	foreach ($hosts_by_domain as $domain => $hosts) {
695
		$unbound_entries .= unbound_generate_zone_data($domain,
696
					$hosts,
697
					$added_ptr,
698
					"transparent",
699
					false,
700
					isset($config['unbound']['always_add_short_names']));
701
	}
702

    
703
	// Write out entries
704
	create_unbound_chroot_path($cfgsubdir);
705
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
706

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

    
711
function unbound_control($action) {
712
	global $config, $g;
713

    
714
	$cache_dumpfile = "/var/tmp/unbound_cache";
715

    
716
	switch ($action) {
717
	case "start":
718
		// Start Unbound
719
		if ($config['unbound']['enable'] == "on") {
720
			if (!is_service_running("unbound")) {
721
				do_as_unbound_user("start");
722
			}
723
		}
724
		break;
725
	case "stop":
726
		if ($config['unbound']['enable'] == "on") {
727
			do_as_unbound_user("stop");
728
		}
729
		break;
730
	case "reload":
731
		if ($config['unbound']['enable'] == "on") {
732
			do_as_unbound_user("reload");
733
		}
734
		break;
735
	case "dump_cache":
736
		// Dump Unbound's Cache
737
		if ($config['unbound']['dumpcache'] == "on") {
738
			do_as_unbound_user("dump_cache");
739
		}
740
		break;
741
	case "restore_cache":
742
		// Restore Unbound's Cache
743
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
744
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
745
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
746
			}
747
		}
748
		break;
749
	default:
750
		break;
751

    
752
	}
753
}
754

    
755
// Generation of Unbound statistics
756
function unbound_statistics() {
757
	global $config;
758

    
759
	if ($config['stats'] == "on") {
760
		$stats_interval = $config['unbound']['stats_interval'];
761
		$cumulative_stats = $config['cumulative_stats'];
762
		if ($config['extended_stats'] == "on") {
763
			$extended_stats = "yes";
764
		} else {
765
			$extended_stats = "no";
766
		}
767
	} else {
768
		$stats_interval = "0";
769
		$cumulative_stats = "no";
770
		$extended_stats = "no";
771
	}
772
	/* XXX To do - add RRD graphs */
773
	$stats = <<<EOF
774
# Unbound Statistics
775
statistics-interval: {$stats_interval}
776
extended-statistics: yes
777
statistics-cumulative: yes
778

    
779
EOF;
780

    
781
	return $stats;
782
}
783

    
784
// Unbound Access lists
785
function unbound_acls_config($cfgsubdir = "") {
786
	global $g, $config;
787

    
788
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
789
		$aclcfg = "access-control: 127.0.0.1/32 allow_snoop\n";
790
		$aclcfg .= "access-control: ::1 allow_snoop\n";
791
		// Add our networks for active interfaces including localhost
792
		if (!empty($config['unbound']['active_interface'])) {
793
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
794
			if (in_array("all", $active_interfaces)) {
795
				$active_interfaces = get_configured_interface_with_descr();
796
			}
797
		} else {
798
			$active_interfaces = get_configured_interface_with_descr();
799
		}
800

    
801
		foreach ($active_interfaces as $ubif => $ifdesc) {
802
			$ifip = get_interface_ip($ubif);
803
			if (is_ipaddrv4($ifip)) {
804
				// IPv4 is handled via NAT networks below
805
			}
806
			$ifip = get_interface_ipv6($ubif);
807
			if (is_ipaddrv6($ifip)) {
808
				if (!is_linklocal($ifip)) {
809
					$subnet_bits = get_interface_subnetv6($ubif);
810
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
811
					// only add LAN-type interfaces
812
					if (!interface_has_gateway($ubif)) {
813
						$aclcfg .= "access-control: {$subnet_ip}/{$subnet_bits} allow\n";
814
					}
815
				}
816
				// add for IPv6 static routes to local networks
817
				// for safety, we include only routes reachable on an interface with no
818
				// gateway specified - read: not an Internet connection.
819
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
820
				foreach ($static_routes as $route) {
821
					if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
822
						// route is on this interface, interface doesn't have gateway, add it
823
						$aclcfg .= "access-control: {$route['network']} allow\n";
824
					}
825
				}
826
			}
827
		}
828

    
829
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
830
		if (empty($FilterIflist)) {
831
			filter_generate_optcfg_array();
832
		}
833
		$natnetworks_array = array();
834
		$natnetworks_array = filter_nat_rules_automatic_tonathosts();
835
		foreach ($natnetworks_array as $allowednet) {
836
			$aclcfg .= "access-control: $allowednet allow \n";
837
		}
838
	}
839

    
840
	// Configure the custom ACLs
841
	if (is_array($config['unbound']['acls'])) {
842
		foreach ($config['unbound']['acls'] as $unbound_acl) {
843
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
844
			foreach ($unbound_acl['row'] as $network) {
845
				if ($unbound_acl['aclaction'] == "allow snoop") {
846
					$unbound_acl['aclaction'] = "allow_snoop";
847
				} elseif ($unbound_acl['aclaction'] == "deny nonlocal") {
848
					$unbound_acl['aclaction'] = "deny_non_local";
849
				} elseif ($unbound_acl['aclaction'] == "refuse nonlocal") {
850
					$unbound_acl['aclaction'] = "refuse_non_local";
851
				}
852
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
853
			}
854
		}
855
	}
856
	// Write out Access list
857
	create_unbound_chroot_path($cfgsubdir);
858
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
859

    
860
}
861

    
862
// Generate hosts and reload services
863
function unbound_hosts_generate() {
864
	// Generate our hosts file
865
	unbound_add_host_entries();
866

    
867
	// Reload our service to read the updates
868
	unbound_control("reload");
869
}
870

    
871
// Array of valid unbound local zone types
872
function unbound_local_zone_types() {
873
	return array(
874
		"deny" => gettext("Deny"),
875
		"refuse" => gettext("Refuse"),
876
		"static" => gettext("Static"),
877
		"transparent" => gettext("Transparent"),
878
		"typetransparent" => gettext("Type Transparent"),
879
		"redirect" => gettext("Redirect"),
880
		"inform" => gettext("Inform"),
881
		"inform_deny" => gettext("Inform Deny"),
882
		"nodefault" => gettext("No Default")
883
	);
884
}
885

    
886
?>
(50-50/60)