Debian Codegraph @

update-systemd-resolved

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env bash
2 #
3 # OpenVPN helper to add DHCP information into systemd-resolved via DBus.
4 # Copyright (C) 2016, Jonathan Wright <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 # This script will parse DHCP options set via OpenVPN (dhcp-option) to update
20 # systemd-resolved directly via DBus, instead of updating /etc/resolv.conf. To
21 # install, set as the 'up' and 'down' script in your OpenVPN configuration file
22 # or via the command-line arguments, alongside setting the 'down-pre' option to
23 # run the 'down' script before the device is closed. For example:
24 # up /etc/openvpn/scripts/update-systemd-resolved
25 # down /etc/openvpn/scripts/update-systemd-resolved
26 # down-pre
27
28 # Define what needs to be called via DBus
29 DBUS_DEST="org.freedesktop.resolve1"
30 DBUS_NODE="/org/freedesktop/resolve1"
31
32 SCRIPT_NAME="${BASH_SOURCE[0]##*/}"
33
34 log() {
35 logger -s -t "$SCRIPT_NAME" "$@"
36 }
37
38 for level in emerg err warning info debug; do
39 printf -v functext -- '%s() { log -p user.%s -- "$@" ; }' "$level" "$level"
40 eval "$functext"
41 done
42
43 usage() {
44 err "${1:?${1}. }. Usage: ${SCRIPT_NAME} up|down device_name."
45 }
46
47 busctl_call() {
48 # Preserve busctl's exit status
49 busctl call "$DBUS_DEST" "$DBUS_NODE" "${DBUS_DEST}.Manager" "$@" || {
50 local -i status=$?
51 emerg "'busctl' exited with status $status"
52 return $status
53 }
54 }
55
56 get_link_info() {
57 dev="$1"
58 shift
59
60 link=''
61 link="$(ip link show dev "$dev")" || return $?
62
63 echo "$dev" "${link%%:*}"
64 }
65
66 dhcp_settings() {
67 for foreign_option in "${!foreign_option_@}"; do
68 foreign_option_value="${!foreign_option}"
69
70 [[ "$foreign_option_value" == *dhcp-option* ]] \
71 && echo "${foreign_option_value#dhcp-option }"
72 done
73 }
74
75 up() {
76 local link="$1"
77 shift
78 local if_index="$1"
79 shift
80
81 info "Link '$link' coming up"
82
83 # Preset values for processing -- will be altered in the various process_*
84 # functions.
85 local -a dns_servers=() dns_domain=() dns_search=() dns_routed=()
86 local -i dns_server_count=0 dns_domain_count=0 dns_search_count=0 dns_routed_count=0
87 local dns_sec=""
88
89 while read -r setting; do
90 setting_type="${setting%% *}"
91 setting_value="${setting#* }"
92
93 process_setting_function="${setting_type,,}"
94 process_setting_function="process_${process_setting_function//-/_}"
95
96 if declare -f "$process_setting_function" &>/dev/null; then
97 "$process_setting_function" "$setting_value" || return $?
98 else
99 warning "Not a recognized DHCP setting: '${setting}'"
100 fi
101 done < <(dhcp_settings)
102
103 if [[ "${#dns_servers[*]}" -gt 0 ]]; then
104 busctl_params=("$if_index" "$dns_server_count" "${dns_servers[@]}")
105 info "SetLinkDNS(${busctl_params[*]})"
106 busctl_call SetLinkDNS 'ia(iay)' "${busctl_params[@]}" || return $?
107 fi
108
109 if [[ "${#dns_domain[*]}" -gt 0 \
110 || "${#dns_search[*]}" -gt 0 \
111 || "${#dns_routed[*]}" -gt 0 ]]; then
112 dns_count=$((dns_domain_count+dns_search_count+dns_routed_count))
113 busctl_params=("$if_index" "$dns_count")
114 if [[ "${#dns_domain[*]}" -gt 0 ]]; then
115 busctl_params+=("${dns_domain[@]}")
116 fi
117 if [[ "${#dns_search[*]}" -gt 0 ]]; then
118 busctl_params+=("${dns_search[@]}")
119 fi
120 if [[ "${#dns_routed[*]}" -gt 0 ]]; then
121 busctl_params+=("${dns_routed[@]}")
122 fi
123 info "SetLinkDomains(${busctl_params[*]})"
124 busctl_call SetLinkDomains 'ia(sb)' "${busctl_params[@]}" || return $?
125 fi
126
127 if [[ -n "${dns_sec}" ]]; then
128 if [[ "${dns_sec}" == "default" ]]; then
129 # We need to provide an empty string to use the default settings
130 info "SetLinkDNSSEC($if_index '')"
131 busctl_call SetLinkDNSSEC 'is' "$if_index" "" || return $?
132 else
133 info "SetLinkDNSSEC($if_index ${dns_sec})"
134 busctl_call SetLinkDNSSEC 'is' "$if_index" "${dns_sec}" || return $?
135 fi
136 fi
137 }
138
139 down() {
140 local link="$1"
141 shift
142 local if_index="$1"
143 shift
144
145 info "Link '$link' going down"
146 if [[ "$(whoami 2>/dev/null)" != "root" ]]; then
147 # Cleanly handle the privilege dropped case by not calling RevertLink
148 info "Privileges dropped in the client: Cannot call RevertLink."
149 else
150 busctl_call RevertLink i "$if_index"
151 fi
152 }
153
154 process_dns() {
155 address="$1"
156 shift
157
158 if looks_like_ipv6 "$address"; then
159 process_dns_ipv6 "$address" || return $?
160 elif looks_like_ipv4 "$address"; then
161 process_dns_ipv4 "$address" || return $?
162 else
163 err "Not a valid IPv6 or IPv4 address: '$address'"
164 return 1
165 fi
166 }
167
168 process_dns6() {
169 process_dns $1
170 }
171
172 looks_like_ipv4() {
173 [[ -n "$1" ]] && {
174 local dots="${1//[^.]}"
175 (( ${#dots} == 3 ))
176 }
177 }
178
179 looks_like_ipv6() {
180 [[ -n "$1" ]] && {
181 local colons="${1//[^:]}"
182 (( ${#colons} >= 2 ))
183 }
184 }
185
186 process_dns_ipv4() {
187 local address="$1"
188 shift
189
190 info "Adding IPv4 DNS Server ${address}"
191 (( dns_server_count += 1 ))
192 dns_servers+=(2 4 ${address//./ })
193 }
194
195 # Enforces RFC 5952:
196 # 1. Don't shorten a single 0 field to '::'
197 # 2. Only longest run of zeros should be compressed
198 # 3. If there are multiple longest runs, the leftmost should be compressed
199 # 4. Address must be maximally compressed, so no all-zero runs next to '::'
200 #
201 # ...
202 #
203 # Thank goodness we don't have to handle port numbers, though :)
204 parse_ipv6() {
205 local raw_address="$1"
206
207 log_invalid_ipv6() {
208 local message="'$raw_address' is not a valid IPv6 address"
209 emerg "${message}: $*"
210 }
211
212 trap -- 'unset -f log_invalid_ipv6' RETURN
213
214 if [[ "$raw_address" == *::*::* ]]; then
215 log_invalid_ipv6 "address cannot contain more than one '::'"
216 return 1
217 elif [[ "$raw_address" =~ :0+:: ]] || [[ "$raw_address" =~ ::0+: ]]; then
218 log_invalid_ipv6 "address contains a 0-group adjacent to '::' and is not maximally shortened"
219 return 1
220 fi
221
222 local -i length=8
223 local -a raw_segments=()
224
225 IFS=$':' read -r -a raw_segments <<<"$raw_address"
226
227 local -i raw_length="${#raw_segments[@]}"
228
229 if (( raw_length > length )); then
230 log_invalid_ipv6 "expected ${length} segments, got ${raw_length}"
231 return 1
232 fi
233
234 # Store zero-runs keyed to their sizes, storing all non-zero segments prefixed
235 # with a token marking them as such.
236 local nonzero_prefix=$'!'
237 local -i zero_run_i=0 compressed_i=0
238 local -a tokenized_segments=()
239 local decimal_segment='' next_decimal_segment=''
240
241 for (( i = 0 ; i < raw_length ; i++ )); do
242 raw_segment="${raw_segments[i]}"
243
244 printf -v decimal_segment -- '%d' "0x${raw_segment:-0}"
245
246 # We're in the compressed group. The length of this run should be
247 # enough to bring the total number of segments to 8.
248 if [[ -z "$raw_segment" ]]; then
249 (( compressed_i = zero_run_i ))
250
251 # `+ 1' because the length of the current segment is counted in
252 # `raw_length'.
253 (( tokenized_segments[zero_run_i] = ((length - raw_length) + 1) ))
254
255 # If we have an address like `::1', skip processing the next group to
256 # avoid double-counting the zero-run, and increment the number of
257 # 0-groups to add since the second empty group is counted in
258 # `raw_length'.
259 if [[ -z "${raw_segments[i + 1]}" ]]; then
260 (( i++ ))
261 (( tokenized_segments[zero_run_i]++ ))
262 fi
263
264 (( zero_run_i++ ))
265 elif (( decimal_segment == 0 )); then
266 (( tokenized_segments[zero_run_i]++ ))
267
268 # The run is over if the next segment is not 0, so increment the
269 # tracking index.
270 printf -v next_decimal_segment -- '%d' "0x${raw_segments[i + 1]}"
271
272 (( next_decimal_segment != 0 )) && (( zero_run_i++ ))
273 else
274 # Prefix the raw segment with `nonzero_prefix' to mark this as a
275 # non-zero field.
276 tokenized_segments[zero_run_i]="${nonzero_prefix}${decimal_segment}"
277 (( zero_run_i++ ))
278 fi
279 done
280
281 if [[ "$raw_address" == *::* ]]; then
282 if (( ${#tokenized_segments[*]} == length )); then
283 log_invalid_ipv6 "single '0' fields should not be compressed"
284 return 1
285 else
286 local -i largest_run_i=0 largest_run=0
287
288 for (( i = 0 ; i < ${#tokenized_segments[@]}; i ++ )); do
289 # Skip groups that aren't zero-runs
290 [[ "${tokenized_segments[i]:0:1}" == "$nonzero_prefix" ]] && continue
291
292 if (( tokenized_segments[i] > largest_run )); then
293 (( largest_run_i = i ))
294 largest_run="${tokenized_segments[i]}"
295 fi
296 done
297
298 local -i compressed_run="${tokenized_segments[compressed_i]}"
299
300 if (( largest_run > compressed_run )); then
301 log_invalid_ipv6 "the compressed run of all-zero fields is smaller than the largest such run"
302 return 1
303 elif (( largest_run == compressed_run )) && (( largest_run_i < compressed_i )); then
304 log_invalid_ipv6 "only the leftmost largest run of all-zero fields should be compressed"
305 return 1
306 fi
307 fi
308 fi
309
310 for segment in "${tokenized_segments[@]}"; do
311 if [[ "${segment:0:1}" == "$nonzero_prefix" ]]; then
312 printf -- '%04x\n' "${segment#${nonzero_prefix}}"
313 else
314 for (( n = 0 ; n < segment ; n++ )); do
315 echo 0000
316 done
317 fi
318 done
319 }
320
321 process_dns_ipv6() {
322 local address="$1"
323 shift
324
325 info "Adding IPv6 DNS Server ${address}"
326
327 local -a segments=()
328 segments=($(parse_ipv6 "$address")) || return $?
329
330 # Add AF_INET6 and byte count
331 dns_servers+=(10 16)
332 for segment in "${segments[@]}"; do
333 dns_servers+=("$((16#${segment:0:2}))" "$((16#${segment:2:2}))")
334 done
335
336 (( dns_server_count += 1 ))
337 }
338
339 process_domain() {
340 local domain="$1"
341 shift
342
343 info "Adding DNS Domain ${domain}"
344 if [[ $dns_domain_count -eq 1 ]]; then
345 (( dns_search_count += 1 ))
346 dns_search+=("${domain}" false)
347 else
348 (( dns_domain_count = 1 ))
349 dns_domain+=("${domain}" false)
350 fi
351 }
352
353 process_adapter_domain_suffix() {
354 # This enables support for ADAPTER_DOMAIN_SUFFIX which is a Microsoft standard
355 # which works in the same way as DOMAIN to set the primary search domain on
356 # this specific link.
357 process_domain "$@"
358 }
359
360 process_domain_search() {
361 local domain="$1"
362 shift
363
364 info "Adding DNS Search Domain ${domain}"
365 (( dns_search_count += 1 ))
366 dns_search+=("${domain}" false)
367 }
368
369 process_domain_route() {
370 local domain="$1"
371 shift
372
373 info "Adding DNS Routed Domain ${domain}"
374 (( dns_routed_count += 1 ))
375 dns_routed+=("${domain}" true)
376 }
377
378 process_dnssec() {
379 local option="$1" setting=""
380 shift
381
382 case "${option,,}" in
383 yes|true)
384 setting="yes" ;;
385 no|false)
386 setting="no" ;;
387 default)
388 setting="default" ;;
389 allow-downgrade)
390 setting="allow-downgrade" ;;
391 *)
392 local message="'$option' is not a valid DNSSEC option"
393 emerg "${message}"
394 return 1 ;;
395 esac
396
397 info "Setting DNSSEC to ${setting}"
398 dns_sec="${setting}"
399 }
400
401 main() {
402 local script_type="${1}"
403 shift
404 local dev="${1:-$dev}"
405 shift
406
407 if [[ -z "$script_type" ]]; then
408 usage 'No script type specified'
409 return 1
410 elif [[ -z "$dev" ]]; then
411 usage 'No device name specified'
412 return 1
413 elif ! declare -f "${script_type}" &>/dev/null; then
414 usage "Invalid script type: '${script_type}'"
415 return 1
416 else
417 if ! read -r link if_index _ < <(get_link_info "$dev"); then
418 usage "Invalid device name: '$dev'"
419 return 1
420 fi
421
422 "$script_type" "$link" "$if_index" "$@" || return 1
423 # Flush the DNS cache
424 systemd-resolve --flush-caches
425 fi
426 }
427
428 if [[ "${BASH_SOURCE[0]}" == "$0" ]] || [[ "$AUTOMATED_TESTING" == 1 ]]; then
429 set -o nounset
430
431 main "${script_type:-down}" "$@"
432 fi