Project

General

Profile

Download (27.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * unbound.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2015 Warren Baker <warren@percol8.co.za>
7
 * Copyright (c) 2015-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(($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: 172.16.0.0/12
174
private-address: 169.254.0.0/16
175
private-address: 192.168.0.0/16
176
private-address: fd00::/8
177
private-address: fe80::/10
178
EOF;
179
	}
180

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

    
213
	// SSL Configuration
214
	$sslconfig = "";
215
	if (isset($unboundcfg['enablessl'])) {
216
		$sslcert_path = "{$g['unbound_chroot_path']}/sslcert.crt";
217
		$sslkey_path = "{$g['unbound_chroot_path']}/sslcert.key";
218

    
219
		// Enable SSL on the chosen or default port
220
		$sslconfig .= "ssl-port: {$sslport}\n";
221

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

    
230
		// Write CA and Server Cert
231
		file_put_contents($sslcert_path, $cert_chain);
232
		chmod($sslcert_path, 0644);
233
		file_put_contents($sslkey_path, base64_decode($cert['prv']));
234
		chmod($sslkey_path, 0600);
235

    
236
		// Add config for CA and Server Cert
237
		$sslconfig .= "ssl-service-pem: \"{$sslcert_path}\"\n";
238
		$sslconfig .= "ssl-service-key: \"{$sslkey_path}\"\n";
239
	}
240

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

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

    
267
	// Configure Unbound statistics
268
	$statistics = unbound_statistics();
269

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

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

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

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

    
334
		if (!empty($dnsservers)) {
335
			$forward_conf .=<<<EOD
336
# Forwarding
337
forward-zone:
338
	name: "."
339

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

    
355
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
356
	$rrset_cache_size = $msg_cache_size * 2;
357

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

    
370
	$unboundconf = <<<EOD
371
##########################
372
# Unbound Configuration
373
##########################
374

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

    
433
# Access lists
434
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
435

    
436
# Static host entries
437
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
438

    
439
# dhcp lease entries
440
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
441

    
442
{$openvpn_clients_conf}
443

    
444
# Domain overrides
445
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
446
{$forward_conf}
447

    
448
{$custom_options}
449

    
450
###
451
# Remote Control Config
452
###
453
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
454

    
455
EOD;
456

    
457
	return $unboundconf;
458
}
459

    
460
function unbound_remote_control_setup($cfgsubdir = "") {
461
	global $g;
462

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

    
474
EOF;
475

    
476
		create_unbound_chroot_path($cfgsubdir);
477
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
478

    
479
		// Generate our keys
480
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
481

    
482
	}
483
}
484

    
485
function sync_unbound_service() {
486
	global $config, $g;
487

    
488
	create_unbound_chroot_path();
489

    
490
	// Configure our Unbound service
491
	do_as_unbound_user("unbound-anchor");
492
	unbound_remote_control_setup();
493
	unbound_generate_config();
494
	do_as_unbound_user("start");
495
	require_once("service-utils.inc");
496
	if (is_service_running("unbound")) {
497
		do_as_unbound_user("restore_cache");
498
	}
499

    
500
}
501

    
502
function unbound_acl_id_used($id) {
503
	global $config;
504

    
505
	if (is_array($config['unbound']['acls'])) {
506
		foreach ($config['unbound']['acls'] as & $acls) {
507
			if ($id == $acls['aclid']) {
508
				return true;
509
			}
510
		}
511
	}
512

    
513
	return false;
514
}
515

    
516
function unbound_get_next_id() {
517
	$aclid = 0;
518
	while (unbound_acl_id_used($aclid)) {
519
		$aclid++;
520
	}
521
	return $aclid;
522
}
523

    
524
// Execute commands as the user unbound
525
function do_as_unbound_user($cmd, $param1 = "") {
526
	global $g;
527

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

    
562
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
563
	global $config, $g;
564

    
565
	$domains = $config['unbound']['domainoverrides'];
566

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

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

    
611
	if ($pvt_rev != "") {
612
		return $domain_entries;
613
	} else {
614
		create_unbound_chroot_path($cfgsubdir);
615
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
616
	}
617
}
618

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

    
654
function unbound_add_host_entries($cfgsubdir = "") {
655
	global $config, $g;
656

    
657
	$hosts = system_hosts_entries($config['unbound']);
658

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

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

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

    
699
	// Write out entries
700
	create_unbound_chroot_path($cfgsubdir);
701
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
702

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

    
707
function unbound_control($action) {
708
	global $config, $g;
709

    
710
	$cache_dumpfile = "/var/tmp/unbound_cache";
711

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

    
748
	}
749
}
750

    
751
// Generation of Unbound statistics
752
function unbound_statistics() {
753
	global $config;
754

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

    
775
EOF;
776

    
777
	return $stats;
778
}
779

    
780
// Unbound Access lists
781
function unbound_acls_config($cfgsubdir = "") {
782
	global $g, $config;
783

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

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

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

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

    
856
}
857

    
858
// Generate hosts and reload services
859
function unbound_hosts_generate() {
860
	// Generate our hosts file
861
	unbound_add_host_entries();
862

    
863
	// Reload our service to read the updates
864
	unbound_control("reload");
865
}
866

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

    
882
?>
(50-50/60)