rplint.py 12 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/bin/env python3

from contextlib import suppress
import glob
import itertools
import os
import sys
8
from typing import Any, Callable, Iterable, Iterator, Optional, List, Union, Set
9 10 11 12 13 14 15

import dns.name

import pydnstest.augwrap
import pydnstest.matchpart
import pydnstest.scenario

16 17
Element = Union["Entry", "Step", pydnstest.scenario.Range]

18 19 20 21 22 23 24
RCODES = {"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED", "YXDOMAIN", "YXRRSET",
          "NXRRSET", "NOTAUTH", "NOTZONE", "BADVERS", "BADSIG", "BADKEY", "BADTIME", "BADMODE",
          "BADNAME", "BADALG", "BADTRUNC", "BADCOOKIE"}
FLAGS = {"QR", "AA", "TC", "RD", "RA", "AD", "CD"}
SECTIONS = {"question", "answer", "authority", "additional"}


25
class RplintError(ValueError):
26 27 28 29 30
    def __init__(self, fails):
        msg = ""
        for fail in fails:
            msg += str(fail) + "\n"
        super().__init__(msg)
31 32


33
def get_line_number(file: str, char_number: int) -> int:
34 35 36 37 38
    pos = 0
    for number, line in enumerate(open(file)):
        pos += len(line)
        if pos >= char_number:
            return number + 2
39
    return 0
40 41


42
def is_empty(iterable: Iterator[Any]) -> bool:
43 44 45 46 47 48 49 50
    try:
        next(iterable)
    except StopIteration:
        return True
    return False


class Entry:
51
    def __init__(self, node: pydnstest.augwrap.AugeasNode) -> None:
52 53 54 55 56 57 58 59 60
        self.match = {m.value for m in node.match("/match")}
        self.adjust = {a.value for a in node.match("/adjust")}
        self.authority = list(node.match("/section/authority/record"))
        self.reply = {r.value for r in node.match("/reply")}
        self.records = list(node.match("/section/*/record"))
        self.node = node


class Step:
61
    def __init__(self, node: pydnstest.augwrap.AugeasNode) -> None:
62 63 64
        self.node = node
        self.type = node["/type"].value
        try:
65
            self.entry = Entry(node["/entry"])  # type: Optional[Entry]
66 67 68
        except KeyError:
            self.entry = None

69

70
class RplintFail:
71 72 73
    def __init__(self, test: "RplintTest",
                 element: Optional[Element] = None,
                 etc: str = "") -> None:
74
        self.path = test.path
75
        self.element = element  # type: Optional[Element]
76 77
        self.line = get_line_number(self.path, element.node.char if element is not None else 0)
        self.etc = etc
78
        self.check = None  # type: Optional[Callable[[RplintTest], List[RplintFail]]]
79 80 81 82 83 84 85 86

    def __str__(self):
        if self.etc:
            return "{}:{} {}: {} ({})".format(os.path.basename(self.path), self.line,
                                              self.check.__name__, self.check.__doc__, self.etc)
        return "{}:{} {}: {}".format(os.path.basename(self.path), self.line, self.check.__name__,
                                     self.check.__doc__)

87

88
class RplintTest:
89
    def __init__(self, path: str) -> None:
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        aug = pydnstest.augwrap.AugeasWrapper(confpath=os.path.realpath(path),
                                              lens='Deckard',
                                              loadpath=os.path.join(os.path.dirname(__file__),
                                                                    'pydnstest'))
        self.node = aug.tree
        self.name = os.path.basename(path)
        self.path = path

        _, self.config = pydnstest.scenario.parse_file(os.path.realpath(path))
        self.range_entries = [Entry(node) for node in self.node.match("/scenario/range/entry")]
        self.steps = [Step(node) for node in self.node.match("/scenario/step")]
        self.step_entries = [step.entry for step in self.steps if step.entry is not None]
        self.entries = self.range_entries + self.step_entries

        self.ranges = [pydnstest.scenario.Range(n) for n in self.node.match("/scenario/range")]

106
        self.fails = None  # type: Optional[List[RplintFail]]
107
        self.checks = [
Štěpán Balážik's avatar
Štěpán Balážik committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            entry_more_than_one_rcode,
            entry_no_qname_qtype_copy_query,
            # Commented out for now until we implement selective turning off of checks
            # entry_ns_in_authority,
            range_overlapping_ips,
            range_shadowing_match_rules,
            step_check_answer_no_match,
            step_query_match,
            step_section_unchecked,
            step_unchecked_match,
            step_unchecked_rcode,
            scenario_ad_or_rrsig_no_ta,
            scenario_timestamp,
            config_trust_anchor_trailing_period_missing,
            step_duplicate_id,
        ]
