fix DKIM record type
[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 as one more data points as 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 ## Record types
119 class A:
120     def __init__(self, address: str) -> None:
121         self._address = check_ipv4(address)
122     
123     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
124         return zone.RR(owner, 'A', self._address)
125
126
127 class AAAA:
128     def __init__(self, address: str) -> None:
129         self._address = check_ipv6(address)
130     
131     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
132         return zone.RR(owner, 'AAAA', self._address)
133
134
135 class MX:
136     def __init__(self, name: str, prio: int = 10) -> None:
137         self._priority = int(prio)
138         self._name = check_hostname(name)
139     
140     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
141         return zone.RR(owner, 'MX', '{0} {1}'.format(self._priority, zone.abs_hostname(self._name)))
142
143
144 class TXT:
145     def __init__(self, text: str) -> None:
146         # test for bad characters
147         for c in ('\n', '\r', '\t'):
148             if c in text:
149                 raise Exception("TXT record {0} contains invalid character")
150         # escape text
151         for c in ('\\', '\"'):
152             text = text.replace(c, '\\'+c)
153         self._text = text
154     
155     def generate_rr(self, owner:str, zone: 'Zone') -> 'Any':
156         return zone.RR(owner, 'TXT', '"{0}"'.format(self._text))
157
158
159 class DKIM(TXT): # helper class to treat DKIM more antively
160     class Version:
161         DKIM1 = "DKIM1"
162     
163     class Algorithm:
164         RSA = "rsa"
165     
166     def __init__(self, selector, version, alg, key):
167         self._selector = check_label(selector)
168         version = check_label(version)
169         alg = check_label(alg)
170         key = check_base64(key)
171         super().__init__("v={0}; k={1}; p={2}".format(version, alg, key))
172     
173     def generate_rr(self, owner, zone):
174         return super().generate_rr('{0}._domainkey.{1}'.format(self._selector, owner), zone)
175
176
177 class SRV:
178     def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
179         self._service = check_label(service)
180         self._protocol = check_label(protocol)
181         self._priority = int(prio)
182         self._weight = int(weight)
183         self._port = int(port)
184         self._name = check_hostname(name)
185     
186     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
187         return zone.RR('_{0}._{1}.{2}'.format(self._service, self._protocol, owner), 'SRV',
188                        '{0} {1} {2} {3}'.format(self._priority, self._weight, self._port, zone.abs_hostname(self._name)))
189
190
191 class TLSA:
192     class Usage:
193         CA = 0 # certificate must pass the usual CA check, with the CA specified by the TLSA record
194         EndEntity_PlusCAs = 1 # the certificate must match the TLSA record *and* pass the usual CA check
195         TrustAnchor = 2 # the certificate must pass a check with the TLSA record giving the (only) trust anchor
196         EndEntity = 3 # the certificate must match the TLSA record
197
198     class Selector:
199         Full = 0
200         SubjectPublicKeyInfo = 1
201     
202     class MatchingType:
203         Exact = 0
204         SHA256 = 1
205         SHA512 = 2
206     
207     def __init__(self, protocol: str, port: int, usage: int, selector: int, matching_type: int, data: str) -> None:
208         self._port = int(port)
209         self._protocol = str(protocol)
210         self._usage = int(usage)
211         self._selector = int(selector)
212         self._matching_type = int(matching_type)
213         self._data = check_hex(data)
214     
215     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
216         return zone.RR('_{0}._{1}.{2}'.format(self._port, self._protocol, owner), 'TLSA', '{0} {1} {2} {3}'.format(self._usage, self._selector, self._matching_type, self._data))
217
218
219 class CNAME:
220     def __init__(self, name: str) -> None:
221         self._name = check_hostname(name)
222     
223     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
224         return zone.RR(owner, 'CNAME', zone.abs_hostname(self._name))
225
226
227 class NS:
228     def __init__(self, name: str) -> None:
229         self._name = check_hostname(name)
230     
231     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
232         return zone.RR(owner, 'NS', zone.abs_hostname(self._name))
233
234
235 class DS:
236     def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
237         self._tag = int(tag)
238         self._key = check_hex(key)
239         self._alg = int(alg)
240         self._digest = int(digest)
241     
242     def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
243         return zone.RR(owner, 'DS', '{0} {1} {2} {3}'.format(self._tag, self._alg, self._digest, self._key))
244
245 ## Higher-level classes
246 class Name:
247     def __init__(self, *records: 'List[Any]') -> None:
248         self._records = records
249     
250     def generate_rrs(self, owner: str, zone: 'Zone') -> 'Iterator':
251         for record in self._records:
252             # this could still be a list
253             if isinstance(record, list):
254                 for subrecord in record:
255                     yield subrecord.generate_rr(owner, zone)
256             else:
257                 yield record.generate_rr(owner, zone)
258
259
260 def CName(name: str) -> Name:
261     return Name(CNAME(name))
262
263
264 def Delegation(name: str) -> Name:
265     return Name(NS(name))
266
267
268 def SecureDelegation(name: str, tag: int, alg: int, digest: int, key: str) -> Name:
269     return Name(NS(name), DS(tag, alg, digest, key))
270
271
272 class Zone:
273     def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]', TTLs: 'Dict[str, int]',
274                  secondary_refresh: int, secondary_retry: int, secondary_expire: int,
275                  domains: 'Dict[str, Any]') -> None:
276         if not name.endswith('.'): raise Exception("Expected an absolute hostname")
277         self._name = check_hostname(name)
278         self._serialfile = serialfile
279         
280         if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
281         atpos = mail.find('@')
282         if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
283         self._mail = check_hostname(mail.replace('@', '.', 1))
284         self._NS = list(map(check_hostname, NS))
285         if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
286         self._TTLs = TTLs
287         
288         self._refresh = secondary_refresh
289         self._retry = secondary_retry
290         self._expire = secondary_expire
291         
292         self._domains = domains
293     
294     def getTTL(self, recordType: str) -> str:
295         return self._TTLs.get(recordType, self._TTLs[''])
296     
297     def RR(self, owner: str, recordType: str, data: str) -> str:
298         '''generate given RR, in textual representation'''
299         assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
300         return column_widths((self.abs_hostname(owner), time(self.getTTL(recordType)), recordType, data), (32, 8, 8))
301     
302     def abs_hostname(self, name):
303         if name == '':
304             raise Exception("Empty domain name is not valid")
305         if name == '.' or name == '@':
306             return self._name
307         if name.endswith('.'):
308             return name
309         return name+"."+self._name
310     
311     def inc_serial(self) -> int:
312         # get serial
313         cur_serial = 0
314         try:
315             with open(self._serialfile) as f:
316                 cur_serial = int(f.read())
317         except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
318             pass
319         # increment serial
320         cur_serial += 1
321         # save serial
322         with open(self._serialfile, 'w') as f:
323             f.write(str(cur_serial))
324         # be done
325         return cur_serial
326     
327     def generate_rrs(self) -> 'Iterator':
328         # SOA record
329         serial = self.inc_serial()
330         yield self.RR(self._name, 'SOA',
331                       ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
332                       ' ; primns mail serial refresh retry expire NX_TTL').format(
333                           NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
334                           refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
335                           NX_TTL=time(self.getTTL('NX')))
336                       )
337         # NS records
338         for name in self._NS:
339             yield NS(name).generate_rr(self._name, self)
340         # all the rest
341         for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
342             for rr in self._domains[name].generate_rrs(name, self):
343                 yield rr
344     
345     def write(self) -> None:
346         print(";; {0} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {1}".format(self._name, datetime.datetime.now()))
347         for rr in self.generate_rrs():
348             print(rr)