ans.py 11.5 KB
Newer Older
Evan Hunt's avatar
Evan Hunt committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
############################################################################
# Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
############################################################################

############################################################################
# ans.py: See README.anspy for details.
############################################################################

from __future__ import print_function
import os
import sys
import signal
import socket
import select
from datetime import datetime, timedelta
20
import functools
Evan Hunt's avatar
Evan Hunt committed
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

import dns, dns.message, dns.query
from dns.rdatatype import *
from dns.rdataclass import *
from dns.rcode import *
from dns.name import *

############################################################################
# set up the RRs to be returned in the next answer
#
# the message contains up to two pipe-separated ('|') fields.
#
# the first field of the message is a comma-separated list
# of actions indicating what to put into the answer set
# (e.g., a dname, a cname, another cname, etc)
#
# supported actions:
# - cname (cname from the current name to a new one in the same domain)
# - dname (dname to a new domain, plus a synthesized cname)
# - xname ("external" cname, to a new name in a new domain)
#
# example: xname, dname, cname represents a CNAME to an external
# domain which is then answered by a DNAME and synthesized
# CNAME pointing to yet another domain, which is then answered
# by a CNAME within the same domain, and finally an answer
# to the query. each RR in the answer set has a corresponding
# RRSIG. these signatures are not valid, but will exercise the
# response parser.
#
# the second field is a comma-separated list of which RRs in the
# answer set to include in the answer, in which order. if prepended
# with 's', the number indicates which signature to include.
#
# examples: for the answer set "cname, cname, cname", an rr set
# '1, s1, 2, s2, 3, s3, 4, s4' indicates that all four RRs should
# be included in the answer, with siagntures, in the origninal
# order, while 4, s4, 3, s3, 2, s2, 1, s1' indicates the order
# should be reversed, 's3, s3, s3, s3' indicates that the third
# RRSIG should be repeated four times and everything else should
# be omitted, and so on.
#
# if there is no second field (i.e., no pipe symbol appears in
# the line) , the default is to send all answers and signatures.
# if a pipe symbol exists but the second field is empty, then
# nothing is sent at all.
############################################################################
actions = []
rrs = []
def ctl_channel(msg):
    global actions, rrs

    msg = msg.splitlines().pop(0)
    print ('received control message: %s' % msg)

75
    msg = msg.split(b'|')
Evan Hunt's avatar
Evan Hunt committed
76
77
78
    if len(msg) == 0:
        return

79
80
    actions = [x.strip() for x in msg[0].split(b',')]
    n = functools.reduce(lambda n, act: (n + (2 if act == b'dname' else 1)), [0] + actions)
Evan Hunt's avatar
Evan Hunt committed
81
82
83
84
85
86
87
88

    if len(msg) == 1:
        rrs = []
        for i in range(n):
            for b in [False, True]:
                rrs.append((i, b))
        return

89
    rlist = [x.strip() for x in msg[1].split(b',')]
Evan Hunt's avatar
Evan Hunt committed
90
91
    rrs = []
    for item in rlist:
92
        if item[0] == b's'[0]:
Evan Hunt's avatar
Evan Hunt committed
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
            i = int(item[1:].strip()) - 1
            if i > n:
                print ('invalid index %d' + (i + 1))
                continue
            rrs.append((int(item[1:]) - 1, True))
        else:
            i = int(item) - 1
            if i > n:
                print ('invalid index %d' % (i + 1))
                continue
            rrs.append((i, False))

