scenario.py 31.1 KB
Newer Older
1
from abc import ABC
2
import binascii
3
import calendar
4
from datetime import datetime
5
import logging
Tomas Krizek's avatar
Tomas Krizek committed
6
import os  # requires posix
7
import random
8 9
import socket
import struct
Marek Vavruša's avatar
Marek Vavruša committed
10
import time
11
from typing import Optional
12 13 14

import dns.dnssec
import dns.message
15
import dns.name
16 17 18
import dns.rcode
import dns.rrset
import dns.tsigkeyring
Marek Vavruša's avatar
Marek Vavruša committed
19

20
import pydnstest.augwrap
21
import pydnstest.matchpart
22
import pydnstest.mock_client
23

24

25 26 27 28 29
def str2bool(v):
    """ Return conversion of JSON-ish string value to boolean. """
    return v.lower() in ('yes', 'true', 'on', '1')


30 31 32 33
# Global statistics
g_rtt = 0.0
g_nqueries = 0

34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
class DNSBlob(ABC):
    def to_wire(self) -> bytes:
        raise NotImplementedError

    def __str__(self) -> str:
        return '<DNSBlob>'


class DNSMessage(DNSBlob):
    def __init__(self, message: dns.message.Message) -> None:
        assert message is not None
        self.message = message

    def to_wire(self) -> bytes:
        return self.message.to_wire(max_size=65535)

    def __str__(self) -> str:
        return str(self.message)


class DNSReply(DNSMessage):
56 57
    def __init__(
                self,
58 59 60 61
                message: dns.message.Message,
                query: Optional[dns.message.Message] = None,
                copy_id: bool = False,
                copy_query: bool = False
62
            ) -> None:
63 64 65 66 67
        super().__init__(message)
        if copy_id or copy_query:
            if query is None:
                raise ValueError("query must be provided to adjust copy_id/copy_query")
            self.adjust_reply(query, copy_id, copy_query)
68

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    def adjust_reply(
                self,
                query: dns.message.Message,
                copy_id: bool = True,
                copy_query: bool = True
            ) -> None:
        answer = dns.message.from_wire(self.message.to_wire(),
                                       xfr=self.message.xfr,
                                       one_rr_per_rrset=True)
        answer.use_edns(query.edns, query.ednsflags, options=self.message.options)
        if copy_id:
            answer.id = query.id
            # Copy letter-case if the template has QD
            if answer.question:
                answer.question[0].name = query.question[0].name
        if copy_query:
            answer.question = query.question
        # Re-set, as the EDNS might have reset the ext-rcode
        answer.set_rcode(self.message.rcode())
88

89 90 91 92 93
        # sanity check: adjusted answer should be almost the same
        assert len(answer.answer) == len(self.message.answer)
        assert len(answer.authority) == len(self.message.authority)
        assert len(answer.additional) == len(self.message.additional)
        self.message = answer
94

95 96 97 98 99 100 101 102 103 104 105

class DNSReplyRaw(DNSBlob):
    def __init__(
                self,
                wire: bytes,
                query: Optional[dns.message.Message] = None,
                copy_id: bool = False
            ) -> None:
        assert wire is not None
        self.wire = wire
        if copy_id:
106 107
            if query is None:
                raise ValueError("query must be provided to adjust copy_id")
108 109 110 111 112
            self.adjust_reply(query, copy_id)

    def adjust_reply(
                self,
                query: dns.message.Message,
113
                raw_id: bool = True
114
            ) -> None:
115
        if raw_id:
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
            if len(self.wire) < 2:
                raise ValueError(
                    'wire data must contain at least 2 bytes to adjust query id')
            raw_answer = bytearray(self.wire)
            struct.pack_into('!H', raw_answer, 0, query.id)
            self.wire = bytes(raw_answer)

    def to_wire(self) -> bytes:
        return self.wire

    def __str__(self) -> str:
        return '<DNSReplyRaw>'


class DNSReplyServfail(DNSMessage):
    def __init__(self, query: dns.message.Message) -> None:
        message = dns.message.make_response(query)
        message.set_rcode(dns.rcode.SERVFAIL)
        super().__init__(message)
135 136


Marek Vavruša's avatar
Marek Vavruša committed
137 138
class Entry:
    """
139 140
    Data entry represents scripted message and extra metadata,
    notably match criteria and reply adjustments.
Marek Vavruša's avatar
Marek Vavruša committed
141 142 143 144 145 146 147
    """

    # Globals
    default_ttl = 3600
    default_cls = 'IN'
    default_rc = 'NOERROR'