124

125
    def run_checks(self) -> bool:
126
        """returns True iff all tests passed"""
127
        self.fails = []
128 129 130
        for check in self.checks:
            fails = check(self)
            for fail in fails:
131 132
                fail.check = check
            self.fails += fails
133

134
        if self.fails == []:
135 136 137
            return True
        return False

138 139 140
    def print_fails(self) -> None:
        if self.fails is None:
            raise RuntimeError("Maybe you should run some test first…")
141 142
        for fail in self.fails:
            print(fail)
143 144


145
def config_trust_anchor_trailing_period_missing(test: RplintTest) -> List[RplintFail]:
146 147 148 149
    """Trust-anchor option in configuration contains domain without trailing period"""
    for conf in test.config:
        if conf[0] == "trust-anchor":
            if conf[1].split()[0][-1] != ".":
150
                return [RplintFail(test, etc=conf[1])]
151 152 153
    return []


154
def scenario_timestamp(test: RplintTest) -> List[RplintFail]:
155 156 157 158 159
    """RRSSIG record present in test but no val-override-date or val-override-timestamp in config"""
    rrsigs = []
    for entry in test.entries:
        for record in entry.records:
            if record["/type"].value == "RRSIG":
160
                rrsigs.append(RplintFail(test, entry))
161 162 163 164 165 166 167
    if rrsigs:
        for k in test.config:
            if k[0] == "val-override-date" or k[0] == "val-override-timestamp":
                return []
    return rrsigs


168
def entry_no_qname_qtype_copy_query(test: RplintTest) -> List[RplintFail]:
169 170 171
    """ENTRY without qname and qtype in MATCH and without copy_query in ADJUST"""
    fails = []
    for entry in test.range_entries:
Štěpán Balážik's avatar
Štěpán Balážik committed
172 173
        if "question" not in entry.match and ("qname" not in entry.match or
                                              "qtype" not in entry.match):
174
            if "copy_query" not in entry.adjust:
175
                fails.append(RplintFail(test, entry))
176 177 178
    return fails


179
def entry_ns_in_authority(test: RplintTest) -> List[RplintFail]:
180 181 182 183 184 185
    """ENTRY has authority section with NS records, consider using MATCH subdomain"""
    fails = []
    for entry in test.range_entries:
        if entry.authority and "subdomain" not in entry.match:
            for record in entry.authority:
                if record["/type"].value == "NS":
186
                    fails.append(RplintFail(test, entry))
187 188 189
    return fails


190
def entry_more_than_one_rcode(test: RplintTest) -> List[RplintFail]:
191 192 193 194
    """ENTRY has more than one rcode in MATCH"""
    fails = []
    for entry in test.entries:
        if len(RCODES & entry.reply) > 1:
195
            fails.append(RplintFail(test, entry))
196 197 198
    return fails


199
def scenario_ad_or_rrsig_no_ta(test: RplintTest) -> List[RplintFail]:
200 201 202 203
    """AD or RRSIG present in test but no trust-anchor present in config"""
    dnssec = []
    for entry in test.entries:
        if "AD" in entry.reply or "AD" in entry.match:
204
            dnssec.append(RplintFail(test, entry))
205 206 207
        else:
            for record in entry.records:
                if record["/type"].value == "RRSIG":
208
                    dnssec.append(RplintFail(test, entry))
209 210 211 212 213 214 215 216

    if dnssec:
        for k in test.config:
            if k[0] == "trust-anchor":
                return []
    return dnssec


217
def step_query_match(test: RplintTest) -> List[RplintFail]:
218
    """STEP QUERY has a MATCH rule"""
219 220
    return [RplintFail(test, step) for step in test.steps if step.type == "QUERY" and
            step.entry and step.entry.match]
221 222


223
def step_check_answer_no_match(test: RplintTest) -> List[RplintFail]:
224
    """ENTRY in STEP CHECK_ANSWER has no MATCH rule"""
225
    return [RplintFail(test, step) for step in test.steps if step.type == "CHECK_ANSWER" and
226
            step.entry and not step.entry.match]
227 228