############################################################################
# Respond to a DNS query.
############################################################################
def create_response(msg):
    m = dns.message.from_wire(msg)
    qname = m.question[0].name.to_text()
    labels = qname.lower().split('.')
    wantsigs = True if m.ednsflags & dns.flags.DO else False

    # get qtype
    rrtype = m.question[0].rdtype
    typename = dns.rdatatype.to_text(rrtype)

    # for 'www.example.com.'...
    # - name is 'www'
    # - domain is 'example.com.'
    # - sld is 'example'
    # - tld is 'com.'
    name = labels.pop(0)
    domain = '.'.join(labels)
    sld = labels.pop(0)
    tld = '.'.join(labels)

    print ('query: ' + qname + '/' + typename)
    print ('domain: ' + domain)

    # default answers, depending on QTYPE.
    # currently only A, AAAA, TXT and NS are supported.
    ttl = 86400
    additionalA = '10.53.0.4'
    additionalAAAA = 'fd92:7065:b8e:ffff::4'
    if typename == 'A':
        final = '10.53.0.4'
    elif typename == 'AAAA':
        final = 'fd92:7065:b8e:ffff::4'
    elif typename == 'TXT':
        final = 'Some\ text\ here'
    elif typename == 'NS':
        domain = qname
        final = ('ns1.%s' % domain)
    else:
        final = None

    # RRSIG rdata - won't validate but will exercise response parsing
    t = datetime.now()
    delta = timedelta(30)
    t1 = t - delta
    t2 = t + delta
    inception=t1.strftime('%Y%m%d000000')
    expiry=t2.strftime('%Y%m%d000000')
    sigdata='OCXH2De0yE4NMTl9UykvOsJ4IBGs/ZIpff2rpaVJrVG7jQfmj50otBAp A0Zo7dpBU4ofv0N/F2Ar6LznCncIojkWptEJIAKA5tHegf/jY39arEpO cevbGp6DKxFhlkLXNcw7k9o7DSw14OaRmgAjXdTFbrl4AiAa0zAttFko Tso='

    # construct answer set.
    answers = []
    sigs = []
    curdom = domain
    curname = name
    i = 0

    for action in actions:
165
        if name != 'test':
Evan Hunt's avatar
Evan Hunt committed
166
            continue
167
        if action == b'xname':
Evan Hunt's avatar
Evan Hunt committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
            owner = curname + '.' + curdom
            newname = 'cname%d' % i
            i += 1
            newdom = 'domain%d.%s' % (i, tld)
            i += 1
            target = newname + '.' + newdom
            print ('add external CNAME %s to %s' % (owner, target))
            answers.append(dns.rrset.from_text(owner, ttl, IN, CNAME, target))
            rrsig = 'CNAME 5 3 %d %s %s 12345 %s %s' % \
               (ttl, expiry, inception, domain, sigdata)
            print ('add external RRISG(CNAME) %s to %s' % (owner, target))
            sigs.append(dns.rrset.from_text(owner, ttl, IN, RRSIG, rrsig))
            curname = newname
            curdom = newdom
            continue

184
        if action == b'cname':
Evan Hunt's avatar
Evan Hunt committed
185
186
187
188
189
190
191
192
193
194
195
196
197
            owner = curname + '.' + curdom
            newname = 'cname%d' % i
            target = newname + '.' + curdom
            i += 1
            print ('add CNAME %s to %s' % (owner, target))
            answers.append(dns.rrset.from_text(owner, ttl, IN, CNAME, target))
            rrsig = 'CNAME 5 3 %d %s %s 12345 %s %s' % \
                   (ttl, expiry, inception, domain, sigdata)
            print ('add RRSIG(CNAME) %s to %s' % (owner, target))
            sigs.append(dns.rrset.from_text(owner, ttl, IN, RRSIG, rrsig))
            curname = newname
            continue

198
        if action == b'dname':
Evan Hunt's avatar
Evan Hunt committed
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
            owner = curdom
            newdom = 'domain%d.%s' % (i, tld)
            i += 1
            print ('add DNAME %s to %s' % (owner, newdom))
            answers.append(dns.rrset.from_text(owner, ttl, IN, DNAME, newdom))
            rrsig = 'DNAME 5 3 %d %s %s 12345 %s %s' % \
                   (ttl, expiry, inception, domain, sigdata)
            print ('add RRSIG(DNAME) %s to %s' % (owner, newdom))
            sigs.append(dns.rrset.from_text(owner, ttl, IN, RRSIG, rrsig))
            owner = curname + '.' + curdom
            target = curname + '.' + newdom
            print ('add synthesized CNAME %s to %s' % (owner, target))
            answers.append(dns.rrset.from_text(owner, ttl, IN, CNAME, target))
            rrsig = 'CNAME 5 3 %d %s %s 12345 %s %s' % \
                   (ttl, expiry, inception, domain, sigdata)
            print ('add synthesized RRSIG(CNAME) %s to %s' % (owner, target))
            sigs.append(dns.rrset.from_text(owner, ttl, IN, RRSIG, rrsig))
            curdom = newdom
            continue

    # now add the final answer
    owner = curname + '.' + curdom
    answers.append(dns.rrset.from_text(owner, ttl, IN, rrtype, final))
    rrsig = '%s 5 3 %d %s %s 12345 %s %s' % \
               (typename, ttl, expiry, inception, domain, sigdata)
    sigs.append(dns.rrset.from_text(owner, ttl, IN, RRSIG, rrsig))

    # prepare the response and convert to wire format
    r = dns.message.make_response(m)