148
    def __init__(self, node):
Marek Vavruša's avatar
Marek Vavruša committed
149
        """ Initialize data entry. """
150
        self.node = node
Marek Vavruša's avatar
Marek Vavruša committed
151 152
        self.origin = '.'
        self.message = dns.message.Message()
153 154
        self.message.use_edns(edns=0, payload=4096)
        self.fired = 0
Marek Vavruša's avatar
Marek Vavruša committed
155

156
        # RAW
157
        self.raw_data = self.process_raw()
158

159
        # MATCH
160
        self.match_fields = self.process_match()
161

162
        # FLAGS
163
        self.process_reply_line()
164

165
        # ADJUST
166
        self.adjust_fields = {m.value for m in node.match("/adjust")}
167

168
        # MANDATORY
169
        try:
170
            self.mandatory = list(node.match("/mandatory"))[0]
171
        except (KeyError, IndexError):
172
            self.mandatory = None
173

174
        # TSIG
175 176 177 178 179 180 181
        self.process_tsig()

        # SECTIONS & RECORDS
        self.sections = self.process_sections()

    def process_raw(self):
        try:
182
            return binascii.unhexlify(self.node["/raw"].value)
183
        except KeyError:
184
            return None
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

    def process_match(self):
        try:
            self.node["/match_present"]
        except KeyError:
            return None

        fields = set(m.value for m in self.node.match("/match"))

        if 'all' in fields:
            fields.remove("all")
            fields |= set(["opcode", "qtype", "qname", "flags",
                           "rcode", "answer", "authority", "additional"])

        if 'question' in fields:
            fields.remove("question")
            fields |= set(["qtype", "qname"])

        return fields

    def process_reply_line(self):
        """Extracts flags, rcode and opcode from given node and adjust dns message accordingly"""
        self.fields = [f.value for f in self.node.match("/reply")]
        if 'DO' in self.fields:
            self.message.want_dnssec(True)
        opcode = self.get_opcode(fields=self.fields)
        rcode = self.get_rcode(fields=self.fields)
        self.message.flags = self.get_flags(fields=self.fields)
        if rcode is not None:
            self.message.set_rcode(rcode)
        if opcode is not None:
            self.message.set_opcode(opcode)

    def process_tsig(self):
219
        try:
220
            tsig = list(self.node.match("/tsig"))[0]
221 222 223 224 225 226 227
            tsig_keyname = tsig["/keyname"].value
            tsig_secret = tsig["/secret"].value
            keyring = dns.tsigkeyring.from_text({tsig_keyname: tsig_secret})
            self.message.use_tsig(keyring=keyring, keyname=tsig_keyname)
        except (KeyError, IndexError):
            pass

228 229 230
    def process_sections(self):
        sections = set()
        for section in self.node.match("/section/*"):
Tomas Krizek's avatar
Tomas Krizek committed
231
            section_name = os.path.basename(section.path)
232
            sections.add(section_name)
233 234 235
            for record in section.match("/record"):
                owner = record['/domain'].value
                if not owner.endswith("."):
236
                    owner += self.origin
237 238 239 240 241 242 243
                try:
                    ttl = dns.ttl.from_text(record['/ttl'].value)
                except KeyError:
                    ttl = self.default_ttl
                try:
                    rdclass = dns.rdataclass.from_text(record['/class'].value)
                except KeyError:
244
                    rdclass = dns.rdataclass.from_text(self.default_cls)
245 246 247 248
                rdtype = dns.rdatatype.from_text(record['/type'].value)
                rr = dns.rrset.from_text(owner, ttl, rdclass, rdtype)
                if section_name != "question":
                    rd = record['/data'].value.split()
249
                    if rd:
250 251 252 253 254 255 256 257
                        if rdtype == dns.rdatatype.DS:
                            rd[1] = str(dns.dnssec.algorithm_from_text(rd[1]))
                        rd = dns.rdata.from_text(rr.rdclass, rr.rdtype, ' '.join(
                            rd), origin=dns.name.from_text(self.origin), relativize=False)
                    rr.add(rd)
                if section_name == 'question':
                    if rr.rdtype == dns.rdatatype.AXFR:
                        self.message.xfr = True
258
                    self.message.question.append(rr)
259
                elif section_name == 'answer':
260
                    self.message.answer.append(rr)
261
                elif section_name == 'authority':
262
                    self.message.authority.append(rr)
263
                elif section_name == 'additional':
264
                    self.message.additional.append(rr)
