Project

General

Profile

Download (22.8 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 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
	unbound_generate_config($unboundcfg, $cfgsubdir);
112
	unbound_remote_control_setup($cfgsubdir);
113
	do_as_unbound_user("unbound-anchor", $cfgsubdir);
114

    
115
	$cfgdir = "{$g['unbound_chroot_path']}{$cfgsubdir}";
116

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

    
121
	return $rv;
122
}
123

    
124

    
125
function unbound_generate_config($unboundcfg = NULL, $cfgsubdir = "") {
126
	global $g;
127

    
128
	$unboundcfgtxt = unbound_generate_config_text($unboundcfg, $cfgsubdir);
129

    
130
	// Configure static Host entries
131
	unbound_add_host_entries($cfgsubdir);
132

    
133
	// Configure Domain Overrides
134
	unbound_add_domain_overrides("", $cfgsubdir);
135

    
136
	// Configure Unbound access-lists
137
	unbound_acls_config($cfgsubdir);
138

    
139
	create_unbound_chroot_path($cfgsubdir);
140
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound.conf", $unboundcfgtxt);
141
}
142

    
143

    
144
function unbound_generate_config_text($unboundcfg = NULL, $cfgsubdir = "") {
145

    
146
	global $config, $g;
147
	if (is_null($unboundcfg)) {
148
		$unboundcfg = $config['unbound'];
149
	}
150

    
151
	// Setup optimization
152
	$optimization = unbound_optimization();
153

    
154
	// Setup DNSSEC support
155
	if (isset($unboundcfg['dnssec'])) {
156
		$module_config = "validator iterator";
157
		$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}{$cfgsubdir}/root.key";
158
	} else {
159
		$module_config = "iterator";
160
	}
161

    
162
	// Setup DNS Rebinding
163
	if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
164
		// Private-addresses for DNS Rebinding
165
		$private_addr = <<<EOF
166
# For DNS Rebinding prevention
167
private-address: 10.0.0.0/8
168
private-address: 172.16.0.0/12
169
private-address: 169.254.0.0/16
170
private-address: 192.168.0.0/16
171
private-address: fd00::/8
172
private-address: fe80::/10
173
EOF;
174
	}
175

    
176
	// Determine interfaces to run on
177
	$bindints = "";
178
	if (!empty($unboundcfg['active_interface'])) {
179
		$active_interfaces = explode(",", $unboundcfg['active_interface']);
180
		if (in_array("all", $active_interfaces, true)) {
181
			$bindints .= "interface: 0.0.0.0\n";
182
			$bindints .= "interface: ::0\n";
183
			$bindints .= "interface-automatic: yes\n";
184
		} else {
185
			foreach ($active_interfaces as $ubif) {
186
				if (is_ipaddr($ubif)) {
187
					$bindints .= "interface: $ubif\n";
188
				} else {
189
					$intip = get_interface_ip($ubif);
190
					if (is_ipaddrv4($intip)) {
191
						$bindints .= "interface: $intip\n";
192
					}
193
					$intip = get_interface_ipv6($ubif);
194
					if (is_ipaddrv6($intip)) {
195
						$bindints .= "interface: $intip\n";
196
					}
197
				}
198
			}
199
		}
200
	} else {
201
		$bindints .= "interface: 0.0.0.0\n";
202
		$bindints .= "interface: ::0\n";
203
		/* If the active interface array is empty, treat it the same as "All" as is done above. Otherwise it breaks CARP with a default config. */
204
		$bindints .= "interface-automatic: yes\n";
205
	}
206

    
207
	// Determine interfaces to run on
208
	$outgoingints = "";
209
	if (!empty($unboundcfg['outgoing_interface'])) {
210
		$outgoingints = "# Outgoing interfaces to be used\n";
211
		$outgoing_interfaces = explode(",", $unboundcfg['outgoing_interface']);
212
		foreach ($outgoing_interfaces as $outif) {
213
			$outip = get_interface_ip($outif);
214
			if (is_ipaddr($outip)) {
215
				$outgoingints .= "outgoing-interface: $outip\n";
216
			}
217
			$outip = get_interface_ipv6($outif);
218
			if (is_ipaddrv6($outip)) {
219
				$outgoingints .= "outgoing-interface: $outip\n";
220
			}
221
		}
222
	}
