summaryrefslogtreecommitdiff
path: root/src/services/vyos-domain-resolver
blob: 0a8596545177b6192383d1590c945ba9326c7c45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/env python3
#
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import json
import time
import logging
import os
from urllib.parse import urlsplit
from urllib.parse import urlunsplit

from vyos import ConfigError
from vyos.configdict import dict_merge
from vyos.configquery import ConfigTreeQuery
from vyos.defaults import directories
from vyos.firewall import fqdn_config_parse
from vyos.utils.network import fqdn_resolve
from vyos.ifconfig import WireGuardIf
from vyos.remote import download
from vyos.template import is_ip
from vyos.template import is_ipv6
from vyos.utils.commit import commit_in_progress
from vyos.utils.convert import human_to_seconds
from vyos.utils.dict import dict_search_args
from vyos.utils.kernel import WIREGUARD_REKEY_AFTER_TIME
from vyos.utils.file import makedir, chmod_775, write_file, read_file
from vyos.utils.network import is_ipv4_address_or_range
from vyos.utils.network import is_ipv6_address_or_range
from vyos.utils.file import read_json
from vyos.utils.file import write_json
from vyos.utils.process import cmdl
from vyos.utils.process import run
from vyos.utils.system import load_as_module
from vyos.xml_ref import get_defaults

base = ['firewall']
timeout = 300
cache = False
base_firewall = ['firewall']
base_nat = ['nat']
base_interfaces = ['interfaces']
base_syslog = ['system', 'syslog']

firewall_config_dir = "/config/firewall"

domain_state = {}
remote_group_last_update = {}

ipv4_tables = {
    'ip vyos_mangle',
    'ip vyos_filter',
    'ip vyos_nat',
    'ip vyos_wanloadbalance',
    'ip raw'
}

ipv6_tables = {
    'ip6 vyos_mangle',
    'ip6 vyos_filter',
    'ip6 raw'
}

logger = logging.getLogger(__name__)
logs_handler = logging.StreamHandler()
logger.addHandler(logs_handler)
logger.setLevel(logging.INFO)

def get_config(conf, node):
    node_config = conf.get_config_dict(node, key_mangling=('-', '_'), get_first_key=True,
                                    no_tag_node_value_mangle=True)

    default_values = get_defaults(node, get_first_key=True)

    node_config = dict_merge(default_values, node_config)

    if node == base_firewall and 'global_options' in node_config:
        global_config = node_config['global_options']
        global timeout, cache

        if 'resolver_interval' in global_config:
            timeout = int(global_config['resolver_interval'])

        if 'resolver_cache' in global_config:
            cache = True

    fqdn_config_parse(node_config, node[0])

    return node_config

def resolve(domains, ipv6=False):
    global domain_state

    ip_list = set()

    for domain in domains:
        resolved = fqdn_resolve(domain, ipv6=ipv6)

        cache_key = f'{domain}_ipv6' if ipv6 else domain

        if resolved and cache:
            domain_state[cache_key] = resolved
        elif not resolved:
            if cache_key not in domain_state:
                continue
            resolved = domain_state[cache_key]

        ip_list = ip_list | resolved
    return ip_list

def wait_commit():
    """Pause code execution while commit still in progress"""

    count = 1
    while commit_in_progress():
        if count % 60 == 0:
            logger.info(f'Commit still in progress after {count}s - waiting')
        count += 1
        time.sleep(1)

def nft_output(table, set_name, ip_list):
    output = [f'flush set {table} {set_name}']
    if ip_list:
        ip_str = ','.join(ip_list)
        output.append(f'add element {table} {set_name} {{ {ip_str} }}')
    return output

def nft_valid_sets():
    try:
        valid_sets = []
        sets_json = cmdl(['nft', '--json', 'list', 'sets'])
        sets_obj = json.loads(sets_json)

        for obj in sets_obj['nftables']:
            if 'set' in obj:
                family = obj['set']['family']
                table = obj['set']['table']
                name = obj['set']['name']
                valid_sets.append((f'{family} {table}', name))

        return valid_sets
    except:
        return []

