11 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
12 REGEX_ipv4 = r'^\d{1,3}(\.\d{1,3}){3}$'
13 REGEX_ipv6 = r'^[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){7}$'
15 def check_label(label: str) -> str:
17 pattern = r'^{0}$'.format(REGEX_label)
18 if re.match(pattern, label):
20 raise Exception(label+" is not a valid label")
22 def check_hostname(name: str) -> str:
24 # check hostname for validity
25 pattern = r'^{0}(\.{0})*\.?$'.format(REGEX_label)
26 if re.match(pattern, name):
28 raise Exception(name+" is not a valid hostname")
30 def check_hex(data: str) -> str:
32 if re.match('^[a-fA-F0-9]+$', data):
34 raise Exception(data+" is not valid hex data")
36 def check_ipv4(address: str) -> str:
37 address = str(address)
38 if re.match(REGEX_ipv4, address):
40 raise Exception(address+" is not a valid IPv4 address")
42 def check_ipv6(address: str) -> str:
43 address = str(address)
44 if re.match(REGEX_ipv6, address):
46 raise Exception(address+" is not a valid IPv6 address")
48 def time(time: int) -> str:
51 elif time % week == 0:
52 return str(time//week)+"w"
54 return str(time//day)+"d"
55 elif time % hour == 0:
56 return str(time//hour)+"h"
57 elif time % minute == 0:
58 return str(time//minute)+"m"
62 def column_widths(datas: 'Sequence', widths: 'Sequence[int]'):
63 assert len(datas) == len(widths)+1, "There must be as one more data points as widths"
66 for data, width in zip(datas, widths): # will *not* cover the last point
67 result += str(data)+" " # add data point, and a minimal space
69 if len(result) < width_sum: # add padding
70 result += (width_sum - len(result))*" "
72 return result+str(datas[-1])
90 def __init__(self, address: str) -> None:
91 self._address = check_ipv4(address)
93 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
94 return zone.RR(owner, 'A', self._address)
98 def __init__(self, address: str) -> None:
99 self._address = check_ipv6(address)
101 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
102 return zone.RR(owner, 'AAAA', self._address)
106 def __init__(self, name: str, prio: int = 10) -> None:
107 self._priority = int(prio)
108 self._name = check_hostname(name)
110 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
111 return zone.RR(owner, 'MX', '{0} {1}'.format(self._priority, zone.abs_hostname(self._name)))
115 def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
116 self._service = check_label(service)
117 self._protocol = check_label(protocol)
118 self._priority = int(prio)
119 self._weight = int(weight)
120 self._port = int(port)
121 self._name = check_hostname(name)
123 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
124 return zone.RR('_{0}._{1}.{2}'.format(self._service, self._protocol, owner), 'SRV',
125 '{0} {1} {2} {3}'.format(self._priority, self._weight, self._port, zone.abs_hostname(self._name)))
130 CA = 0 # certificate must pass the usual CA check, with the CA specified by the TLSA record
131 EndEntity_PlusCAs = 1 # the certificate must match the TLSA record *and* pass the usual CA check
132 TrustAnchor = 2 # the certificate must pass a check with the TLSA record giving the (only) trust anchor
133 EndEntity = 3 # the certificate must match the TLSA record
137 SubjectPublicKeyInfo = 1
144 def __init__(self, protocol: str, port: int, usage: int, selector: int, matching_type: int, data: str) -> None:
145 self._port = int(port)
146 self._protocol = str(protocol)
147 self._usage = int(usage)
148 self._selector = int(selector)
149 self._matching_type = int(matching_type)
150 self._data = check_hex(data)
152 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
153 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))
157 def __init__(self, name: str) -> None:
158 self._name = check_hostname(name)
160 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
161 return zone.RR(owner, 'CNAME', zone.abs_hostname(self._name))
165 def __init__(self, name: str) -> None:
166 self._name = check_hostname(name)
168 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
169 return zone.RR(owner, 'NS', zone.abs_hostname(self._name))
173 def __init__(self, tag: int, alg: int, digest: int, key: str) -> None:
175 self._key = check_hex(key)
177 self._digest = int(digest)
179 def generate_rr(self, owner: str, zone: 'Zone') -> 'Any':
180 return zone.RR(owner, 'DS', '{0} {1} {2} {3}'.format(self._tag, self._alg, self._digest, self._key))
182 ## Higher-level classes
184 def __init__(self, *records: 'List[Any]') -> None:
185 self._records = records
187 def generate_rrs(self, owner: str, zone: 'Zone') -> 'Iterator':
188 for record in self._records:
189 # this could still be a list
190 if isinstance(record, list):
191 for subrecord in record:
192 yield subrecord.generate_rr(owner, zone)
194 yield record.generate_rr(owner, zone)
197 def CName(name: str) -> Name:
198 return Name(CNAME(name))
201 def Delegation(name: str) -> Name:
202 return Name(NS(name))
205 def SecureDelegation(name: str, tag: int, alg: int, digest: int, key: str) -> Name:
206 return Name(NS(name), DS(tag, alg, digest, key))
210 def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]',
211 secondary_refresh: int, secondary_retry: int, secondary_expire: int,
212 NX_TTL: int = None, A_TTL: int = None, other_TTL: int = None,
213 domains: 'Dict[str, Any]' = {}) -> None:
214 self._serialfile = serialfile
216 if not name.endswith('.'): raise Exception("Expected an absolute hostname")
217 self._name = check_hostname(name)
218 if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
219 atpos = mail.find('@')
220 if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
221 self._mail = check_hostname(mail.replace('@', '.', 1))
222 self._NS = list(map(check_hostname, NS))
224 self._refresh = secondary_refresh
225 self._retry = secondary_retry
226 self._expire = secondary_expire
228 if other_TTL is None: raise Exception("Must give other_TTL")
229 self._NX_TTL = NX_TTL
230 self._A_TTL = self._AAAA_TTL = A_TTL
231 self._other_TTL = other_TTL
233 self._domains = domains
235 def RR(self, owner: str, recordType: str, data: str) -> str:
236 '''generate given RR, in textual representation'''
237 assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
239 attrname = "_"+recordType+"_TTL"
240 TTL = None # type: int
241 if hasattr(self, attrname):
242 TTL = getattr(self, attrname)
244 TTL = self._other_TTL
246 return column_widths((self.abs_hostname(owner), time(TTL), recordType, data), (32, 8, 8))
248 def abs_hostname(self, name):
249 if name == '.' or name == '@':
251 if name.endswith('.'):
253 return name+"."+self._name
255 def inc_serial(self) -> int:
259 with open(self._serialfile) as f:
260 cur_serial = int(f.read())
261 except OSError: # FileNotFoundError has been added in Python 3.3
266 with open(self._serialfile, 'w') as f:
267 f.write(str(cur_serial))
271 def generate_rrs(self) -> 'Iterator':
273 serial = self.inc_serial()
274 yield self.RR(self._name, 'SOA',
275 ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
276 ' ; primns mail serial refresh retry expire NX_TTL').format(
277 NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
278 refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
279 NX_TTL=time(self._NX_TTL))
282 for name in self._NS:
283 yield NS(name).generate_rr(self._name, self)
285 for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
286 for rr in self._domains[name].generate_rrs(name, self):
289 def write(self) -> None:
290 print(";; {0} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {1}".format(self._name, datetime.datetime.now()))
291 for rr in self.generate_rrs():