229
    if name != 'test':
Evan Hunt's avatar
Evan Hunt committed
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
        r.answer.append(answers[-1])
        if wantsigs:
            r.answer.append(sigs[-1])
    else:
        for (i, sig) in rrs:
            if sig and not wantsigs:
                continue
            elif sig:
                r.answer.append(sigs[i])
            else:
                r.answer.append(answers[i])

    if typename != 'NS':
        r.authority.append(dns.rrset.from_text(domain, ttl, IN, "NS",
                                               ("ns1.%s" % domain)))
    r.additional.append(dns.rrset.from_text(('ns1.%s' % domain), 86400,
                                             IN, A, additionalA))
    r.additional.append(dns.rrset.from_text(('ns1.%s' % domain), 86400,
                                             IN, AAAA, additionalAAAA))

    r.flags |= dns.flags.AA
    r.use_edns()
    return r.to_wire()

def sigterm(signum, frame):
    print ("Shutting down now...")
    os.remove('ans.pid')
257
    running = False
258
    sys.exit(0)
Evan Hunt's avatar
Evan Hunt committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272

############################################################################
# Main
#
# Set up responder and control channel, open the pid file, and start
# the main loop, listening for queries on the query channel or commands
# on the control channel and acting on them.
############################################################################
ip4 = "10.53.0.4"
ip6 = "fd92:7065:b8e:ffff::4"
sock = 5300

query4_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
query4_socket.bind((ip4, sock))
273
274
275
276
277
278
279
280
281
282
283

havev6 = True
try:
    query6_socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    try:
        query6_socket.bind((ip6, sock))
    except:
        query6_socket.close()
        havev6 = False
except:
    havev6 = False
Evan Hunt's avatar
Evan Hunt committed
284
285
286
287
288
289
290
291
292
293
294
295

ctrl_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ctrl_socket.bind((ip4, sock + 1))
ctrl_socket.listen(5)

signal.signal(signal.SIGTERM, sigterm)

f = open('ans.pid', 'w')
pid = os.getpid()
print (pid, file=f)
f.close()

296
running = True
Evan Hunt's avatar
Evan Hunt committed
297
298

print ("Listening on %s port %d" % (ip4, sock))
299
300
if havev6:
    print ("Listening on %s port %d" % (ip6, sock))
Evan Hunt's avatar
Evan Hunt committed
301
302
303
print ("Control channel on %s port %d" % (ip4, sock + 1))
print ("Ctrl-c to quit")

304
305
306
307
if havev6:
    input = [query4_socket, query6_socket, ctrl_socket]
else:
    input = [query4_socket, ctrl_socket]
Evan Hunt's avatar
Evan Hunt committed
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

while running:
    try:
        inputready, outputready, exceptready = select.select(input, [], [])
    except select.error as e:
        break
    except socket.error as e:
        break
    except KeyboardInterrupt:
        break

    for s in inputready:
        if s == ctrl_socket:
            # Handle control channel input
            conn, addr = s.accept()
            print ("Control channel connected")
            while True:
                msg = conn.recv(65535)
                if not msg:
                    break
                ctl_channel(msg)
            conn.close()
        if s == query4_socket or s == query6_socket:
            print ("Query received on %s" %
                    (ip4 if s == query4_socket else ip6))
            # Handle incoming queries
            msg = s.recvfrom(65535)
            rsp = create_response(msg[0])
            if rsp:
                s.sendto(rsp, msg[1])
    if not running:
        break