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}){1,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])
104 def concatenate(root, path):
105 if path == '' or root == '':
106 raise Exception("Empty domain name is not valid")
109 if root == '@' or path.endswith('.'):
129 def __init__(self, path, recordType, data):
130 '''<path> can be relative or absolute.'''
131 assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
133 self.recordType = recordType
137 def mapPath(self, f):
138 '''Run the path through f. Returns self, for nicer chaining.'''
139 self.path = f(self.path)
142 def relativize(self, root):
143 return self.mapPath(lambda path: concatenate(root, path))
146 '''Run the current TTL and the recordType through f.'''
147 self.TTL = f(self.TTL, self.recordType)
151 return column_widths((self.path, time(self.TTL), self.recordType, self.data), (8*3, 8, 8))
155 def __init__(self, address: str) -> None:
156 self._address = check_ipv4(address)
158 def generate_rr(self):
159 return RR('@', 'A', self._address)
163 def __init__(self, address: str) -> None:
164 self._address = check_ipv6(address)
166 def generate_rr(self):
167 return RR('@', 'AAAA', self._address)
171 def __init__(self, name: str, prio: int = 10) -> None:
172 self._priority = int(prio)
173 self._name = check_hostname(name)
175 def generate_rr(self):
176 return RR('@', 'MX', '{0} {1}'.format(self._priority, self._name))
180 def __init__(self, text: str) -> None:
181 # test for bad characters
182 for c in ('\n', '\r', '\t'):
184 raise Exception("TXT record {0} contains invalid character")
186 for c in ('\\', '\"'):
187 text = text.replace(c, '\\'+c)
190 def generate_rr(self):
191 return RR('@', 'TXT', '"{0}"'.format(self._text))
194 class DKIM(TXT): # helper class to treat DKIM more antively
201 def __init__(self, selector, version, alg, key):
202 self._selector = check_label(selector)
203 version = check_label(version)
204 alg = check_label(alg)
205 key = check_base64(key)
206 super().__init__("v={0}; k={1}; p={2}".format(version, alg, key))
208 def generate_rr(self):
209 return super().generate_rr().relativize('{}._domainkey'.format(self._selector))
213 def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
214 self._service = check_label(service)
215 self._protocol = check_label(protocol)
216 self._priority = int(prio)
217 self._weight = int(weight)
218 self._port = int(port)
219 self._name = check_hostname(name)
221 def generate_rr(self):
222 return RR('_{}._{}'.format(self._service, self._protocol), 'SRV',
223 '{} {} {} {}'.format(self._priority, self._weight, self._port, self._name))
228 CA = 0 # certificate must pass the usual CA check, with the CA specified by the TLSA record
229 EndEntity_PlusCAs = 1 # the certificate must match the TLSA record *and* pass the usual CA check
230 TrustAnchor = 2 # the certificate must pass a check with the TLSA record giving the (only) trust anchor
231 EndEntity = 3 # the certificate must match the TLSA record
235 SubjectPublicKeyInfo = 1
242 def __init__(self, protocol: str, port: int, usage: int, selector: int, matching_type: int, data: str) -> None:
243 self._port = int(port)
244 self._protocol = str(protocol)
245 self._usage = int(usage)
246 self._selector = int(selector)
247 self._matching_type = int(matching_type)
248 self._data = check_hex(data)
250 def generate_rr(self):
251 return RR('_{}._{}'.format(self._port, self._protocol), 'TLSA', '{} {} {} {}'.format(self._usage, self._selector, self._matching_type, self._data))
255 def __init__(self, name: str) -> None:
256 self._name = check_hostname(name)
258 def generate_rr(self):
259 return RR('@', 'CNAME', self._name)
263 def __init__(self, name: str) -> None:
264 self._name = check_hostname(name)
266 def generate_rr(self):
267 return RR('@', 'NS', self._name)
271 def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
273 self._key = check_hex(key)
275 self._digest = int(digest)
277 def generate_rr(self):
278 return RR('@', 'DS', '{} {} {} {}'.format(self._tag, self._alg, self._digest, self._key))
280 ## Higher-level classes
282 def __init__(self, *records: 'List[Any]') -> None:
283 self._records = records
285 def generate_rrs(self):
286 for record in self._records:
287 # this could still be a list
288 if isinstance(record, list):
289 for subrecord in record:
290 yield subrecord.generate_rr()
292 yield record.generate_rr()
295 def CName(name: str) -> Name:
296 return Name(CNAME(name))
299 def Delegation(*names) -> Name:
300 return Name(list(map(NS, names)))
303 def SecureDelegation(tag: int, alg: int, digest: int, key: str, *names) -> Name:
304 return Name(DS(tag, alg, digest, key), list(map(NS, names)))
308 def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]', TTLs: 'Dict[str, int]',
309 secondary_refresh: int, secondary_retry: int, secondary_expire: int,
310 domains: 'Dict[str, Any]') -> None:
311 if not name.endswith('.'): raise Exception("Expected an absolute hostname")
312 self._name = check_hostname(name)
313 self._serialfile = serialfile
315 if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
316 atpos = mail.find('@')
317 if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
318 self._mail = check_hostname(mail.replace('@', '.', 1))
319 self._NS = list(map(check_hostname, NS))
320 if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
323 self._refresh = secondary_refresh
324 self._retry = secondary_retry
325 self._expire = secondary_expire
327 self._domains = domains
329 def getTTL(self, TTL: int, recordType: str) -> int:
330 if TTL is not None: return TTL
331 # TTL is None, so get a global default
332 return int(self._TTLs.get(recordType, self._TTLs['']))
334 def inc_serial(self) -> int:
338 with open(self._serialfile) as f:
339 cur_serial = int(f.read())
340 except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
345 with open(self._serialfile, 'w') as f:
346 f.write(str(cur_serial))
351 def generate_rrs_from_dict(root, domains):
352 for name in sorted(domains.keys(), key=lambda s: s.split('.')):
353 if name.endswith('.'):
354 raise Exception("You are trying to add a record outside of your zone. This is not supported. Use '@' for the zone root.")
355 domain = domains[name]
356 name = concatenate(root, name)
357 if isinstance(domain, dict):
358 for rr in Zone.generate_rrs_from_dict(name, domain):
361 for rr in domain.generate_rrs():
362 yield rr.relativize(name)
364 def generate_rrs(self) -> 'Iterator':
366 serial = self.inc_serial()
368 ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
369 ' ; primns mail serial refresh retry expire NX_TTL').format(
370 NS=self._NS[0], mail=self._mail, serial=serial,
371 refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
372 NX_TTL=time(self.getTTL(None, 'NX')))
375 for name in self._NS:
376 yield NS(name).generate_rr()
378 for rr in Zone.generate_rrs_from_dict('@', self._domains):
381 def write(self) -> None:
382 print(";; {} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {}".format(self._name, datetime.datetime.now()))
383 print("$ORIGIN {}".format(self._name))
384 for rr in map(lambda rr: rr.mapTTL(self.getTTL), self.generate_rrs()):