265
        return sections
266 267 268

    def __str__(self):
        txt = 'ENTRY_BEGIN\n'
269
        if self.raw_data is None:
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
            txt += 'MATCH {0}\n'.format(' '.join(self.match_fields))
        txt += 'ADJUST {0}\n'.format(' '.join(self.adjust_fields))
        txt += 'REPLY {rcode} {flags}\n'.format(
            rcode=dns.rcode.to_text(self.message.rcode()),
            flags=' '.join([dns.flags.to_text(self.message.flags),
                            dns.flags.edns_to_text(self.message.ednsflags)])
        )
        for sect_name in ['question', 'answer', 'authority', 'additional']:
            sect = getattr(self.message, sect_name)
            if not sect:
                continue
            txt += 'SECTION {n}\n'.format(n=sect_name.upper())
            for rr in sect:
                txt += str(rr)
                txt += '\n'
285
        if self.raw_data is not None:
286 287 288 289 290 291 292 293 294
            txt += 'RAW\n'
            if self.raw_data:
                txt += binascii.hexlify(self.raw_data)
            else:
                txt += 'NULL'
            txt += '\n'
        txt += 'ENTRY_END\n'
        return txt

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
    @classmethod
    def get_flags(cls, fields):
        """From `fields` extracts and returns flags"""
        flags = []
        for code in fields:
            try:
                dns.flags.from_text(code)  # throws KeyError on failure
                flags.append(code)
            except KeyError:
                pass
        return dns.flags.from_text(' '.join(flags))

    @classmethod
    def get_rcode(cls, fields):
        """
        From `fields` extracts and returns rcode.
        Throws `ValueError` if there are more then one rcodes
        """
        rcodes = []
        for code in fields:
            try:
                rcodes.append(dns.rcode.from_text(code))
            except dns.rcode.UnknownRcode:
                pass
        if len(rcodes) > 1:
            raise ValueError("Parse failed, too many rcode values.", rcodes)
321
        if not rcodes:
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            return None
        return rcodes[0]

    @classmethod
    def get_opcode(cls, fields):
        """
        From `fields` extracts and returns opcode.
        Throws `ValueError` if there are more then one opcodes
        """
        opcodes = []
        for code in fields:
            try:
                opcodes.append(dns.opcode.from_text(code))
            except dns.opcode.UnknownOpcode:
                pass
        if len(opcodes) > 1:
            raise ValueError("Parse failed, too many opcode values.")
339
        if not opcodes:
340 341 342
            return None
        return opcodes[0]

Marek Vavruša's avatar
Marek Vavruša committed
343 344
    def match(self, msg):
        """ Compare scripted reply to given message based on match criteria. """
345
        for code in self.match_fields:
Marek Vavruša's avatar
Marek Vavruša committed
346
            try:
347 348
                pydnstest.matchpart.match_part(self.message, msg, code)
            except pydnstest.matchpart.DataMismatch as ex:
349
                errstr = '%s in the response:\n%s' % (str(ex), msg.to_text())
350 351
                # TODO: cisla radku
                raise ValueError("%s, \"%s\": %s" % (self.node.span, code, errstr))
Marek Vavruša's avatar
Marek Vavruša committed
352 353

    def cmp_raw(self, raw_value):
354
        assert self.raw_data is not None
Marek Vavruša's avatar
Marek Vavruša committed
355 356 357 358 359 360 361
        expected = None
        if self.raw_data is not None:
            expected = binascii.hexlify(self.raw_data)
        got = None
        if raw_value is not None:
            got = binascii.hexlify(raw_value)
        if expected != got:
362
            raise ValueError("raw message comparsion failed: expected %s got %s" % (expected, got))
Marek Vavruša's avatar
Marek Vavruša committed
363

364
    def reply(self, query) -> Optional[DNSBlob]:
365 366
        if 'do_not_answer' in self.adjust_fields:
            return None
367
        if self.raw_data is not None:
368
            raw_id = 'raw_id' in self.adjust_fields
369
            assert self.raw_data is not None
370
            return DNSReplyRaw(self.raw_data, query, raw_id)
371 372 373
        copy_id = 'copy_id' in self.adjust_fields
        copy_query = 'copy_query' in self.adjust_fields
        return DNSReply(self.message, query, copy_id, copy_query)
374

375 376 377 378
    def set_edns(self, fields):
        """ Set EDNS version and bufsize. """
        version = 0
        bufsize = 4096
379
        if fields and fields[0].isdigit():
380
            version = int(fields.pop(0))