229
def step_unchecked_rcode(test: RplintTest) -> List[RplintFail]:
230 231 232
    """ENTRY specifies rcode but STEP MATCH does not check for it."""
    fails = []
    for step in test.steps:
233
        if step.type == "CHECK_ANSWER" and step.entry and "all" not in step.entry.match:
234
            if step.entry.reply & RCODES and "rcode" not in step.entry.match:
235
                fails.append(RplintFail(test, step.entry))
236 237 238
    return fails


239
def step_unchecked_match(test: RplintTest) -> List[RplintFail]:
240 241 242 243 244
    """ENTRY specifies flags but MATCH does not check for them"""
    fails = []
    for step in test.steps:
        if step.type == "CHECK_ANSWER":
            entry = step.entry
245 246
            if entry and "all" not in entry.match and entry.reply - RCODES and \
               "flags" not in entry.match:
247
                fails.append(RplintFail(test, entry, str(entry.reply - RCODES)))
248 249 250
    return fails


251
def step_section_unchecked(test: RplintTest) -> List[RplintFail]:
252 253 254
    """ENTRY has non-empty sections but MATCH does not check for all of them"""
    fails = []
    for step in test.steps:
255
        if step.type == "CHECK_ANSWER" and step.entry and "all" not in step.entry.match:
256 257 258
            for section in SECTIONS:
                if not is_empty(step.node.match("/entry/section/" + section + "/*")):
                    if section not in step.entry.match:
259
                        fails.append(RplintFail(test, step.entry, section))
260 261 262
    return fails


263
def range_overlapping_ips(test: RplintTest) -> List[RplintFail]:
264 265 266 267 268 269
    """RANGE has common IPs with some previous overlapping RANGE"""
    fails = []
    for r1, r2 in itertools.combinations(test.ranges, 2):
        # If the ranges overlap
        if min(r1.b, r2.b) >= max(r1.a, r2.a):
            if r1.addresses & r2.addresses:
270 271
                info = "previous range on line %d" % get_line_number(test.path, r1.node.char)
                fails.append(RplintFail(test, r2, info))
272 273 274
    return fails


275
def range_shadowing_match_rules(test: RplintTest) -> List[RplintFail]:
276
    """ENTRY has no effect since one of previous entries has the same or broader match rules"""
277 278 279
    fails = []
    for r in test.ranges:
        for e1, e2 in itertools.combinations(r.stored, 2):
280 281
            try:
                e1.match(e2.message)
282
            except ValueError:
283 284
                pass
            else:
285
                info = "previous entry on line %d" % get_line_number(test.path, e1.node.char)
286 287
                if e1.match_fields > e2.match_fields:
                    continue
288 289
                if "subdomain" not in e1.match_fields and "subdomain" in e2.match_fields:
                    continue
290
                fails.append(RplintFail(test, e2, info))
291 292 293
    return fails


294
def step_duplicate_id(test: RplintTest) -> List[RplintFail]:
295 296
    """STEP has the same ID as one of previous ones"""
    fails = []
297
    step_numbers = set()  # type: Set[int]
298 299
    for step in test.steps:
        if step.node.value in step_numbers:
300
            fails.append(RplintFail(test, step))
301 302
        else:
            step_numbers.add(step.node.value)
303 304 305 306 307 308 309 310
    return fails


# TODO: This will make sense after we fix how we handle defaults in deckard.aug and scenario.py
# We might just not use defaults altogether as testbound does
# if "copy_id" not in adjust:
#    entry_error(test, entry, "copy_id should be in ADJUST")

311
def test_run_rplint(rpl_path: str) -> None:
312
    t = RplintTest(rpl_path)
313 314
    passed = t.run_checks()
    if not passed:
315
        raise RplintError(t.fails)
316

317

318
def main():
319 320 321 322 323
    try:
        test_path = sys.argv[1]
    except IndexError:
        print("usage: %s <path to rpl file>" % sys.argv[0])
        sys.exit(2)
324 325 326 327
    if not os.path.isfile(test_path):
        print("rplint.py works on single file only.")
        print("Use rplint.sh with --scenarios=<directory with rpls> to run on rpls.")
        sys.exit(2)
328 329 330
    print("Linting %s" % test_path)
    t = RplintTest(test_path)
    passed = t.run_checks()
331
    t.print_fails()
332 333 334 335

    if passed:
        sys.exit(0)
    sys.exit(1)
336 337 338 339


if __name__ == '__main__':
    main()