more systematic (and sane) approach to handling relative paths
[zonemaker.git] / zone.py
1 # Copyright (c) 2014, Ralf Jung <post@ralfj.de>
2 # All rights reserved.
3
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6
7 # 1. Redistributions of source code must retain the above copyright notice, this
8 #    list of conditions and the following disclaimer. 
9 # 2. Redistributions in binary form must reproduce the above copyright notice,
10 #    this list of conditions and the following disclaimer in the documentation
11 #    and/or other materials provided with the distribution.
12
13 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23
24 import re, datetime
25 #from typing import *
26
27
28 second = 1
29 minute = 60*second
30 hour = 60*minute
31 day = 24*hour
32 week = 7*day
33
34 REGEX_label = r'[a-zA-Z90-9]([a-zA-Z90-9-]{0,61}[a-zA-Z90-9])?' # max. 63 characters; must not start or end with hyphen
35 REGEX_ipv4  = r'^\d{1,3}(\.\d{1,3}){3}$'
36 REGEX_ipv6  = r'^[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){7}$'
37
38 def check_label(label: str) -> str:
39     label = str(label)
40     pattern = r'^{0}$'.format(REGEX_label)
41     if re.match(pattern, label):
42         return label
43     raise Exception(label+" is not a valid label")
44
45 def check_hostname(name: str) -> str:
46     name = str(name)
47     # check hostname for validity
48     pattern = r'^{0}(\.{0})*\.?$'.format(REGEX_label)
49     if re.match(pattern, name):
50         return name
51     raise Exception(name+" is not a valid hostname")
52
53 def check_hex(data: str) -> str:
54     data = str(data)
55     if re.match('^[a-fA-F0-9]+$', data):
56         return data
57     raise Exception(data+" is not valid hex data")
58
59 def check_base64(data: str) -> str:
60     data = str(data)
61     if re.match('^[a-zA-Z0-9+/=]+$', data):
62         return data
63     raise Exception(data+" is not valid hex data")
64
65
66 def check_ipv4(address: str) -> str:
67     address = str(address)
68     if re.match(REGEX_ipv4, address):
69         return address
70     raise Exception(address+" is not a valid IPv4 address")
71
72 def check_ipv6(address: str) -> str:
73     address = str(address)
74     if re.match(REGEX_ipv6, address):
75         return address
76     raise Exception(address+" is not a valid IPv6 address")
77
78 def time(time: int) -> str:
79     if time == 0:
80         return "0"
81     elif time % week == 0:
82         return str(time//week)+"w"
83     elif time % day == 0:
84         return str(time//day)+"d"
85     elif time % hour == 0:
86         return str(time//hour)+"h"
87     elif time % minute == 0:
88         return str(time//minute)+"m"
89     else:
90         return str(time)
91
92 def column_widths(datas: 'Sequence', widths: 'Sequence[int]'):
93     assert len(datas) == len(widths)+1, "There must be one more data points as there are widths"
94     result = ""
95     width_sum = 0
96     for data, width in zip(datas, widths): # will *not* cover the last point
97         result += str(data)+" " # add data point, and a minimal space
98         width_sum += width
99         if len(result) < width_sum: # add padding
100             result += (width_sum - len(result))*" "
101     # last data point
102     return result+str(datas[-1])
103
104
105 ## Enums
106 class Protocol:
107     TCP = 'tcp'
108     UDP = 'udp'
109
110 class Algorithm:
111     RSA_SHA256 = 8
112
113 class Digest:
114     SHA1 = 1
115     SHA256 = 2
116
117
118 ## Resource records
119 class RR:
120     def __init__(self, path, recordType, data):
121         '''<path> can be relative or absolute.'''
122         assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
123         self.path = path
124         self.recordType = recordType
125         self.data = data
126         self.TTL = None
127     
128     def mapPath(self, f):
129         '''Run the path through f. Returns self, for nicer chaining.'''
130         self.path = f(self.path)
131         return self
132     
133     def relativize(self, root):
134         def _relativize(path):
135             if path == '' or root == '':
136                 raise Exception("Empty domain name is not valid")
137             if path == '@':
138                 return root
139             if root == '@' or path.endswith('.'):
140                 return path
141             return path+"."+root
142         return self.mapPath(_relativize)
143     
144     def mapTTL(self, f):
145         '''Run the current TTL and the recordType through f.'''
146         self.TTL = f(self.TTL, self.recordType)
147         return self
148     
149     def __str__(self):
150         return column_widths((self.path, time(self.TTL), self.recordType, self.data), (32, 8, 8))
151
152 ## Record types
153 class A:
154     def __init__(self, address: str) -> None:
155         self._address = check_ipv4(address)
156     
157     def generate_rr(self):
158         return RR('@', 'A', self._address)
159
160
161 class AAAA:
162     def __init__(self, address: str) -> None:
163         self._address = check_ipv6(address)
164     
165     def generate_rr(self):
166         return RR('@', 'AAAA', self._address)
167
168
169 class MX:
170     def __init__(self, name: str, prio: int = 10) -> None:
171         self._priority = int(prio)
172         self._name = check_hostname(name)
173     
174     def generate_rr(self):
175         return RR('@', 'MX', '{0} {1}'.format(self._priority, self._name))
176
177
178 class TXT:
179     def __init__(self, text: str) -> None:
180         # test for bad characters
181         for c in ('\n', '\r', '\t'):
182             if c in text:
183                 raise Exception("TXT record {0} contains invalid character")
184         # escape text
185         for c in ('\\', '\"'):
186             text = text.replace(c, '\\'+c)
187         self._text = text
188     
189     def generate_rr(self):
190         return RR('@', 'TXT', '"{0}"'.format(self._text))
191
192
193 class DKIM(TXT): # helper class to treat DKIM more antively
194     class Version:
195         DKIM1 = "DKIM1"
196     
197     class Algorithm:
198         RSA = "rsa"
199     
200     def __init__(self, selector, version, alg, key):
201         self._selector = check_label(selector)
202         version = check_label(version)
203         alg = check_label(alg)
204         key = check_base64(key)
205         super().__init__("v={0}; k={1}; p={2}".format(version, alg, key))
206     
207     def generate_rr(self):
208         return super().generate_rr().relativize('{}._domainkey'.format(self._selector))
209
210
211 class SRV:
212     def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
213         self._service = check_label(service)
214         self._protocol = check_label(protocol)
215         self._priority = int(prio)
216         self._weight = int(weight)
217         self._port = int(port)
218         self._name = check_hostname(name)
219     
220     def generate_rr(self):
221         return RR('_{}._{}'.format(self._service, self._protocol), 'SRV',
222                        '{} {} {} {}'.format(self._priority, self._weight, self._port, self._name))
223
224
225 class TLSA:
226     class Usage:
227         CA = 0 # certificate must pass the usual CA check, with the CA specified by the TLSA record
228         EndEntity_PlusCAs = 1 # the certificate must match the TLSA record *and* pass the usual CA check
229         TrustAnchor = 2 # the certificate must pass a check with the TLSA record giving the (only) trust anchor
230         EndEntity = 3 # the certificate must match the TLSA record
231
232     class Selector:
233         Full = 0
234         SubjectPublicKeyInfo = 1
235     
236     class MatchingType:
237         Exact = 0
238         SHA256 = 1
239         SHA512 = 2
240     
241     def __init__(self, protocol: str, port: int, usage: int, selector: int, matching_type: int, data: str) -> None:
242         self._port = int(port)
243         self._protocol = str(protocol)
244         self._usage = int(usage)
245         self._selector = int(selector)
246         self._matching_type = int(matching_type)
247         self._data = check_hex(data)
248     
249     def generate_rr(self):
250         return RR('_{}._{}'.format(self._port, self._protocol), 'TLSA', '{} {} {} {}'.format(self._usage, self._selector, self._matching_type, self._data))
251
252
253 class CNAME:
254     def __init__(self, name: str) -> None:
255         self._name = check_hostname(name)
256     
257     def generate_rr(self):
258         return RR('@', 'CNAME', self._name)
259
260
261 class NS:
262     def __init__(self, name: str) -> None:
263         self._name = check_hostname(name)
264     
265     def generate_rr(self):
266         return RR('@', 'NS', self._name)
267
268
269 class DS:
270     def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
271         self._tag = int(tag)
272         self._key = check_hex(key)
273         self._alg = int(alg)
274         self._digest = int(digest)
275     
276     def generate_rr(self):
277         return RR('@', 'DS', '{} {} {} {}'.format(self._tag, self._alg, self._digest, self._key))
278
279 ## Higher-level classes
280 class Name:
281     def __init__(self, *records: 'List[Any]') -> None:
282         self._records = records
283     
284     def generate_rrs(self):
285         for record in self._records:
286             # this could still be a list
287             if isinstance(record, list):
288                 for subrecord in record:
289                     yield subrecord.generate_rr()
290             else:
291                 yield record.generate_rr()
292
293
294 def CName(name: str) -> Name:
295     return Name(CNAME(name))
296
297
298 def Delegation(name: str) -> Name:
299     return Name(NS(name))
300
301
302 def SecureDelegation(name: str, tag: int, alg: int, digest: int, key: str) -> Name:
303     return Name(NS(name), DS(tag, alg, digest, key))
304
305
306 class Zone:
307     def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]', TTLs: 'Dict[str, int]',
308                  secondary_refresh: int, secondary_retry: int, secondary_expire: int,
309                  domains: 'Dict[str, Any]') -> None:
310         if not name.endswith('.'): raise Exception("Expected an absolute hostname")
311         self._name = check_hostname(name)
312         self._serialfile = serialfile
313         
314         if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
315         atpos = mail.find('@')
316         if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
317         self._mail = check_hostname(mail.replace('@', '.', 1))
318         self._NS = list(map(check_hostname, NS))
319         if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
320         self._TTLs = TTLs
321         
322         self._refresh = secondary_refresh
323         self._retry = secondary_retry
324         self._expire = secondary_expire
325         
326         self._domains = domains
327     
328     def getTTL(self, TTL: int, recordType: str) -> int:
329         if TTL is not None: return TTL
330         # TTL is None, so get a global default
331         return int(self._TTLs.get(recordType, self._TTLs['']))
332     
333     def inc_serial(self) -> int:
334         # get serial
335         cur_serial = 0
336         try:
337             with open(self._serialfile) as f:
338                 cur_serial = int(f.read())
339         except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
340             pass
341         # increment serial
342         cur_serial += 1
343         # save serial
344         with open(self._serialfile, 'w') as f:
345             f.write(str(cur_serial))
346         # be done
347         return cur_serial
348     
349     def generate_rrs(self) -> 'Iterator':
350         # SOA record
351         serial = self.inc_serial()
352         yield RR('@', 'SOA',
353                       ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
354                       ' ; primns mail serial refresh retry expire NX_TTL').format(
355                           NS=self._NS[0], mail=self._mail, serial=serial,
356                           refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
357                           NX_TTL=time(self.getTTL(None, 'NX')))
358                       )
359         # NS records
360         for name in self._NS:
361             yield NS(name).generate_rr()
362         # all the rest
363         for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
364             if name.endswith('.'):
365                 raise Exception("You are trying to add a record outside of your zone. This is not supported. Use '@' for the zone root.")
366             for rr in self._domains[name].generate_rrs():
367                 yield rr.relativize(name)
368     
369     def write(self) -> None:
370         print(";; {} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {}".format(self._name, datetime.datetime.now()))
371         print("$ORIGIN {}".format(self._name))
372         for rr in map(lambda rr: rr.relativize(self._name).mapTTL(self.getTTL), self.generate_rrs()):
373             print(rr)