def remote_group_interval(remote_config):
    # Per-group update interval, falling back to the global resolver interval
    if 'interval' in remote_config:
        return human_to_seconds(remote_config['interval'])
    return timeout

def update_remote_group(config):
    conf_lines = []
    count = 0
    now = time.time()
    valid_sets = nft_valid_sets()

    remote_groups = dict_search_args(config, 'group', 'remote_group')
    if remote_groups:
        # Create directory for list files if necessary
        if not os.path.isdir(firewall_config_dir):
            makedir(firewall_config_dir, group='vyattacfg')
            chmod_775(firewall_config_dir)

        for set_name, remote_config in remote_groups.items():
            if 'url' not in remote_config:
                continue
            interval = remote_group_interval(remote_config)
            last_update = remote_group_last_update.get(set_name, 0)
            if now - last_update < interval:
                continue
            nft_ip_set_name = f'R_{set_name}'
            nft_ip6_set_name = f'R6_{set_name}'

            # Create list file if necessary
            list_file = os.path.join(firewall_config_dir, f"{nft_ip_set_name}.txt")
            if not os.path.exists(list_file):
                write_file(list_file, '', user="root", group="vyattacfg", mode=0o644)

            # Attempt to download file, use cached version if download fails
            try:
                download(list_file, remote_config['url'], raise_error=True)
                remote_group_last_update[set_name] = now
            except Exception as err:
                # Retry failed downloads at the resolver cadence instead of
                # waiting the full group interval
                retry = min(interval, timeout)
                remote_group_last_update[set_name] = now - interval + retry
                url = urlsplit(remote_config['url'])
                _, _, netloc = url.netloc.rpartition('@')
                redacted_url = urlunsplit(url._replace(netloc=netloc, query='', fragment=''))
                err_msg = str(err).replace(remote_config['url'], redacted_url)
                logger.error(
                    'Failed to download list-file for %s remote group: %s: %s',
                    set_name,
                    err.__class__.__name__,
                    err_msg,
                )
                logger.debug('Download failure details for %s', set_name, exc_info=True)
                logger.info(f'Using cached list-file for {set_name} remote group')

            # Read list file
            ip_list = []
            ip6_list = []
            invalid_list = []
            for line in read_file(list_file).splitlines():
                line_first_word = line.strip().partition(' ')[0]

                if not line_first_word:
                    continue

                if is_ipv4_address_or_range(line_first_word):
                    ip_list.append(line_first_word)
                elif is_ipv6_address_or_range(line_first_word):
                    ip6_list.append(line_first_word)
                elif line_first_word[0].isalnum():
                    invalid_list.append(line_first_word)

            # Load ip tables
            for table in ipv4_tables:
                if (table, nft_ip_set_name) in valid_sets:
                    conf_lines += nft_output(table, nft_ip_set_name, ip_list)

            # Load ip6 tables
            for table in ipv6_tables:
                if (table, nft_ip6_set_name) in valid_sets:
                    conf_lines += nft_output(table, nft_ip6_set_name, ip6_list)

            invalid_str = ", ".join(invalid_list)
            if invalid_str:
                logger.info(f'Invalid address for set {set_name}: {invalid_str}')

            count += 1

    if count:
        nft_conf_str = "\n".join(conf_lines) + "\n"
        code = run(f'nft --file -', input=nft_conf_str)

        logger.info(f'Updated {count} remote-groups in firewall - result: {code}')


