Git Repository Public Repository

nip.io

URLs

Copy to Clipboard
 
ff3961375c8c1439937adc41e60c0697f8b07677
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/python

import ConfigParser
import os
import re
import sys


def _is_debug():
    return False


def _log(msg):
    sys.stderr.write('backend (%s): %s\n' % (os.getpid(), msg))


def _write(*l):
    args = len(l)
    c = 0
    for a in l:
        c += 1
        if _is_debug():
            _log('writing: %s' % a)
        sys.stdout.write(a)
        if c < args:
            if _is_debug():
                _log('writetab')
            sys.stdout.write('\t')
    if _is_debug():
        _log('writenewline')
    sys.stdout.write('\n')
    sys.stdout.flush()


def _get_next():
    if _is_debug():
        _log('reading now')
    line = sys.stdin.readline()
    if _is_debug():
        _log('read line: %s' % line)
    return line.strip().split('\t')


class DynamicBackend:
    def __init__(self):
        self.id = ''
        self.soa = ''
        self.domain = ''
        self.ip_address = ''
        self.ttl = ''
        self.name_servers = {}
        self.blacklisted_ips = []

    def configure(self):
        fname = self._get_config_filename()
        if not os.path.exists(fname):
            _log('%s does not exist' % fname)
            sys.exit(1)

        with open(fname) as fp:
            config = ConfigParser.ConfigParser()
            config.readfp(fp)

        self.id = config.get('soa', 'id')
        self.soa = '%s %s %s' % (config.get('soa', 'ns'), config.get('soa', 'hostmaster'), self.id)
        self.domain = config.get('main', 'domain')
        self.ip_address = config.get('main', 'ipaddress')
        self.ttl = config.get('main', 'ttl')

        for entry in config.items('nameservers'):
            self.name_servers[entry[0]] = entry[1]

        if config.has_section("blacklist"):
            for entry in config.items("blacklist"):
                self.blacklisted_ips.append(entry[1])

        _log('Name servers: %s' % self.name_servers)
        _log('ID: %s' % self.id)
        _log('TTL %s' % self.ttl)
        _log('SOA: %s' % self.soa)
        _log('IP Address: %s' % self.ip_address)
        _log('DOMAIN: %s' % self.domain)
        _log("Blacklist: %s" % self.blacklisted_ips)

    def run(self):
        _log('starting up')
        handshake = _get_next()
        if handshake[1] != '1':
            _log('Not version 1: %s' % handshake)
            sys.exit(1)
        _write('OK', 'We are good')
        _log('Done handshake')

        while True:
            cmd = _get_next()
            if _is_debug():
                _log("cmd: %s" % cmd)

            if cmd[0] == "END":
                _log("completing")
                break

            if len(cmd) < 6:
                _log('did not understand: %s' % cmd)
                _write('FAIL')
                continue

            qname = cmd[1].lower()
            qtype = cmd[3]

            if (qtype == 'A' or qtype == 'ANY') and qname.endswith(self.domain):
                if qname == self.domain:
                    self.handle_self(self.domain)
                elif qname in self.name_servers:
                    self.handle_nameservers(qname)
                else:
                    self.handle_subdomains(qname)
            elif qtype == 'SOA' and qname.endswith(self.domain):
                self.handle_soa(qname)
            else:
                self.handle_unknown(qtype, qname)

    def handle_self(self, name):
        _write('DATA', name, 'IN', 'A', self.ttl, self.id, self.ip_address)
        self.write_name_servers(name)
        _write('END')

    def handle_subdomains(self, qname):
        subdomain = qname[0:qname.find(self.domain) - 1]

        subparts = subdomain.split('.')
        if len(subparts) < 4:
            if _is_debug():
                _log('subparts less than 4')
            self.handle_self(qname)
            return

        ip_address_parts = subparts[-4:]
        if _is_debug():
            _log('ip: %s' % ip_address_parts)
        for part in ip_address_parts:
            if re.match('^\d{1,3}$', part) is None:
                if _is_debug():
                    _log('%s is not a number' % part)
                self.handle_self(qname)
                return
            parti = int(part)
            if parti < 0 or parti > 255:
                if _is_debug():
                    _log('%d is too big/small' % parti)
                self.handle_self(qname)
                return

        ip_address = ".".join(ip_address_parts)
        if ip_address in self.blacklisted_ips:
            self.handle_blacklisted(ip_address)
            return

        _write('DATA', qname, 'IN', 'A', self.ttl, self.id, '%s.%s.%s.%s' % (ip_address_parts[0], ip_address_parts[1], ip_address_parts[2], ip_address_parts[3]))
        self.write_name_servers(qname)
        _write('END')

    def handle_nameservers(self, qname):
        ip = self.name_servers[qname]
        _write('DATA', qname, 'IN', 'A', self.ttl, self.id, ip)
        _write('END')

    def write_name_servers(self, qname):
        for nameServer in self.name_servers:
            _write('DATA', qname, 'IN', 'NS', self.ttl, self.id, nameServer)

    def handle_soa(self, qname):
        _write('DATA', qname, 'IN', 'SOA', self.ttl, self.id, self.soa)
        _write('END')

    def handle_unknown(self, qtype, qname):
        _write('LOG', 'Unknown type: %s, domain: %s' % (qtype, qname))
        _write('END')

    def handle_blacklisted(self, ip_address):
        _write('LOG', 'Blacklisted: %s' % ip_address)
        _write('END')

    def _get_config_filename(self):
        return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'backend.conf')


if __name__ == '__main__':
    backend = DynamicBackend()
    backend.configure()
    backend.run()

Commits for nip.ionipio/backend.py

Diff revisions: vs.
Revision Author Commited Message
ff3961 ... rs picture rs Fri 08 Feb, 2019 07:09:51 +0000

Add tests and support for blacklisting IPs