223

    
224
	// Allow DNS Rebind for forwarded domains
225
	if (isset($unboundcfg['domainoverrides']) && is_array($unboundcfg['domainoverrides'])) {
226
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
227
			$private_domains = "# Set private domains in case authoritative name server returns a Private IP address\n";
228
			$private_domains .= unbound_add_domain_overrides("private");
229
		}
230
		$reverse_zones .= unbound_add_domain_overrides("reverse");
231
	}
232

    
233
	// Configure Unbound statistics
234
	$statistics = unbound_statistics();
235

    
236
	// Add custom Unbound options
237
	if ($unboundcfg['custom_options']) {
238
		$custom_options_source = explode("\n", base64_decode($unboundcfg['custom_options']));
239
		$custom_options = "# Unbound custom options\n";
240
		foreach ($custom_options_source as $ent) {
241
			$custom_options .= $ent."\n";
242
		}
243
	}
244

    
245
	// Server configuration variables
246
	$port = (is_port($unboundcfg['port'])) ? $unboundcfg['port'] : "53";
247
	$hide_identity = isset($unboundcfg['hideidentity']) ? "yes" : "no";
248
	$hide_version = isset($unboundcfg['hideversion']) ? "yes" : "no";
249
	$harden_dnssec_stripped = isset($unboundcfg['dnssecstripped']) ? "yes" : "no";
250
	$prefetch = isset($unboundcfg['prefetch']) ? "yes" : "no";
251
	$prefetch_key = isset($unboundcfg['prefetchkey']) ? "yes" : "no";
252
	$outgoing_num_tcp = isset($unboundcfg['outgoing_num_tcp']) ? $unboundcfg['outgoing_num_tcp'] : "10";
253
	$incoming_num_tcp = isset($unboundcfg['incoming_num_tcp']) ? $unboundcfg['incoming_num_tcp'] : "10";
254
	$edns_buffer_size = (!empty($unboundcfg['edns_buffer_size'])) ? $unboundcfg['edns_buffer_size'] : "4096";
255
	$num_queries_per_thread = (!empty($unboundcfg['num_queries_per_thread'])) ? $unboundcfg['num_queries_per_thread'] : "4096";
256
	$jostle_timeout = (!empty($unboundcfg['jostle_timeout'])) ? $unboundcfg['jostle_timeout'] : "200";
257
	$cache_max_ttl = (!empty($unboundcfg['cache_max_ttl'])) ? $unboundcfg['cache_max_ttl'] : "86400";
258
	$cache_min_ttl = (!empty($unboundcfg['cache_min_ttl'])) ? $unboundcfg['cache_min_ttl'] : "0";
259
	$infra_host_ttl = (!empty($unboundcfg['infra_host_ttl'])) ? $unboundcfg['infra_host_ttl'] : "900";
260
	$infra_cache_numhosts = (!empty($unboundcfg['infra_cache_numhosts'])) ? $unboundcfg['infra_cache_numhosts'] : "10000";
261
	$unwanted_reply_threshold = (!empty($unboundcfg['unwanted_reply_threshold'])) ? $unboundcfg['unwanted_reply_threshold'] : "0";
262
	if ($unwanted_reply_threshold == "disabled") {
263
		$unwanted_reply_threshold = "0";
264
	}
265
	$msg_cache_size = (!empty($unboundcfg['msgcachesize'])) ? $unboundcfg['msgcachesize'] : "4";
266
	$verbosity = isset($unboundcfg['log_verbosity']) ? $unboundcfg['log_verbosity'] : 1;
267
	$use_caps = isset($unboundcfg['use_caps']) ? "yes" : "no";
268

    
269
	// Set up forwarding if it is configured
270
	if (isset($unboundcfg['forwarding'])) {
271
		$dnsservers = array();
272
		if (isset($config['system']['dnsallowoverride'])) {
273
			$ns = array_unique(get_nameservers());
274
			foreach ($ns as $nameserver) {
275
				if ($nameserver) {
276
					$dnsservers[] = $nameserver;
277
				}
278
			}
279
		} else {
280
			$ns = array();
281
		}
282
		$sys_dnsservers = array_unique(get_dns_servers());
283
		foreach ($sys_dnsservers as $sys_dnsserver) {
284
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
285
				$dnsservers[] = $sys_dnsserver;
286
			}
287
		}
