add support for generating TLSA records directly from a certificate file
[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, os, subprocess, re
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}){1,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 def concatenate(root, path):
105     if path == '' or root == '':
106         raise Exception("Empty domain name is not valid")
107     if path == '@':
108         return root
109     if root == '@' or path.endswith('.'):
110         return path
111     return path+"."+root
112
113 def escape_TXT(text):
114     for c in ('\\', '\"'):
115         text = text.replace(c, '\\'+c)
116     return text
117
118
119 ## Enums
120 class Protocol:
121     TCP = 'tcp'
122     UDP = 'udp'
123
124 class Algorithm:
125     RSA_SHA256 = 8
126
127 class Digest:
128     SHA1 = 1
129     SHA256 = 2
130
131
132 ## Resource records
133 class RR:
134     def __init__(self, path, recordType, data):
135         '''<path> can be relative or absolute.'''
136         assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
137         self.path = path
138         self.recordType = recordType
139         self.data = data
140         self.TTL = None
141     
142     def mapPath(self, f):
143         '''Run the path through f. Returns self, for nicer chaining.'''
144         self.path = f(self.path)
145         return self
146     
147     def relativize(self, root):
148         return self.mapPath(lambda path: concatenate(root, path))
149     
150     def mapTTL(self, f):
151         '''Run the current TTL and the recordType through f.'''
152         self.TTL = f(self.TTL, self.recordType)
153         return self
154     
155     def __str__(self):
156         return column_widths((self.path, time(self.TTL), self.recordType, self.data), (8*3, 8, 8))
157
158 ## Record types
159 class A:
160     def __init__(self, address: str) -> None:
161         self._address = check_ipv4(address)
162     
163     def generate_rr(self):
164         return RR('@', 'A', self._address)
165
166
167 class AAAA:
168     def __init__(self, address: str) -> None:
169         self._address = check_ipv6(address)
170     
171     def generate_rr(self):
172         return RR('@', 'AAAA', self._address)
173
174
175 class MX:
176     def __init__(self, name: str, prio: int = 10) -> None:
177         self._priority = int(prio)
178         self._name = check_hostname(name)
179     
180     def generate_rr(self):
181         return RR('@', 'MX', '{0} {1}'.format(self._priority, self._name))
182
183
184 class TXT:
185     def __init__(self, text: str) -> None:
186         # test for bad characters
187         for c in ('\n', '\r', '\t'):
188             if c in text:
189                 raise Exception("TXT record {0} contains invalid character")
190         self._text = text
191     
192     def generate_rr(self):
193         text = escape_TXT(self._text)
194         # split into chunks of max. 255 characters; be careful not to split right after a backslash
195         chunks = re.findall(r'.{0,254}[^\\]', text)
196         assert sum(len(c) for c in chunks) == len (text)
197         chunksep = '"\n' + ' '*20 + '"'
198         chunked = '( "' + chunksep.join(chunks) + '" )'
199         # generate the chunks
200         return RR('@', 'TXT', chunked)
201
202
203 class DKIM(TXT): # helper class to treat DKIM more antively
204     class Version:
205         DKIM1 = "DKIM1"
206     
207     class Algorithm:
208         RSA = "rsa"
209     
210     def __init__(self, selector, version, alg, key):
211         self._selector = check_label(selector)
212         version = check_label(version)
213         alg = check_label(alg)
214         key = check_base64(key)
215         super().__init__("v={0}; k={1}; p={2}".format(version, alg, key))
216     
217     def generate_rr(self):
218         return super().generate_rr().relativize('{}._domainkey'.format(self._selector))
219
220
221 class SRV:
222     def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
223         self._service = check_label(service)
224         self._protocol = check_label(protocol)
225         self._priority = int(prio)
226         self._weight = int(weight)
227         self._port = int(port)
228         self._name = check_hostname(name)
229     
230     def generate_rr(self):
231         return RR('_{}._{}'.format(self._service, self._protocol), 'SRV',
232                        '{} {} {} {}'.format(self._priority, self._weight, self._port, self._name))
233
234
235 class TLSA:
236     class Usage:
237         CA = 0 # certificate must pass the usual CA check, with the CA specified by the TLSA record
238         EndEntity_PlusCAs = 1 # the certificate must match the TLSA record *and* pass the usual CA check
239         TrustAnchor = 2 # the certificate must pass a check with the TLSA record giving the (only) trust anchor
240         EndEntity = 3 # the certificate must match the TLSA record
241
242     class Selector:
243         Full = 0
244         SubjectPublicKeyInfo = 1
245     
246     class MatchingType:
247         Exact = 0
248         SHA256 = 1
249         SHA512 = 2
250     
251     def __init__(self, protocol: str, port: int, usage: int, selector: int, matching_type: int, data: str) -> None:
252         self._port = int(port)
253         self._protocol = str(protocol)
254         self._usage = int(usage)
255         self._selector = int(selector)
256         self._matching_type = int(matching_type)
257         self._data = check_hex(data)
258
259     def from_crt(protocol: str, port: int, crtfile: str):
260         '''Generate a TLSA record from a given certificate file.'''
261         open(crtfile).close() # check if the file exists (and throw python-style exceptions if it dos not)
262         # Call the shell script to do the actual work
263         dir = os.path.dirname(os.path.realpath(__file__))
264         cmd = [dir+"/tlsa", crtfile]
265         #print(" ".join(cmd), file=sys.stderr)
266         zone_line = subprocess.check_output(cmd).decode("utf-8").strip().split("\n")[-1]
267         m = re.match("^([0-9]+) ([0-9]+) ([0-9]+) ([0-9a-zA-Z]+)$", zone_line)
268         assert m is not None
269         # make sure we match on *the key only*, so that we can renew the certificate without harm
270         assert int(m.group(1)) == TLSA.Usage.EndEntity
271         assert int(m.group(2)) == TLSA.Selector.SubjectPublicKeyInfo
272         return TLSA(protocol, port, TLSA.Usage.EndEntity, TLSA.Selector.SubjectPublicKeyInfo, int(m.group(3)), m.group(4))
273     
274     def generate_rr(self):
275         return RR('_{}._{}'.format(self._port, self._protocol), 'TLSA', '{} {} {} {}'.format(self._usage, self._selector, self._matching_type, self._data))
276
277 class CAA:
278     class Tag:
279         Issue = "issue"
280         IssueWild = "issuewild"
281
282     def __init__(self, flag: int, tag: str, value: str) -> None:
283         self._flag = int(flag)
284         self._tag = str(tag)
285         self._value = str(value)
286
287     def generate_rr(self):
288         return RR('@', 'CAA', '{} {} {}'.format(self._flag, self._tag, self._value))
289
290
291 class CNAME:
292     def __init__(self, name: str) -> None:
293         self._name = check_hostname(name)
294     
295     def generate_rr(self):
296         return RR('@', 'CNAME', self._name)
297
298
299 class NS:
300     def __init__(self, name: str) -> None:
301         self._name = check_hostname(name)
302     
303     def generate_rr(self):
304         return RR('@', 'NS', self._name)
305
306
307 class DS:
308     def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
309         self._tag = int(tag)
310         self._key = check_hex(key)
311         self._alg = int(alg)
312         self._digest = int(digest)
313     
314     def generate_rr(self):
315         return RR('@', 'DS', '{} {} {} {}'.format(self._tag, self._alg, self._digest, self._key))
316
317 ## Higher-level classes
318 class Name:
319     def __init__(self, *records: 'List[Any]') -> None:
320         self._records = records
321     
322     def generate_rrs(self):
323         for record in self._records:
324             # this could still be a list
325             if isinstance(record, list):
326                 for subrecord in record:
327                     yield subrecord.generate_rr()
328             else:
329                 yield record.generate_rr()
330
331
332 def CName(name: str) -> Name:
333     return Name(CNAME(name))
334
335
336 def Delegation(*names) -> Name:
337     return Name(list(map(NS, names)))
338
339
340 def SecureDelegation(tag: int, alg: int, digest: int, key: str, *names) -> Name:
341     return Name(DS(tag, alg, digest, key), list(map(NS, names)))
342
343
344 class Zone:
345     def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]', TTLs: 'Dict[str, int]',
346                  secondary_refresh: int, secondary_retry: int, secondary_expire: int,
347                  domains: 'Dict[str, Any]') -> None:
348         if not name.endswith('.'): raise Exception("Expected an absolute hostname")
349         self._name = check_hostname(name)
350         self._serialfile = serialfile
351         
352         if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
353         atpos = mail.find('@')
354         if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
355         self._mail = check_hostname(mail.replace('@', '.', 1))
356         self._NS = list(map(check_hostname, NS))
357         if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
358         self._TTLs = TTLs
359         
360         self._refresh = secondary_refresh
361         self._retry = secondary_retry
362         self._expire = secondary_expire
363         
364         self._domains = domains
365     
366     def getTTL(self, TTL: int, recordType: str) -> int:
367         if TTL is not None: return TTL
368         # TTL is None, so get a global default
369         return int(self._TTLs.get(recordType, self._TTLs['']))
370     
371     def inc_serial(self) -> int:
372         # get serial
373         cur_serial = 0
374         try:
375             with open(self._serialfile) as f:
376                 cur_serial = int(f.read())
377         except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
378             pass
379         # increment serial
380         cur_serial += 1
381         # save serial
382         with open(self._serialfile, 'w') as f:
383             f.write(str(cur_serial))
384         # be done
385         return cur_serial
386     
387     @staticmethod
388     def generate_rrs_from_dict(root, domains):
389         for name in sorted(domains.keys(), key=lambda s: s.split('.')):
390             if name.endswith('.'):
391                 raise Exception("You are trying to add a record outside of your zone. This is not supported. Use '@' for the zone root.")
392             domain = domains[name]
393             name = concatenate(root, name)
394             if isinstance(domain, dict):
395                 for rr in Zone.generate_rrs_from_dict(name, domain):
396                     yield rr
397             else:
398                 for rr in domain.generate_rrs():
399                     yield rr.relativize(name)
400     
401     def generate_rrs(self) -> 'Iterator':
402         # SOA record
403         serial = self.inc_serial()
404         yield RR('@', 'SOA',
405                       ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
406                       ' ; primns mail serial refresh retry expire NX_TTL').format(
407                           NS=self._NS[0], mail=self._mail, serial=serial,
408                           refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
409                           NX_TTL=time(self.getTTL(None, 'NX')))
410                       )
411         # NS records
412         for name in self._NS:
413             yield NS(name).generate_rr()
414         # all the rest
415         for rr in Zone.generate_rrs_from_dict('@', self._domains):
416             yield rr
417     
418     def write(self) -> None:
419         print(";; {} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {}".format(self._name, datetime.datetime.now()))
420         print("$ORIGIN {}".format(self._name))
421         for rr in map(lambda rr: rr.mapTTL(self.getTTL), self.generate_rrs()):
422             print(rr)