rplint.py 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/env python3

from contextlib import suppress
import glob
import itertools
import os
import sys

import dns.name

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

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"}


22
class RplintError(ValueError):
23 24 25 26 27
    def __init__(self, fails):
        msg = ""
        for fail in fails:
            msg += str(fail) + "\n"
        super().__init__(msg)
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
def get_line_number(file, char_number):
    pos = 0
    for number, line in enumerate(open(file)):
        pos += len(line)
        if pos >= char_number:
            return number + 2


def is_empty(iterable):
    try:
        next(iterable)
    except StopIteration:
        return True
    return False


class Entry:
    def __init__(self, node):
        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:
    def __init__(self, node):
        self.node = node
        self.type = node["/type"].value
        try:
            self.entry = Entry(node["/entry"])
        except KeyError:
            self.entry = None

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
class RplintFail:
    def __init__(self, test, element=None, etc=""):
        self.path = test.path
        self.element = element
        self.line = get_line_number(self.path, element.node.char if element is not None else 0)
        self.etc = etc
        self.check = None

    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__)

80

81
class RplintTest:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def __init__(self, path):
        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")]

99
        self.fails = None
100
        self.checks = [
Štěpán Balážik's avatar
Štěpán Balážik committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                        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,
                    ]
117

118 119
    def run_checks(self):
        """returns True iff all tests passed"""
120
        self.fails = []
121 122 123
        for check in self.checks:
            fails = check(self)
            for fail in fails:
124 125
                fail.check = check
            self.fails += fails
126

127
        if self.fails == []:
128 129 130
            return True
        return False

131 132 133
    def print_fails(self):
        for fail in self.fails:
            print(fail)
134 135


136
def config_trust_anchor_trailing_period_missing(test):
137 138 139 140
    """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] != ".":
141
                return [RplintFail(test, etc=conf[1])]
142 143 144
    return []


145
def scenario_timestamp(test):
146 147 148 149 150
    """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":
151
                rrsigs.append(RplintFail(test, entry))
152 153 154 155 156 157 158 159 160 161 162
    if rrsigs:
        for k in test.config:
            if k[0] == "val-override-date" or k[0] == "val-override-timestamp":
                return []
    return rrsigs


def entry_no_qname_qtype_copy_query(test):
    """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
163 164
        if "question" not in entry.match and ("qname" not in entry.match or
                                              "qtype" not in entry.match):
165
            if "copy_query" not in entry.adjust:
166
                fails.append(RplintFail(test, entry))
167 168 169 170 171 172 173 174 175 176
    return fails


def entry_ns_in_authority(test):
    """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":
177
                    fails.append(RplintFail(test, entry))
178 179 180 181 182 183 184 185
    return fails


def entry_more_than_one_rcode(test):
    """ENTRY has more than one rcode in MATCH"""
    fails = []
    for entry in test.entries:
        if len(RCODES & entry.reply) > 1:
186
            fails.append(RplintFail(test, entry))
187 188 189
    return fails


190
def scenario_ad_or_rrsig_no_ta(test):
191 192 193 194
    """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:
195
            dnssec.append(RplintFail(test, entry))
196 197 198
        else:
            for record in entry.records:
                if record["/type"].value == "RRSIG":
199
                    dnssec.append(RplintFail(test, entry))
200 201 202 203 204 205 206 207 208 209

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


def step_query_match(test):
    """STEP QUERY has a MATCH rule"""
210
    return [RplintFail(test, step) for step in test.steps if step.type == "QUERY" and step.entry.match]
211 212 213 214


def step_check_answer_no_match(test):
    """ENTRY in STEP CHECK_ANSWER has no MATCH rule"""
215
    return [RplintFail(test, step) for step in test.steps if step.type == "CHECK_ANSWER" and
Štěpán Balážik's avatar
Štěpán Balážik committed
216
            not step.entry.match]
217 218 219 220 221 222 223 224


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


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


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


def range_overlapping_ips(test):
    """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:
259 260
                info = "previous range on line %d" % get_line_number(test.path, r1.node.char)
                fails.append(RplintFail(test, r2, info))
261 262 263 264
    return fails


def range_shadowing_match_rules(test):
265
    """ENTRY has no effect since one of previous entries has the same or broader match rules"""
266 267 268
    fails = []
    for r in test.ranges:
        for e1, e2 in itertools.combinations(r.stored, 2):
269 270 271 272 273 274
            try:
                e1.match(e2.message)
                info = "previous entry on line %d" % get_line_number(test.path, e1.node.char)
                fails.append(RplintFail(test, e2, info))
            except ValueError:
                pass
275 276 277 278 279 280
    return fails


def step_duplicate_id(test):
    """STEP has the same ID as one of previous ones"""
    fails = []
281 282 283
    step_numbers = set()
    for step in test.steps:
        if step.node.value in step_numbers:
284
            fails.append(RplintFail(test, step))
285 286
        else:
            step_numbers.add(step.node.value)
287 288 289 290 291 292 293 294
    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")

295 296
def test_run_rplint(rpl_path):
    t = RplintTest(rpl_path)
297 298
    passed = t.run_checks()
    if not passed:
299
        raise RplintError(t.fails)
300

301
if __name__ == '__main__':
302 303 304 305 306
    try:
        test_path = sys.argv[1]
    except IndexError:
        print("usage: %s <path to rpl file>" % sys.argv[0])
        sys.exit(2)
307 308 309 310
    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)
311 312 313
    print("Linting %s" % test_path)
    t = RplintTest(test_path)
    passed = t.run_checks()
314
    t.print_fails()
315 316 317 318

    if passed:
        sys.exit(0)
    sys.exit(1)