381
        if fields and fields[0].isdigit():
382
            bufsize = int(fields.pop(0))
383 384 385
        if bufsize == 0:
            self.message.use_edns(False)
            return
386 387
        opts = []
        for v in fields:
Marek Vavrusa's avatar
Marek Vavrusa committed
388
            k, v = tuple(v.split('=')) if '=' in v else (v, True)
389
            if k.lower() == 'nsid':
390
                opts.append(dns.edns.GenericOption(dns.edns.NSID, '' if v is True else v))
391 392 393
            if k.lower() == 'subnet':
                net = v.split('/')
                subnet_addr = net[0]
394 395
                family = socket.AF_INET6 if ':' in subnet_addr else socket.AF_INET
                addr = socket.inet_pton(family, subnet_addr)
396 397 398
                prefix = len(addr) * 8
                if len(net) > 1:
                    prefix = int(net[1])
399 400
                addr = addr[0: (prefix + 7) / 8]
                if prefix % 8 != 0:  # Mask the last byte
401
                    addr = addr[:-1] + chr(ord(addr[-1]) & 0xFF << (8 - prefix % 8))
402 403 404
                opts.append(dns.edns.GenericOption(8, struct.pack(
                    "!HBB", 1 if family == socket.AF_INET else 2, prefix, 0) + addr))
        self.message.use_edns(edns=version, payload=bufsize, options=opts)
405

406

Marek Vavruša's avatar
Marek Vavruša committed
407 408 409 410
class Range:
    """
    Range represents a set of scripted queries valid for given step range.
    """
411
    log = logging.getLogger('pydnstest.scenario.Range')
Marek Vavruša's avatar
Marek Vavruša committed
412

413
    def __init__(self, node):
Marek Vavruša's avatar
Marek Vavruša committed
414
        """ Initialize reply range. """
415
        self.node = node
416 417
        self.a = int(node['/from'].value)
        self.b = int(node['/to'].value)
418
        assert self.a <= self.b
419 420 421

        address = node["/address"].value
        self.addresses = {address} if address is not None else set()
422
        self.addresses |= {a.value for a in node.match("/address/*")}
423
        self.stored = [Entry(n) for n in node.match("/entry")]
424 425 426 427 428
        self.args = {}
        self.received = 0
        self.sent = 0

    def __del__(self):
429 430
        self.log.info('[ RANGE %d-%d ] %s received: %d sent: %d',
                      self.a, self.b, self.addresses, self.received, self.sent)
Marek Vavruša's avatar
Marek Vavruša committed
431

432 433 434 435 436 437 438 439 440 441
    def __str__(self):
        txt = '\nRANGE_BEGIN {a} {b}\n'.format(a=self.a, b=self.b)
        for addr in self.addresses:
            txt += '        ADDRESS {0}\n'.format(addr)

        for entry in self.stored:
            txt += '\n'
            txt += str(entry)
        txt += 'RANGE_END\n\n'
        return txt
Marek Vavruša's avatar
Marek Vavruša committed
442

443
    def eligible(self, ident, address):
Marek Vavruša's avatar
Marek Vavruša committed
444
        """ Return true if this range is eligible for fetching reply. """
445
        if self.a <= ident <= self.b:
446
            return (None is address
447 448
                    or set() == self.addresses
                    or address in self.addresses)
Marek Vavruša's avatar
Marek Vavruša committed
449 450
        return False

451
    def reply(self, query: dns.message.Message) -> Optional[DNSBlob]:
452
        """Get answer for given query (adjusted if needed)."""
453
        self.received += 1
Marek Vavruša's avatar
Marek Vavruša committed
454 455 456
        for candidate in self.stored:
            try:
                candidate.match(query)
457
                resp = candidate.reply(query)
458 459 460
                # Probabilistic loss
                if 'LOSS' in self.args:
                    if random.random() < float(self.args['LOSS']):
461
                        return DNSReplyServfail(query)
462
                self.sent += 1
463
                candidate.fired += 1
464
                return resp
465
            except ValueError:
Marek Vavruša's avatar
Marek Vavruša committed
466
                pass
467
        return DNSReplyServfail(query)
Marek Vavruša's avatar
Marek Vavruša committed
468 469


470
class StepLogger(logging.LoggerAdapter):  # pylint: disable=too-few-public-methods
471 472 473 474 475 476 477
    """
    Prepent Step identification before each log message.
    """
    def process(self, msg, kwargs):
        return '[STEP %s %s] %s' % (self.extra['id'], self.extra['type'], msg), kwargs