def update_fqdn(config, node):
    conf_lines = []
    count = 0
    valid_sets = nft_valid_sets()

    if node == 'firewall':
        domain_groups = dict_search_args(config, 'group', 'domain_group')
        if domain_groups:
            for set_name, domain_config in domain_groups.items():
                if 'address' not in domain_config:
                    continue
                nft_set_name = f'D_{set_name}'
                domains = domain_config['address']

                ip_list = resolve(domains, ipv6=False)
                for table in ipv4_tables:
                    if (table, nft_set_name) in valid_sets:
                        conf_lines += nft_output(table, nft_set_name, ip_list)
                ip6_list = resolve(domains, ipv6=True)
                for table in ipv6_tables:
                    if (table, nft_set_name) in valid_sets:
                        conf_lines += nft_output(table, nft_set_name, ip6_list)
                count += 1

        for set_name, domain in config['ip_fqdn'].items():
            table = 'ip vyos_filter'
            nft_set_name = f'FQDN_{set_name}'
            ip_list = resolve([domain], ipv6=False)
            if (table, nft_set_name) in valid_sets:
                conf_lines += nft_output(table, nft_set_name, ip_list)
            count += 1

        for set_name, domain in config['ip6_fqdn'].items():
            table = 'ip6 vyos_filter'
            nft_set_name = f'FQDN_{set_name}'
            ip_list = resolve([domain], ipv6=True)
            if (table, nft_set_name) in valid_sets:
                conf_lines += nft_output(table, nft_set_name, ip_list)
            count += 1

    else:
        # It's NAT
        for set_name, domain in config['ip_fqdn'].items():
            table = 'ip vyos_nat'
            nft_set_name = f'FQDN_nat_{set_name}'
            ip_list = resolve([domain], ipv6=False)
            if (table, nft_set_name) in valid_sets:
                conf_lines += nft_output(table, nft_set_name, ip_list)
            count += 1

    nft_conf_str = "\n".join(conf_lines) + "\n"
    code = run(f'nft --file -', input=nft_conf_str)

    logger.info(f'Updated {count} sets in {node} - result: {code}')

def update_interfaces(config, node):
    if node == 'interfaces':
        wg_interfaces = dict_search_args(config, 'wireguard')
        if wg_interfaces:

            peer_public_keys = {}
            # for each wireguard interfaces
            for interface, wireguard in wg_interfaces.items():
                peer_public_keys[interface] = []
                for peer, peer_config in wireguard['peer'].items():
                    # check peer if peer host-name or address is set
                    if 'host_name' in peer_config or 'address' in peer_config:
                        # check latest handshake
                        peer_public_keys[interface].append(
                            peer_config['public_key']
                        )

            now_time = time.time()
            for (interface, check_peer_public_keys) in peer_public_keys.items():
                if len(check_peer_public_keys) == 0:
                    continue

                intf = WireGuardIf(interface, create=False, debug=False)
                handshakes = intf.operational.get_latest_handshakes()

                # WireGuard performs a handshake every WIREGUARD_REKEY_AFTER_TIME
                # if data is being transmitted between the peers. If no data is
                # transmitted, the handshake will not be initiated unless new
                # data begins to flow. Each handshake generates a new session
                # key, and the key is rotated at least every 120 seconds or
                # upon data transmission after a prolonged silence.
                for public_key, handshake_time in handshakes.items():
                    if public_key in check_peer_public_keys and (
                        handshake_time == 0
                        or (now_time - handshake_time > 3*WIREGUARD_REKEY_AFTER_TIME)
                    ):
                        intf.operational.reset_peer(public_key=public_key)

def collect_syslog_targets(config):
    """Collect VRF-bound FQDN targets from 'system syslog remote <hostname>'"""

    targets = []
    for remote, remote_options in config.get('remote', {}).items():
        target = remote
        vrf = remote_options.get('vrf')

        if vrf and not is_ip(target):  # The remote uses VRF context and target address is FQDN
            targets.append((target, vrf, remote_options))

    return targets


