]> git.ipfire.org Git - ipfire-2.x.git/blob - src/initscripts/system/unbound
unbound: Allow forwarding to multiple servers at the same time
[ipfire-2.x.git] / src / initscripts / system / unbound
1 #!/bin/sh
2 # Begin $rc_base/init.d/unbound
3
4 # Description : Unbound DNS resolver boot script for IPfire
5 # Author : Marcel Lorenz <marcel.lorenz@ipfire.org>
6
7 . /etc/sysconfig/rc
8 . ${rc_functions}
9
10 TEST_DOMAIN="ipfire.org"
11
12 # This domain will never validate
13 TEST_DOMAIN_FAIL="dnssec-failed.org"
14
15 INSECURE_ZONES=
16 USE_FORWARDERS=1
17
18 # Cache any local zones for 60 seconds
19 LOCAL_TTL=60
20
21 # EDNS buffer size
22 EDNS_DEFAULT_BUFFER_SIZE=4096
23
24 # Load optional configuration
25 [ -e "/etc/sysconfig/unbound" ] && . /etc/sysconfig/unbound
26
27 function cidr() {
28 local cidr nbits IFS;
29 IFS=. read -r i1 i2 i3 i4 <<< ${1}
30 IFS=. read -r m1 m2 m3 m4 <<< ${2}
31 cidr=$(printf "%d.%d.%d.%d\n" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))")
32 nbits=0
33 IFS=.
34 for dec in $2 ; do
35 case $dec in
36 255) let nbits+=8;;
37 254) let nbits+=7;;
38 252) let nbits+=6;;
39 248) let nbits+=5;;
40 240) let nbits+=4;;
41 224) let nbits+=3;;
42 192) let nbits+=2;;
43 128) let nbits+=1;;
44 0);;
45 *) echo "Error: $dec is not recognised"; exit 1
46 esac
47 done
48 echo "${cidr}/${nbits}"
49 }
50
51 ip_address_revptr() {
52 local addr=${1}
53
54 local a1 a2 a3 a4
55 IFS=. read -r a1 a2 a3 a4 <<< ${addr}
56
57 echo "${a4}.${a3}.${a2}.${a1}.in-addr.arpa"
58 }
59
60 read_name_servers() {
61 local i
62 for i in 1 2; do
63 echo "$(</var/ipfire/red/dns${i})"
64 done 2>/dev/null | xargs echo
65 }
66
67 config_header() {
68 echo "# This file is automatically generated and any changes"
69 echo "# will be overwritten. DO NOT EDIT!"
70 echo
71 }
72
73 update_forwarders() {
74 if [ "${USE_FORWARDERS}" = "1" -a -e "/var/ipfire/red/active" ]; then
75 local forwarders
76 local broken_forwarders
77
78 local ns
79 for ns in $(read_name_servers); do
80 test_name_server ${ns} &>/dev/null
81 case "$?" in
82 # Only use DNSSEC-validating or DNSSEC-aware name servers
83 0|2)
84 forwarders="${forwarders} ${ns}"
85 ;;
86 *)
87 broken_forwarders="${broken_forwarders} ${ns}"
88 ;;
89 esac
90 done
91
92 # Determine EDNS buffer size
93 local new_edns_buffer_size=${EDNS_DEFAULT_BUFFER_SIZE}
94
95 for ns in ${forwarders}; do
96 local edns_buffer_size=$(ns_determine_edns_buffer_size ${ns})
97 if [ -n "${edns_buffer_size}" ]; then
98 if [ ${edns_buffer_size} -lt ${new_edns_buffer_size} ]; then
99 new_edns_buffer_size=${edns_buffer_size}
100 fi
101 fi
102 done
103
104 if [ ${new_edns_buffer_size} -lt ${EDNS_DEFAULT_BUFFER_SIZE} ]; then
105 boot_mesg "EDNS buffer size reduced to ${new_edns_buffer_size}" ${WARNING}
106 echo_warning
107
108 unbound-control -q set_option edns-buffer-size: ${new_edns_buffer_size}
109 fi
110
111 # Show warning for any broken upstream name servers
112 if [ -n "${broken_forwarders}" ]; then
113 boot_mesg "Ignoring broken upstream name server(s): ${broken_forwarders:1}" ${WARNING}
114 echo_warning
115 fi
116
117 if [ -n "${forwarders}" ]; then
118 boot_mesg "Configuring upstream name server(s): ${forwarders:1}" ${INFO}
119 echo_ok
120
121 # Make sure DNSSEC is activated
122 enable_dnssec
123
124 echo "${forwarders}" > /var/ipfire/red/dns
125 unbound-control -q forward ${forwarders}
126 return 0
127
128 # In case we have found no working forwarders
129 else
130 # Test if the recursor mode is available
131 if can_resolve_root +bufsize=${new_edns_buffer_size}; then
132 # Make sure DNSSEC is activated
133 enable_dnssec
134
135 boot_mesg "Falling back to recursor mode" ${WARNING}
136 echo_warning
137
138 # If not, we set DNSSEC in permissive mode and allow using all recursors
139 elif [ -n "${broken_forwarders}" ]; then
140 disable_dnssec
141
142 boot_mesg "DNSSEC has been set to permissive mode" ${FAILURE}
143 echo_failure
144
145 echo "${broken_forwarders}" > /var/ipfire/red/dns
146 unbound-control -q forward ${broken_forwarders}
147 return 0
148 fi
149 fi
150 fi
151
152 # If forwarders cannot be used we run in recursor mode
153 echo "local recursor" > /var/ipfire/red/dns
154 unbound-control -q forward off
155 }
156
157 own_hostname() {
158 local hostname=$(hostname -f)
159 # 1.1.1.1 is reserved for unused green, skip this
160 if [ -n "${GREEN_ADDRESS}" -a "${GREEN_ADDRESS}" != "1.1.1.1" ]; then
161 unbound-control -q local_data "${hostname} ${LOCAL_TTL} IN A ${GREEN_ADDRESS}"
162 fi
163
164 local address
165 for address in ${GREEN_ADDRESS} ${BLUE_ADDRESS} ${ORANGE_ADDRESS}; do
166 [ -n "${address}" ] || continue
167 [ "${address}" = "1.1.1.1" ] && continue
168
169 address=$(ip_address_revptr ${address})
170 unbound-control -q local_data "${address} ${LOCAL_TTL} IN PTR ${hostname}"
171 done
172 }
173
174 update_hosts() {
175 local enabled address hostname domainname
176
177 while IFS="," read -r enabled address hostname domainname; do
178 [ "${enabled}" = "on" ] || continue
179
180 # Build FQDN
181 local fqdn="${hostname}.${domainname}"
182
183 unbound-control -q local_data "${fqdn} ${LOCAL_TTL} IN A ${address}"
184
185 # Skip reverse resolution if the address equals the GREEN address
186 [ "${address}" = "${GREEN_ADDRESS}" ] && continue
187
188 # Add RDNS
189 address=$(ip_address_revptr ${address})
190 unbound-control -q local_data "${address} ${LOCAL_TTL} IN PTR ${fqdn}"
191 done < /var/ipfire/main/hosts
192 }
193
194 write_forward_conf() {
195 (
196 config_header
197
198 local insecure_zones="${INSECURE_ZONES}"
199
200 local enabled zone server servers remark
201 while IFS="," read -r enabled zone servers remark; do
202 # Line must be enabled.
203 [ "${enabled}" = "on" ] || continue
204
205 # Zones that end with .local are commonly used for internal
206 # zones and therefore not signed
207 case "${zone}" in
208 *.local)
209 insecure_zones="${insecure_zones} ${zone}"
210 ;;
211 esac
212
213 # Reverse-lookup zones must be stubs
214 case "${zone}" in
215 *.in-addr.arpa)
216 echo "stub-zone:"
217 echo " name: ${zone}"
218 for server in ${servers//|/ }; do
219 echo " stub-addr: ${server}"
220 done
221 echo
222 echo "server:"
223 echo " local-zone: \"${zone}\" transparent"
224 echo
225 ;;
226 *)
227 echo "forward-zone:"
228 echo " name: ${zone}"
229 for server in ${servers//|/ }; do
230 echo " forward-addr: ${server}"
231 done
232 echo
233 ;;
234 esac
235 done < /var/ipfire/dnsforward/config
236
237 if [ -n "${insecure_zones}" ]; then
238 echo "server:"
239
240 for zone in ${insecure_zones}; do
241 echo " domain-insecure: ${zone}"
242 done
243 fi
244 ) > /etc/unbound/forward.conf
245 }
246
247 write_tuning_conf() {
248 # https://www.unbound.net/documentation/howto_optimise.html
249
250 # Determine number of online processors
251 local processors=$(getconf _NPROCESSORS_ONLN)
252
253 # Determine number of slabs
254 local slabs=1
255 while [ ${slabs} -lt ${processors} ]; do
256 slabs=$(( ${slabs} * 2 ))
257 done
258
259 # Determine amount of system memory
260 local mem=$(get_memory_amount)
261
262 # In the worst case scenario, unbound can use double the
263 # amount of memory allocated to a cache due to malloc overhead
264
265 # Even larger systems with more than 8GB of RAM
266 if [ ${mem} -ge 8192 ]; then
267 mem=1024
268
269 # Extra large systems with more than 4GB of RAM
270 elif [ ${mem} -ge 4096 ]; then
271 mem=512
272
273 # Large systems with more than 2GB of RAM
274 elif [ ${mem} -ge 2048 ]; then
275 mem=256
276
277 # Medium systems with more than 1GB of RAM
278 elif [ ${mem} -ge 1024 ]; then
279 mem=128
280
281 # Small systems with less than 256MB of RAM
282 elif [ ${mem} -le 256 ]; then
283 mem=16
284
285 # Everything else
286 else
287 mem=64
288 fi
289
290 (
291 config_header
292
293 # We run one thread per processor
294 echo "num-threads: ${processors}"
295 echo "so-reuseport: yes"
296
297 # Adjust number of slabs
298 echo "infra-cache-slabs: ${slabs}"
299 echo "key-cache-slabs: ${slabs}"
300 echo "msg-cache-slabs: ${slabs}"
301 echo "rrset-cache-slabs: ${slabs}"
302
303 # Slice up the cache
304 echo "rrset-cache-size: $(( ${mem} / 2 ))m"
305 echo "msg-cache-size: $(( ${mem} / 4 ))m"
306 echo "key-cache-size: $(( ${mem} / 4 ))m"
307
308 # Increase parallel queries
309 echo "outgoing-range: 8192"
310 echo "num-queries-per-thread: 4096"
311
312 # Use larger send/receive buffers
313 echo "so-sndbuf: 4m"
314 echo "so-rcvbuf: 4m"
315 ) > /etc/unbound/tuning.conf
316 }
317
318 get_memory_amount() {
319 local key val unit
320
321 while read -r key val unit; do
322 case "${key}" in
323 MemTotal:*)
324 # Convert to MB
325 echo "$(( ${val} / 1024 ))"
326 break
327 ;;
328 esac
329 done < /proc/meminfo
330 }
331
332 test_name_server() {
333 local ns=${1}
334 local args
335
336 # Return codes:
337 # 0 DNSSEC validating
338 # 1 Error: unreachable, etc.
339 # 2 DNSSEC aware
340 # 3 NOT DNSSEC-aware
341
342 # Exit when the server is not reachable
343 ns_is_online ${ns} || return 1
344
345 # Determine the maximum edns buffer size that works
346 local edns_buffer_size=$(ns_determine_edns_buffer_size ${ns})
347 if [ -n "${edns_buffer_size}" ]; then
348 args="${args} +bufsize=${edns_buffer_size}"
349 fi
350
351 local errors
352 for rr in DNSKEY DS RRSIG; do
353 if ! ns_forwards_${rr} ${ns} ${args}; then
354 errors="${errors} ${rr}"
355 fi
356 done
357
358 if [ -n "${errors}" ]; then
359 echo >&2 "Unable to retrieve the following resource records from ${ns}: ${errors:1}"
360 return 3
361 fi
362
363 if ns_is_validating ${ns} ${args}; then
364 # Return 0 if validating
365 return 0
366 else
367 # Is DNSSEC-aware
368 return 2
369 fi
370 }
371
372 # Sends an A query to the nameserver w/o DNSSEC
373 ns_is_online() {
374 local ns=${1}
375 shift
376
377 dig @${ns} +nodnssec A ${TEST_DOMAIN} $@ >/dev/null
378 }
379
380 # Resolving ${TEST_DOMAIN_FAIL} will fail if the nameserver is validating
381 ns_is_validating() {
382 local ns=${1}
383 shift
384
385 if ! dig @${ns} A ${TEST_DOMAIN_FAIL} $@ | grep -q SERVFAIL; then
386 return 1
387 else
388 # Determine if NS replies with "ad" data flag if DNSSEC enabled
389 dig @${ns} +dnssec SOA ${TEST_DOMAIN} $@ | awk -F: '/\;\;\ flags\:/ { s=1; if (/\ ad/) s=0; exit s }'
390 fi
391 }
392
393 # Checks if we can retrieve the DNSKEY for this domain.
394 # dig will print the SOA if nothing was found
395 ns_forwards_DNSKEY() {
396 local ns=${1}
397 shift
398
399 dig @${ns} DNSKEY ${TEST_DOMAIN} $@ | grep -qv SOA
400 }
401
402 ns_forwards_DS() {
403 local ns=${1}
404 shift
405
406 dig @${ns} DS ${TEST_DOMAIN} $@ | grep -qv SOA
407 }
408
409 ns_forwards_RRSIG() {
410 local ns=${1}
411 shift
412
413 dig @${ns} +dnssec A ${TEST_DOMAIN} $@ | grep -q RRSIG
414 }
415
416 ns_supports_tcp() {
417 local ns=${1}
418 shift
419
420 dig @${ns} +tcp A ${TEST_DOMAIN} $@ >/dev/null || return 1
421 }
422
423 ns_determine_edns_buffer_size() {
424 local ns=${1}
425 shift
426
427 local b
428 for b in 4096 2048 1500 1480 1464 1400 1280 512; do
429 if dig @${ns} +dnssec +bufsize=${b} A ${TEST_DOMAIN} $@ >/dev/null; then
430 echo "${b}"
431 return 0
432 fi
433 done
434
435 return 1
436 }
437
438 get_root_nameservers() {
439 while read -r hostname ttl record address; do
440 # Searching for A records
441 [ "${record}" = "A" ] || continue
442
443 echo "${address}"
444 done < /etc/unbound/root.hints
445 }
446
447 can_resolve_root() {
448 local ns
449 for ns in $(get_root_nameservers); do
450 if dig @${ns} +dnssec SOA . $@ >/dev/null; then
451 return 0
452 fi
453 done
454
455 # none of the servers was reachable
456 return 1
457 }
458
459 enable_dnssec() {
460 local status=$(unbound-control get_option val-permissive-mode)
461
462 # Log DNSSEC status
463 echo "on" > /var/ipfire/red/dnssec-status
464
465 # Don't do anything if DNSSEC is already activated
466 [ "${status}" = "no" ] && return 0
467
468 # Activate DNSSEC and flush cache with any stale and unvalidated data
469 unbound-control -q set_option val-permissive-mode: no
470 unbound-control -q flush_zone .
471 }
472
473 disable_dnssec() {
474 # Log DNSSEC status
475 echo "off" > /var/ipfire/red/dnssec-status
476
477 unbound-control -q set_option val-permissive-mode: yes
478 }
479
480 fix_time_if_dns_fail() {
481 # If DNS still not work try to init ntp with
482 # hardcoded ntp.ipfire.org (81.3.27.46)
483 if [ -e /var/ipfire/red/active ]; then
484 host 0.ipfire.pool.ntp.org > /dev/null 2>&1
485 if [ "${?}" != "0" ]; then
486 boot_mesg "DNS still not functioning... Trying to sync time with ntp.ipfire.org (81.3.27.46)..."
487 loadproc /usr/local/bin/settime 81.3.27.46
488 fi
489 fi
490 }
491
492 case "$1" in
493 start)
494 # Print a nicer messagen when unbound is already running
495 if pidofproc -s unbound; then
496 statusproc /usr/sbin/unbound
497 exit 0
498 fi
499
500 eval $(/usr/local/bin/readhash /var/ipfire/ethernet/settings)
501
502 # Create control keys at first run
503 if [ ! -r "/etc/unbound/unbound_control.key" ]; then
504 unbound-control-setup -d /etc/unbound &>/dev/null
505 fi
506
507 # Update configuration files
508 write_tuning_conf
509 write_forward_conf
510
511 boot_mesg "Starting Unbound DNS Proxy..."
512 loadproc /usr/sbin/unbound || exit $?
513
514 # Make own hostname resolveable
515 own_hostname
516
517 # Update any known forwarding name servers
518 update_forwarders
519
520 # Update hosts
521 update_hosts
522
523 fix_time_if_dns_fail
524 ;;
525
526 stop)
527 boot_mesg "Stopping Unbound DNS Proxy..."
528 killproc /usr/sbin/unbound
529 ;;
530
531 restart)
532 $0 stop
533 sleep 1
534 $0 start
535 ;;
536
537 status)
538 statusproc /usr/sbin/unbound
539 ;;
540
541 update-forwarders)
542 # Do not try updating forwarders when unbound is not running
543 if ! pgrep unbound &>/dev/null; then
544 exit 0
545 fi
546
547 update_forwarders
548
549 unbound-control flush_negative > /dev/null
550 unbound-control flush_bogus > /dev/null
551
552 fix_time_if_dns_fail
553 ;;
554
555 test-name-server)
556 ns=${2}
557
558 test_name_server ${ns}
559 ret=${?}
560
561 case "${ret}" in
562 0)
563 echo "${ns} is validating"
564 ;;
565 2)
566 echo "${ns} is DNSSEC-aware"
567 ;;
568 3)
569 echo "${ns} is NOT DNSSEC-aware"
570 ;;
571 *)
572 echo "Test failed for an unknown reason"
573 exit ${ret}
574 ;;
575 esac
576
577 if ns_supports_tcp ${ns}; then
578 echo "${ns} supports TCP fallback"
579 else
580 echo "${ns} does not support TCP fallback"
581 fi
582
583 edns_buffer_size=$(ns_determine_edns_buffer_size ${ns})
584 if [ -n "${edns_buffer_size}" ]; then
585 echo "EDNS buffer size for ${ns}: ${edns_buffer_size}"
586 fi
587
588 exit ${ret}
589 ;;
590
591 *)
592 echo "Usage: $0 {start|stop|restart|status|update-forwarders|test-name-server}"
593 exit 1
594 ;;
595 esac
596
597 # End $rc_base/init.d/unbound