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