def update_syslog(config: dict):
    """Handle a resolved-address change for a VRF-bound syslog remote"""

    targets = collect_syslog_targets(config)
    if not targets:
        return

    wait_commit()

    logger.info('Starting `update_syslog` with targets: %s', ['|'.join(t[:2]) for t in targets])

    # Shared state which keyed by "fqdn|vrf" for 'system_syslog.py'
    resolver_state_file = '/run/vyos-rsyslog-name-resolve.json'
    resolver_state = read_json(resolver_state_file, defaultonfailure={})
    prev_resolver_state = resolver_state.copy()

    changed = False

    for fqdn, vrf, remote_options in targets:
        logger.debug('Resolving FQDN %s for VRF %s', fqdn, vrf)

        # Resolve a remote syslog target inside a VRF, trying both families
        source_address = remote_options.get('source_address')
        if source_address:
            # Select record family matching the configured source address
            addrs = fqdn_resolve(fqdn, ipv6=is_ipv6(source_address), vrf=vrf)
        else:
            # Tries A and AAAA record, inside the given VRF's routing context
            addrs = fqdn_resolve(fqdn, ipv6=None, vrf=vrf)

        if not addrs:
            logger.warning(
                'No addresses resolved for %s in VRF %s. Keeping last-known-good.', fqdn, vrf
            )
            continue  # Keep last-known-good rather than clearing on a transient failure

        state_key = f'{fqdn}|{vrf}'
        resolved = sorted(addrs)[0]
        old_value = resolver_state.get(state_key)
        if old_value != resolved:
            logger.info('Address changed for %s: %s -> %s', state_key, old_value, resolved)
            resolver_state[state_key] = resolved
            changed = True

    failed = False

    if resolver_state and changed:
        write_json(resolver_state_file, resolver_state, atomic=True)

        mod_name = 'system_syslog'
        conf_mode = directories['conf_mode']
        mod_path = f'{conf_mode}/{mod_name}.py'

        logger.info('Executing module: %s', mod_path)
        mod = load_as_module(mod_name, mod_path)

        try:
            c = mod.get_config()
            mod.verify(c)
            mod.generate(c)
            # By default 'apply' triggers restart of the 'vyos-domain-resolver' service.
            # Necessary to disable it and run 'apply' without restart the service:
            mod.apply.ignore_domain_resolver = True
            mod.apply(c)
        except ConfigError as e:
            failed = True
            logger.error('Failed to execute `%s.py` module: %s', mod_name, e)
        except Exception:
            failed = True
            logger.exception('Unexpected failure in `%s.py` module', mod_name)
        else:
            logger.info('`update_syslog` successfully executed')
    else:
        logger.info('No changes detected in `update_syslog`')

    if failed:
        try:
            # Restore the prior state on failure
            write_json(resolver_state_file, prev_resolver_state, atomic=True)
        except Exception as e:
            logger.exception('Failed to restore prior resolver state')


if __name__ == '__main__':
    logger.info('VyOS domain resolver')

    wait_commit()

    conf = ConfigTreeQuery()
    firewall = get_config(conf, base_firewall)
    nat = get_config(conf, base_nat)
    interfaces = get_config(conf, base_interfaces)
    syslog = get_config(conf, base_syslog)

    logger.info(f'interval: {timeout}s - cache: {cache}')

    remote_groups = dict_search_args(firewall, 'group', 'remote_group') or {}

    last_fqdn_update = 0
    while True:
        now = time.time()

        if now - last_fqdn_update >= timeout:
            last_fqdn_update = now
            update_fqdn(firewall, 'firewall')
            update_fqdn(nat, 'nat')
            update_interfaces(interfaces, 'interfaces')
            update_syslog(syslog)

        update_remote_group(firewall)

        # Sleep until the next scheduled update
        next_due = [last_fqdn_update + timeout]
        for set_name, remote_config in remote_groups.items():
            if 'url' not in remote_config:
                continue
            next_due.append(remote_group_last_update.get(set_name, 0) +
                            remote_group_interval(remote_config))
        time.sleep(max(min(next_due) - time.time(), 1))