Marek Vavruša's avatar
Marek Vavruša committed
478 479 480 481 482
class Step:
    """
    Step represents one scripted action in a given moment,
    each step has an order identifier, type and optionally data entry.
    """
483
    require_data = ['QUERY', 'CHECK_ANSWER', 'REPLY']
Marek Vavruša's avatar
Marek Vavruša committed
484

485
    def __init__(self, node):
Marek Vavruša's avatar
Marek Vavruša committed
486
        """ Initialize single scenario step. """
487
        self.node = node
488 489
        self.id = int(node.value)
        self.type = node["/type"].value
490
        self.log = StepLogger(logging.getLogger('pydnstest.scenario.Step'),
491
                              {'id': self.id, 'type': self.type})
492 493 494 495 496
        try:
            self.delay = int(node["/timestamp"].value)
        except KeyError:
            pass
        self.data = [Entry(n) for n in node.match("/entry")]
497
        self.queries = []
498
        self.has_data = self.type in Step.require_data
Marek Vavruša's avatar
Marek Vavruša committed
499 500
        self.answer = None
        self.raw_answer = None
501 502 503
        self.repeat_if_fail = 0
        self.pause_if_fail = 0
        self.next_if_fail = -1
Petr Špaček's avatar
Petr Špaček committed
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    def __str__(self):
        txt = '\nSTEP {i} {t}'.format(i=self.id, t=self.type)
        if self.repeat_if_fail:
            txt += ' REPEAT {v}'.format(v=self.repeat_if_fail)
        elif self.pause_if_fail:
            txt += ' PAUSE {v}'.format(v=self.pause_if_fail)
        elif self.next_if_fail != -1:
            txt += ' NEXT {v}'.format(v=self.next_if_fail)
        # if self.args:
        #     txt += ' '
        #     txt += ' '.join(self.args)
        txt += '\n'

        for data in self.data:
            # from IPython.core.debugger import Tracer
            # Tracer()()
            txt += str(data)
        return txt
Marek Vavruša's avatar
Marek Vavruša committed
523

524
    def play(self, ctx):
Marek Vavruša's avatar
Marek Vavruša committed
525 526
        """ Play one step from a scenario. """
        if self.type == 'QUERY':
527 528
            self.log.info('')
            self.log.debug(self.data[0].message.to_text())
529
            # Parse QUERY-specific parameters
530 531
            choice, tcp = None, False
            return self.__query(ctx, tcp=tcp, choice=choice)
532
        elif self.type == 'CHECK_OUT_QUERY':  # ignore
533
            self.log.info('')
534
            return None
535
        elif self.type == 'CHECK_ANSWER' or self.type == 'ANSWER':
536
            self.log.info('')
Marek Vavruša's avatar
Marek Vavruša committed
537
            return self.__check_answer(ctx)
538
        elif self.type == 'TIME_PASSES ELAPSE':
539
            self.log.info('')
540
            return self.__time_passes()
541
        elif self.type == 'REPLY' or self.type == 'MOCK':
542
            self.log.info('')
543
            return None
Marek Vavruša's avatar
Marek Vavruša committed
544
        else:
545
            raise NotImplementedError('step %03d type %s unsupported' % (self.id, self.type))
546

Marek Vavruša's avatar
Marek Vavruša committed
547 548
    def __check_answer(self, ctx):
        """ Compare answer from previously resolved query. """
549
        if not self.data:
550
            raise ValueError("response definition required")
Marek Vavruša's avatar
Marek Vavruša committed
551
        expected = self.data[0]
552
        if expected.raw_data is not None:
553
            self.log.debug("raw answer: %s", ctx.last_raw_answer.to_text())
Marek Vavruša's avatar
Marek Vavruša committed
554 555 556
            expected.cmp_raw(ctx.last_raw_answer)
        else:
            if ctx.last_answer is None:
557
                raise ValueError("no answer from preceding query")
558
            self.log.debug("answer: %s", ctx.last_answer.to_text())
Marek Vavruša's avatar
Marek Vavruša committed
559 560
            expected.match(ctx.last_answer)

561
    def __query(self, ctx, tcp=False, choice=None):
562 563 564 565 566
        """
        Send query and wait for an answer (if the query is not RAW).

        The received answer is stored in self.answer and ctx.last_answer.
        """
567
        if not self.data:
568
            raise ValueError("query definition required")
569
        if self.data[0].raw_data is not None:
Marek Vavruša's avatar
Marek Vavruša committed
570 571 572 573
            data_to_wire = self.data[0].raw_data
        else:
            # Don't use a message copy as the EDNS data portion is not copied.
            data_to_wire = self.data[0].message.to_wire()
574
        if choice is None or not choice:
575
            choice = list(ctx.client.keys())[0]
576
        if choice not in ctx.client:
577
            raise ValueError('step %03d invalid QUERY target: %s' % (self.id, choice))
578

579
        tstart = datetime.now()
580 581

        # Send query and wait for answer
Marek Vavruša's avatar
Marek Vavruša committed
582
        answer = None
583 584 585 586
        sock = pydnstest.mock_client.setup_socket(ctx.client[choice][0],
                                                  ctx.client[choice][1],
                                                  tcp)
        pydnstest.mock_client.send_query(sock, data_to_wire)
587
        if self.data[0].raw_data is None:
588 589
            answer = pydnstest.mock_client.get_answer(sock)

590 591 592 593 594
        # Track RTT
        rtt = (datetime.now() - tstart).total_seconds() * 1000
        global g_rtt, g_nqueries
        g_nqueries += 1
        g_rtt += rtt
595

Marek Vavruša's avatar
Marek Vavruša committed
596 597 598 599
        # Remember last answer for checking later
        self.raw_answer = answer
        ctx.last_raw_answer = answer
        if self.raw_answer is not None:
Petr Špaček's avatar
Petr Špaček committed
600
            self.answer = dns.message.from_wire(self.raw_answer, one_rr_per_rrset=True)
Marek Vavruša's avatar
Marek Vavruša committed
601 602 603 604
        else:
            self.answer = None
        ctx.last_answer = self.answer

605
    def __time_passes(self):
Marek Vavruša's avatar
Marek Vavruša committed
606
        """ Modify system time. """
607 608 609 610
        file_old = os.environ["FAKETIME_TIMESTAMP_FILE"]
        file_next = os.environ["FAKETIME_TIMESTAMP_FILE"] + ".next"
        with open(file_old, 'r') as time_file:
            line = time_file.readline().strip()
611
        t = time.mktime(datetime.strptime(line, '@%Y-%m-%d %H:%M:%S').timetuple())
612
        t += self.delay
613 614 615 616
        with open(file_next, 'w') as time_file:
            time_file.write(datetime.fromtimestamp(t).strftime('@%Y-%m-%d %H:%M:%S') + "\n")
            time_file.flush()
        os.replace(file_next, file_old)
Marek Vavruša's avatar
Marek Vavruša committed
617

618

Marek Vavruša's avatar
Marek Vavruša committed
619
class Scenario:
620
    log = logging.getLogger('pydnstest.scenatio.Scenario')
621

622
    def __init__(self, node, filename):
Marek Vavruša's avatar
Marek Vavruša committed
623
        """ Initialize scenario with description. """
624
        self.node = node
625
        self.info = node.value
626
        self.file = filename
627
        self.ranges = [Range(n) for n in node.match("/range")]
628
        self.current_range = None
629
        self.steps = [Step(n) for n in node.match("/step")]
Marek Vavruša's avatar
Marek Vavruša committed
630
        self.current_step = None
631
        self.client = {}
Marek Vavruša's avatar
Marek Vavruša committed
632

633 634 635 636 637
    def __str__(self):
        txt = 'SCENARIO_BEGIN'
        if self.info:
            txt += ' {0}'.format(self.info)
        txt += '\n'
638 639
        for range_ in self.ranges:
            txt += str(range_)
640 641 642 643 644
        for step in self.steps:
            txt += str(step)
        txt += "\nSCENARIO_END"
        return txt

645
    def reply(self, query: dns.message.Message, address=None) -> Optional[DNSBlob]:
646
        """Generate answer packet for given query."""
647
        current_step_id = self.current_step.id
Marek Vavruša's avatar
Marek Vavruša committed
648 649
        # Unknown address, select any match
        # TODO: workaround until the server supports stub zones
650
        all_addresses = set()  # type: ignore
651 652 653
        for rng in self.ranges:
            all_addresses.update(rng.addresses)
        if address not in all_addresses:
Marek Vavruša's avatar
Marek Vavruša committed
654 655 656
            address = None
        # Find current valid query response range
        for rng in self.ranges:
657
            if rng.eligible(current_step_id, address):
658
                self.current_range = rng
659
                return rng.reply(query)
Marek Vavruša's avatar
Marek Vavruša committed
660 661
        # Find any prescripted one-shot replies
        for step in self.steps:
662
            if step.id < current_step_id or step.type != 'REPLY':
Marek Vavruša's avatar
Marek Vavruša committed
663 664 665
                continue
            try:
                candidate = step.data[0]
666 667 668
                candidate.match(query)
                step.data.remove(candidate)
                return candidate.reply(query)
669
            except (IndexError, ValueError):
Marek Vavruša's avatar
Marek Vavruša committed
670
                pass
671
        return DNSReplyServfail(query)
Marek Vavruša's avatar
Marek Vavruša committed
672

673
    def play(self, paddr):
Marek Vavruša's avatar
Marek Vavruša committed
674
        """ Play given scenario. """
675 676
        # Store test subject => address mapping
        self.client = paddr
Marek Vavruša's avatar
Marek Vavruša committed
677

678 679 680 681 682 683 684
        step = None
        i = 0
        while i < len(self.steps):
            step = self.steps[i]
            self.current_step = step
            try:
                step.play(self)
685
            except ValueError as ex:
686
                if step.repeat_if_fail > 0:
687
                    self.log.info("[play] step %d: exception - '%s', retrying step %d (%d left)",
688
                                  step.id, ex, step.next_if_fail, step.repeat_if_fail)
689
                    step.repeat_if_fail -= 1
690
                    if step.pause_if_fail > 0:
691
                        time.sleep(step.pause_if_fail)
692
                    if step.next_if_fail != -1:
693 694
                        next_steps = [j for j in range(len(self.steps)) if self.steps[
                            j].id == step.next_if_fail]
695
                        if not next_steps:
696 697
                            raise ValueError('step %d: wrong NEXT value "%d"' %
                                             (step.id, step.next_if_fail))
698
                        next_step = next_steps[0]
699
                        if next_step < len(self.steps):
700 701
                            i = next_step
                        else:
702 703
                            raise ValueError('step %d: Can''t branch to NEXT value "%d"' %
                                             (step.id, step.next_if_fail))
704 705
                    continue
                else:
706 707
                    raise ValueError('%s step %d %s' % (self.file, step.id, str(ex)))
            i += 1
708

709 710
        for r in self.ranges:
            for e in r.stored:
711
                if e.mandatory and e.fired == 0:
712
                    # TODO: cisla radku
713
                    raise ValueError('Mandatory section at %s not fired' % e.mandatory.span)
714

715

716
def get_next(file_in, skip_empty=True):
717 718 719
    """ Return next token from the input stream. """
    while True:
        line = file_in.readline()
720
        if not line:
721
            return False
722
        quoted, escaped = False, False
723 724
        for i, char in enumerate(line):
            if char == '\\':
725
                escaped = not escaped
726
            if not escaped and char == '"':
727
                quoted = not quoted
728
            if char == ';' and not quoted:
729 730
                line = line[0:i]
                break
731
            if char != '\\':
732
                escaped = False
733
        tokens = ' '.join(line.strip().split()).split()
734
        if not tokens:
735 736 737 738
            if skip_empty:
                continue
            else:
                return '', []
739 740 741
        op = tokens.pop(0)
        return op, tokens

742

743
def parse_config(scn_cfg, qmin, installdir):  # FIXME: pylint: disable=too-many-statements
744 745
    """
    Transform scene config (key, value) pairs into dict filled with defaults.
746 747 748
    Returns tuple:
      context dict: {Jinja2 variable: value}
      trust anchor dict: {domain: [TA lines for particular domain]}
749 750 751 752 753 754
    """
    # defaults
    do_not_query_localhost = True
    harden_glue = True
    sockfamily = 0  # auto-select value for socket.getaddrinfo
    trust_anchor_list = []
755
    trust_anchor_files = {}
756
    negative_ta_list = []
757 758 759 760 761 762 763 764 765 766 767
    stub_addr = None
    override_timestamp = None

    features = {}
    feature_list_delimiter = ';'
    feature_pair_delimiter = '='

    for k, v in scn_cfg:
        # Enable selectively for some tests
        if k == 'do-not-query-localhost':
            do_not_query_localhost = str2bool(v)
768
        elif k == 'domain-insecure':
769
            negative_ta_list.append(v)
770
        elif k == 'harden-glue':
771
            harden_glue = str2bool(v)
772
        elif k == 'query-minimization':
773 774
            qmin = str2bool(v)
        elif k == 'trust-anchor':