288

    
289
		if (!empty($dnsservers)) {
290
			$forward_conf .=<<<EOD
291
# Forwarding
292
forward-zone:
293
	name: "."
294

    
295
EOD;
296
			foreach ($dnsservers as $dnsserver) {
297
				if (is_ipaddr($dnsserver) && !ip_in_subnet($dnsserver, "127.0.0.0/8")) {
298
					$forward_conf .= "\tforward-addr: $dnsserver\n";
299
				}
300
			}
301
		}
302
	} else {
303
		$forward_conf = "";
304
	}
305

    
306
	// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
307
	$rrset_cache_size = $msg_cache_size * 2;
308

    
309
	$unboundconf = <<<EOD
310
##########################
311
# Unbound Configuration
312
##########################
313

    
314
##
315
# Server configuration
316
##
317
server:
318
{$reverse_zones}
319
chroot: {$g['unbound_chroot_path']}
320
username: "unbound"
321
directory: "{$g['unbound_chroot_path']}"
322
pidfile: "/var/run/unbound.pid"
323
use-syslog: yes
324
port: {$port}
325
verbosity: {$verbosity}
326
hide-identity: {$hide_identity}
327
hide-version: {$hide_version}
328
harden-glue: yes
329
do-ip4: yes
330
do-ip6: yes
331
do-udp: yes
332
do-tcp: yes
333
do-daemonize: yes
334
module-config: "{$module_config}"
335
unwanted-reply-threshold: {$unwanted_reply_threshold}
336
num-queries-per-thread: {$num_queries_per_thread}
337
jostle-timeout: {$jostle_timeout}
338
infra-host-ttl: {$infra_host_ttl}
339
infra-cache-numhosts: {$infra_cache_numhosts}
340
outgoing-num-tcp: {$outgoing_num_tcp}
341
incoming-num-tcp: {$incoming_num_tcp}
342
edns-buffer-size: {$edns_buffer_size}
343
cache-max-ttl: {$cache_max_ttl}
344
cache-min-ttl: {$cache_min_ttl}
345
harden-dnssec-stripped: {$harden_dnssec_stripped}
346
msg-cache-size: {$msg_cache_size}m
347
rrset-cache-size: {$rrset_cache_size}m
348

    
349
{$optimization['number_threads']}
350
{$optimization['msg_cache_slabs']}
351
{$optimization['rrset_cache_slabs']}
352
{$optimization['infra_cache_slabs']}
353
{$optimization['key_cache_slabs']}
354
outgoing-range: 4096
355
{$optimization['so_rcvbuf']}
356
{$anchor_file}
357
prefetch: {$prefetch}
358
prefetch-key: {$prefetch_key}
359
use-caps-for-id: {$use_caps}
360
# Statistics
361
{$statistics}
362
# Interface IP(s) to bind to
363
{$bindints}
364
{$outgoingints}
365

    
366
# DNS Rebinding
367
{$private_addr}
368
{$private_domains}
369

    
370
# Access lists
371
include: {$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf
372

    
373
# Static host entries
374
include: {$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf
375

    
376
# dhcp lease entries
377
include: {$g['unbound_chroot_path']}{$cfgsubdir}/dhcpleases_entries.conf
378

    
379
# Domain overrides
380
include: {$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf
381
{$forward_conf}
382

    
383
{$custom_options}
384

    
385
###
386
# Remote Control Config
387
###
388
include: {$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf
389

    
390
EOD;
391

    
392
	return $unboundconf;
393
}
394

    
395
function unbound_remote_control_setup($cfgsubdir = "") {
396
	global $g;
397

    
398
	if (!file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf") || !file_exists("{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key")) {
399
		$remotcfg = <<<EOF
400
remote-control:
401
	control-enable: yes
402
	control-interface: 127.0.0.1
403
	control-port: 953
404
	server-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.key"
405
	server-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_server.pem"
406
	control-key-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.key"
407
	control-cert-file: "{$g['unbound_chroot_path']}{$cfgsubdir}/unbound_control.pem"
408

    
409
EOF;
410

    
411
		create_unbound_chroot_path($cfgsubdir);
412
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/remotecontrol.conf", $remotcfg);
413

    
414
		// Generate our keys
415
		do_as_unbound_user("unbound-control-setup", $cfgsubdir);
416

    
417
	}
418
}
419

    
420
function sync_unbound_service() {
421
	global $config, $g;
422

    
423
	create_unbound_chroot_path();
424

    
425
	// Configure our Unbound service
426
	do_as_unbound_user("unbound-anchor");
427
	unbound_remote_control_setup();
428
	unbound_generate_config();
429
	do_as_unbound_user("start");
430
	require_once("service-utils.inc");
431
	if (is_service_running("unbound")) {
432
		do_as_unbound_user("restore_cache");
433
	}
434

    
435
}
436

    
437
function unbound_acl_id_used($id) {
438
	global $config;
439

    
440
	if (is_array($config['unbound']['acls'])) {
441
		foreach ($config['unbound']['acls'] as & $acls) {
442
			if ($id == $acls['aclid']) {
443
				return true;
444
			}
445
		}
446
	}
447

    
448
	return false;
449
}
450

    
451
function unbound_get_next_id() {
452
	$aclid = 0;
453
	while (unbound_acl_id_used($aclid)) {
454
		$aclid++;
455
	}
456
	return $aclid;
457
}
458

    
459
// Execute commands as the user unbound
460
function do_as_unbound_user($cmd, $param1 = "") {
461
	global $g;
462

    
463
	switch ($cmd) {
464
		case "start":
465
			mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
466
			break;
467
		case "stop":
468
			mwexec("echo '/usr/local/sbin/unbound-control stop' | /usr/bin/su -m unbound", true);
469
			break;
470
		case "reload":
471
			mwexec("echo '/usr/local/sbin/unbound-control reload' | /usr/bin/su -m unbound", true);
472
			break;
473
		case "unbound-anchor":
474
			$root_key_file = "{$g['unbound_chroot_path']}{$param1}/root.key";
475
			// sanity check root.key because unbound-anchor will fail without manual removal otherwise. redmine #5334
476
			if (file_exists($root_key_file)) {
477
				$rootkeycheck = mwexec("/usr/bin/grep 'autotrust trust anchor file' {$root_key_file}", true);
478
				if ($rootkeycheck != "0") {
479
					log_error("Unbound {$root_key_file} file is corrupt, removing and recreating.");
480
					unlink_if_exists($root_key_file);
481
				}
482
			}
483
			mwexec("echo '/usr/local/sbin/unbound-anchor -a {$root_key_file}' | /usr/bin/su -m unbound", true);
484
			// Only sync the file if this is the real (default) one, not a test one.
485
			if ($param1 == "") {
486
				pfSense_fsync($root_key_file);
487
			}
488
			break;
489
		case "unbound-control-setup":
490
			mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}{$param1}' | /usr/bin/su -m unbound", true);
491
			break;
492
		default:
493
			break;
494
	}
495
}
496

    
497
function unbound_add_domain_overrides($pvt_rev="", $cfgsubdir = "") {
498
	global $config, $g;
499

    
500
	$domains = $config['unbound']['domainoverrides'];
501

    
502
	$sorted_domains = msort($domains, "domain");
503
	$result = array();
504
	foreach ($sorted_domains as $domain) {
505
		$domain_key = current($domain);
506
		if (!isset($result[$domain_key])) {
507
			$result[$domain_key] = array();
508
		}
509
		$result[$domain_key][] = $domain['ip'];
510
	}
511

    
512
	// Domain overrides that have multiple entries need multiple stub-addr: added
513
	$domain_entries = "";
514
	foreach ($result as $domain=>$ips) {
515
		if ($pvt_rev == "private") {
516
			$domain_entries .= "private-domain: \"$domain\"\n";
517
			$domain_entries .= "domain-insecure: \"$domain\"\n";
518
		} else if ($pvt_rev == "reverse") {
519
			if ((substr($domain, -14) == ".in-addr.arpa.") || (substr($domain, -13) == ".in-addr.arpa")) {
520
				$domain_entries .= "local-zone: \"$domain\" typetransparent\n";
521
			}
522
		} else {
523
			$domain_entries .= "forward-zone:\n";
524
			$domain_entries .= "\tname: \"$domain\"\n";
525
			foreach ($ips as $ip) {
526
				$domain_entries .= "\tforward-addr: $ip\n";
527
			}
528
		}
529
	}
530

    
531
	if ($pvt_rev != "") {
532
		return $domain_entries;
533
	} else {
534
		create_unbound_chroot_path($cfgsubdir);
535
		file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/domainoverrides.conf", $domain_entries);
536
	}
537
}
538

    
539
function unbound_add_host_entries($cfgsubdir = "") {
540
	global $config, $g;
541

    
542
	// Make sure the config setting is a valid unbound local zone type.  If not use "transparent".
543
	if (array_key_exists($config['unbound']['system_domain_local_zone_type'], unbound_local_zone_types())) {
544
		$system_domain_local_zone_type = $config['unbound']['system_domain_local_zone_type'];
545
	} else {
546
		$system_domain_local_zone_type = "transparent";
547
	}
548

    
549
	$unbound_entries = "local-zone: \"{$config['system']['domain']}\" {$system_domain_local_zone_type}\n";
550

    
551
	$hosts = system_hosts_entries($config['unbound']);
552
	$added_ptr = array();
553
	foreach ($hosts as $host) {
554
		if (is_ipaddrv4($host['ipaddr'])) {
555
			$type = 'A';
556
		} else if (is_ipaddrv6($host['ipaddr'])) {
557
			$type = 'AAAA';
558
		} else {
559
			continue;
560
		}
561

    
562
		if (!$added_ptr[$host['ipaddr']]) {
563
			$unbound_entries .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
564
			$added_ptr[$host['ipaddr']] = true;
565
		}
566
		$unbound_entries .= "local-data: \"{$host['fqdn']} {$type} {$host['ipaddr']}\"\n";
567
	}
568

    
569
	// Write out entries
570
	create_unbound_chroot_path($cfgsubdir);
571
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/host_entries.conf", $unbound_entries);
572

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

    
577
function unbound_control($action) {
578
	global $config, $g;
579

    
580
	$cache_dumpfile = "/var/tmp/unbound_cache";
581

    
582
	switch ($action) {
583
	case "start":
584
		// Start Unbound
585
		if ($config['unbound']['enable'] == "on") {
586
			if (!is_service_running("unbound")) {
587
				do_as_unbound_user("start");
588
			}
589
		}
590
		break;
591
	case "stop":
592
		if ($config['unbound']['enable'] == "on") {
593
			do_as_unbound_user("stop");
594
		}
595
		break;
596
	case "reload":
597
		if ($config['unbound']['enable'] == "on") {
598
			do_as_unbound_user("reload");
599
		}
600
		break;
601
	case "dump_cache":
602
		// Dump Unbound's Cache
603
		if ($config['unbound']['dumpcache'] == "on") {
604
			do_as_unbound_user("dump_cache");
605
		}
606
		break;
607
	case "restore_cache":
608
		// Restore Unbound's Cache
609
		if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
610
			if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
611
				do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
612
			}
613
		}
614
		break;
615
	default:
616
		break;
617

    
618
	}
619
}
620

    
621
// Generation of Unbound statistics
622
function unbound_statistics() {
623
	global $config;
624

    
625
	if ($config['stats'] == "on") {
626
		$stats_interval = $config['unbound']['stats_interval'];
627
		$cumulative_stats = $config['cumulative_stats'];
628
		if ($config['extended_stats'] == "on") {
629
			$extended_stats = "yes";
630
		} else {
631
			$extended_stats = "no";
632
		}
633
	} else {
634
		$stats_interval = "0";
635
		$cumulative_stats = "no";
636
		$extended_stats = "no";
637
	}
638
	/* XXX To do - add RRD graphs */
639
	$stats = <<<EOF
640
# Unbound Statistics
641
statistics-interval: {$stats_interval}
642
extended-statistics: yes
643
statistics-cumulative: yes
644

    
645
EOF;
646

    
647
	return $stats;
648
}
649

    
650
// Unbound Access lists
651
function unbound_acls_config($cfgsubdir = "") {
652
	global $g, $config;
653

    
654
	if (!isset($config['unbound']['disable_auto_added_access_control'])) {
655
		$aclcfg = "access-control: 127.0.0.1/32 allow\n";
656
		$aclcfg .= "access-control: ::1 allow\n";
657
		// Add our networks for active interfaces including localhost
658
		if (!empty($config['unbound']['active_interface'])) {
659
			$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
660
			if (in_array("all", $active_interfaces)) {
661
				$active_interfaces = get_configured_interface_with_descr();
662
			}
663
		} else {
664
			$active_interfaces = get_configured_interface_with_descr();
665
		}
666

    
667
		$bindints = "";
668
		foreach ($active_interfaces as $ubif => $ifdesc) {
669
			$ifip = get_interface_ip($ubif);
670
			if (is_ipaddrv4($ifip)) {
671
				// IPv4 is handled via NAT networks below
672
			}
673
			$ifip = get_interface_ipv6($ubif);
674
			if (is_ipaddrv6($ifip)) {
675
				if (!is_linklocal($ifip)) {
676
					$subnet_bits = get_interface_subnetv6($ubif);
677
					$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
678
					// only add LAN-type interfaces
679
					if (!interface_has_gateway($ubif)) {
680
						$aclcfg .= "access-control: {$subnet_ip}/{$subnet_bits} allow\n";
681
					}
682
				}
683
				// add for IPv6 static routes to local networks
684
				// for safety, we include only routes reachable on an interface with no
685
				// gateway specified - read: not an Internet connection.
686
				$static_routes = get_staticroutes(false, false, true); // Parameter 3 returnenabledroutesonly
687
				foreach ($static_routes as $route) {
688
					if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
689
						// route is on this interface, interface doesn't have gateway, add it
690
						$aclcfg .= "access-control: {$route['network']} allow\n";
691
					}
692
				}
693
			}
694
		}
695

    
696
		// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
697
		if (empty($FilterIflist)) {
698
			filter_generate_optcfg_array();
699
		}
700
		$natnetworks_array = array();
701
		$natnetworks_array = filter_nat_rules_automatic_tonathosts();
702
		foreach ($natnetworks_array as $allowednet) {
703
			$aclcfg .= "access-control: $allowednet allow \n";
704
		}
705
	}
706

    
707
	// Configure the custom ACLs
708
	if (is_array($config['unbound']['acls'])) {
709
		foreach ($config['unbound']['acls'] as $unbound_acl) {
710
			$aclcfg .= "#{$unbound_acl['aclname']}\n";
711
			foreach ($unbound_acl['row'] as $network) {
712
				if ($unbound_acl['aclaction'] == "allow snoop") {
713
					$unbound_acl['aclaction'] = "allow_snoop";
714
				} elseif ($unbound_acl['aclaction'] == "deny nonlocal") {
715
					$unbound_acl['aclaction'] = "deny_non_local";
716
				} elseif ($unbound_acl['aclaction'] == "refuse nonlocal") {
717
					$unbound_acl['aclaction'] = "refuse_non_local";
718
				}
719
				$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
720
			}
721
		}
722
	}
723
	// Write out Access list
724
	create_unbound_chroot_path($cfgsubdir);
725
	file_put_contents("{$g['unbound_chroot_path']}{$cfgsubdir}/access_lists.conf", $aclcfg);
726

    
727
}
728

    
729
// Generate hosts and reload services
730
function unbound_hosts_generate() {
731
	// Generate our hosts file
732
	unbound_add_host_entries();
733

    
734
	// Reload our service to read the updates
735
	unbound_control("reload");
736
}
737

    
738
// Array of valid unbound local zone types
739
function unbound_local_zone_types() {
740
	return array(
741
		"deny" => gettext("Deny"),
742
		"refuse" => gettext("Refuse"),
743
		"static" => gettext("Static"),
744
		"transparent" => gettext("Transparent"),
745
		"typetransparent" => gettext("Type Transparent"),
746
		"redirect" => gettext("Redirect"),
747
		"inform" => gettext("Inform"),
748
		"inform_deny" => gettext("Inform Deny"),
749
		"nodefault" => gettext("No Default")
750
	);
751
}
752

    
753
?>
(41-41/51)