summaryrefslogtreecommitdiff
path: root/src/validators/bgp-rd-rt
blob: b2b69c9be0f6fa80a9779f323c32edf91a3509ba (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
#!/usr/bin/env python3
#
# Copyright (C) 2021 VyOS maintainers and contributors
#
# 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/>.

from argparse import ArgumentParser
from vyos.template import is_ipv4

parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--route-distinguisher', action='store', help='Validate BGP route distinguisher')
group.add_argument('--route-target', action='store', help='Validate one BGP route-target')
group.add_argument('--route-target-multi', action='store', help='Validate multiple, whitespace separated BGP route-targets')
args = parser.parse_args()

def is_valid(rt):
    """ Verify BGP RD/RT - both can be verified using the same logic """
    # every RD/RT (route distinguisher/route target) needs to have a colon and
    # must consists of two parts
    value = rt.split(':')
    if len(value) != 2:
        return False

    # An RD/RT must either be only numbers, or the first part must be an IPv4
    # address
    if (is_ipv4(value[0]) or value[0].isdigit()) and value[1].isdigit():
        return True
    return False

if __name__ == '__main__':
    if args.route_distinguisher:
        if not is_valid(args.route_distinguisher):
            exit(1)

    elif args.route_target:
        if not is_valid(args.route_target):
            exit(1)

    elif args.route_target_multi:
        for rt in args.route_target_multi.split(' '):
            if not is_valid(rt):
                exit(1)

    else:
        parser.print_help()
        exit(1)

    exit(0)