1 # Copyright (c) 2014, Ralf Jung <post@ralfj.de>
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
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.
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.
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}$'
38 def check_label(label: str) -> str:
40 pattern = r'^{0}$'.format(REGEX_label)
41 if re.match(pattern, label):
43 raise Exception(label+" is not a valid label")
45 def check_hostname(name: str) -> str:
47 # check hostname for validity
48 pattern = r'^{0}(\.{0})*\.?$'.format(REGEX_label)
49 if re.match(pattern, name):
51 raise Exception(name+" is not a valid hostname")
53 def check_hex(data: str) -> str:
55 if re.match('^[a-fA-F0-9]+$', data):
57 raise Exception(data+" is not valid hex data")
59 def check_base64(data: str) -> str:
61 if re.match('^[a-zA-Z0-9+/=]+$', data):
63 raise Exception(data+" is not valid hex data")
66 def check_ipv4(address: str) -> str:
67 address = str(address)
68 if re.match(REGEX_ipv4, address):
70 raise Exception(address+" is not a valid IPv4 address")
72 def check_ipv6(address: str) -> str:
73 address = str(address)
74 if re.match(REGEX_ipv6, address):
76 raise Exception(address+" is not a valid IPv6 address")
78 def time(time: int) -> str:
81 elif time % week == 0:
82 return str(time//week)+"w"
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"
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"
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
99 if len(result) < width_sum: # add padding
100 result += (width_sum - len(result))*" "
102 return result+str(datas[-1])
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"
124 self.recordType = recordType
128 def mapPath(self, f):
129 '''Run the path through f. Returns self, for nicer chaining.'''
130 self.path = f(self.path)
133 def relativize(self, root):
134 def _relativize(path):
135 if path == '' or root == '':
136 raise Exception("Empty domain name is not valid")
139 if root == '@' or path.endswith('.'):
142 return self.mapPath(_relativize)
145 '''Run the current TTL and the recordType through f.'''
146 self.TTL = f(self.TTL, self.recordType)
150 return column_widths((self.path, time(self.TTL), self.recordType, self.data), (8*3, 8, 8))
154 def __init__(self, address: str) -> None:
155 self._address = check_ipv4(address)
157 def generate_rr(self):
158 return RR('@', 'A', self._address)
162 def __init__(self, address: str) -> None:
163 self._address = check_ipv6(address)
165 def generate_rr(self):
166 return RR('@', 'AAAA', self._address)
170 def __init__(self, name: str, prio: int = 10) -> None:
171 self._priority = int(prio)
172 self._name = check_hostname(name)
174 def generate_rr(self):
175 return RR('@', 'MX', '{0} {1}'.format(self._priority, self._name))
179 def __init__(self, text: str) -> None:
180 # test for bad characters
181 for c in ('\n', '\r', '\t'):
183 raise Exception("TXT record {0} contains invalid character")
185 for c in ('\\', '\"'):
186 text = text.replace(c, '\\'+c)
189 def generate_rr(self):
190 return RR('@', 'TXT', '"{0}"'.format(self._text))
193 class DKIM(TXT): # helper class to treat DKIM more antively
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))
207 def generate_rr(self):
208 return super().generate_rr().relativize('{}._domainkey'.format(self._selector))
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)
220 def generate_rr(self):
221 return RR('_{}._{}'.format(self._service, self._protocol), 'SRV',
222 '{} {} {} {}'.format(self._priority, self._weight, self._port, self._name))
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
234 SubjectPublicKeyInfo = 1
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)
249 def generate_rr(self):
250 return RR('_{}._{}'.format(self._port, self._protocol), 'TLSA', '{} {} {} {}'.format(self._usage, self._selector, self._matching_type, self._data))
254 def __init__(self, name: str) -> None:
255 self._name = check_hostname(name)
257 def generate_rr(self):
258 return RR('@', 'CNAME', self._name)
262 def __init__(self, name: str) -> None:
263 self._name = check_hostname(name)
265 def generate_rr(self):
266 return RR('@', 'NS', self._name)
270 def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
272 self._key = check_hex(key)
274 self._digest = int(digest)
276 def generate_rr(self):
277 return RR('@', 'DS', '{} {} {} {}'.format(self._tag, self._alg, self._digest, self._key))
279 ## Higher-level classes
281 def __init__(self, *records: 'List[Any]') -> None:
282 self._records = records
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()
291 yield record.generate_rr()
294 def CName(name: str) -> Name:
295 return Name(CNAME(name))
298 def Delegation(name: str) -> Name:
299 return Name(NS(name))
302 def SecureDelegation(name: str, tag: int, alg: int, digest: int, key: str) -> Name:
303 return Name(NS(name), DS(tag, alg, digest, key))
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
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")
322 self._refresh = secondary_refresh
323 self._retry = secondary_retry
324 self._expire = secondary_expire
326 self._domains = domains
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['']))
333 def inc_serial(self) -> int:
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
344 with open(self._serialfile, 'w') as f:
345 f.write(str(cur_serial))
349 def generate_rrs(self) -> 'Iterator':
351 serial = self.inc_serial()
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')))
360 for name in self._NS:
361 yield NS(name).generate_rr()
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)
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.mapTTL(self.getTTL), self.generate_rrs()):