775 776 777 778 779 780
            trust_anchor = v.strip('"\'')
            trust_anchor_list.append(trust_anchor)
            domain = dns.name.from_text(trust_anchor.split()[0]).canonicalize()
            if domain not in trust_anchor_files:
                trust_anchor_files[domain] = []
            trust_anchor_files[domain].append(trust_anchor)
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        elif k == 'val-override-timestamp':
            override_timestamp_str = v.strip('"\'')
            override_timestamp = int(override_timestamp_str)
        elif k == 'val-override-date':
            override_date_str = v.strip('"\'')
            ovr_yr = override_date_str[0:4]
            ovr_mnt = override_date_str[4:6]
            ovr_day = override_date_str[6:8]
            ovr_hr = override_date_str[8:10]
            ovr_min = override_date_str[10:12]
            ovr_sec = override_date_str[12:]
            override_date_str_arg = '{0} {1} {2} {3} {4} {5}'.format(
                ovr_yr, ovr_mnt, ovr_day, ovr_hr, ovr_min, ovr_sec)
            override_date = time.strptime(override_date_str_arg, "%Y %m %d %H %M %S")
            override_timestamp = calendar.timegm(override_date)
        elif k == 'stub-addr':
            stub_addr = v.strip('"\'')
        elif k == 'features':
            feature_list = v.split(feature_list_delimiter)
            try:
                for f_item in feature_list:
                    if f_item.find(feature_pair_delimiter) != -1:
                        f_key, f_value = [x.strip()
                                          for x
                                          in f_item.split(feature_pair_delimiter, 1)]
                    else:
                        f_key = f_item.strip()
                        f_value = ""
                    features[f_key] = f_value
810 811
            except KeyError as ex:
                raise KeyError("can't parse features (%s) in config section (%s)" % (v, str(ex)))
812 813 814 815 816 817 818
        elif k == 'feature-list':
            try:
                f_key, f_value = [x.strip() for x in v.split(feature_pair_delimiter, 1)]
                if f_key not in features:
                    features[f_key] = []
                f_value = f_value.replace("{{INSTALL_DIR}}", installdir)
                features[f_key].append(f_value)
819 820 821
            except KeyError as ex:
                raise KeyError("can't parse feature-list (%s) in config section (%s)"
                               % (v, str(ex)))
822 823
        elif k == 'force-ipv6' and v.upper() == 'TRUE':
            sockfamily = socket.AF_INET6
824 825
        else:
            raise NotImplementedError('unsupported CONFIG key "%s"' % k)
826 827 828

    ctx = {
        "DO_NOT_QUERY_LOCALHOST": str(do_not_query_localhost).lower(),
829
        "NEGATIVE_TRUST_ANCHORS": negative_ta_list,
830 831 832 833 834
        "FEATURES": features,
        "HARDEN_GLUE": str(harden_glue).lower(),
        "INSTALL_DIR": installdir,
        "QMIN": str(qmin).lower(),
        "TRUST_ANCHORS": trust_anchor_list,
835
        "TRUST_ANCHOR_FILES": trust_anchor_files.keys()
836 837 838 839 840 841 842 843 844 845 846 847 848
    }
    if stub_addr:
        ctx['ROOT_ADDR'] = stub_addr
        # determine and verify socket family for specified root address
        gai = socket.getaddrinfo(stub_addr, 53, sockfamily, 0,
                                 socket.IPPROTO_UDP, socket.AI_NUMERICHOST)
        assert len(gai) == 1
        sockfamily = gai[0][0]
    if not sockfamily:
        sockfamily = socket.AF_INET  # default to IPv4
    ctx['_SOCKET_FAMILY'] = sockfamily
    if override_timestamp:
        ctx['_OVERRIDE_TIMESTAMP'] = override_timestamp
849
    return (ctx, trust_anchor_files)
850 851


852
def parse_file(path):
853
    """ Parse scenario from a file. """
854

855 856
    aug = pydnstest.augwrap.AugeasWrapper(
        confpath=path, lens='Deckard', loadpath=os.path.dirname(__file__))
857
    node = aug.tree
858 859 860
    config = []
    for line in [c.value for c in node.match("/config/*")]:
        if line:
861 862 863 864 865
            if not line.startswith(';'):
                if '#' in line:
                    line = line[0:line.index('#')]
                # Break to key-value pairs
                # e.g.: ['minimization', 'on']
866
                kv = [x.strip() for x in line.split(':', 1)]
867 868
                if len(kv) >= 2:
                    config.append(kv)
Tomas Krizek's avatar
Tomas Krizek committed
869
    scenario = Scenario(node["/scenario"], os.path.basename(node.path))
870
    return scenario, config