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]', TTLs: 'Dict[str, int]',
211 secondary_refresh: int, secondary_retry: int, secondary_expire: int,
212 domains: 'Dict[str, Any]') -> None:
213 if not name.endswith('.'): raise Exception("Expected an absolute hostname")
214 self._name = check_hostname(name)
215 self._serialfile = serialfile
217 if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
218 atpos = mail.find('@')
219 if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
220 self._mail = check_hostname(mail.replace('@', '.', 1))
221 self._NS = list(map(check_hostname, NS))
222 if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
225 self._refresh = secondary_refresh
226 self._retry = secondary_retry
227 self._expire = secondary_expire
229 self._domains = domains
231 def getTTL(self, recordType: str) -> str:
232 return self._TTLs.get(recordType, self._TTLs[''])
234 def RR(self, owner: str, recordType: str, data: str) -> str:
235 '''generate given RR, in textual representation'''
236 assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
237 return column_widths((self.abs_hostname(owner), time(self.getTTL(recordType)), recordType, data), (32, 8, 8))
239 def abs_hostname(self, name):
240 if name == '.' or name == '@':
242 if name.endswith('.'):
244 return name+"."+self._name
246 def inc_serial(self) -> int:
250 with open(self._serialfile) as f:
251 cur_serial = int(f.read())
252 except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
257 with open(self._serialfile, 'w') as f:
258 f.write(str(cur_serial))
262 def generate_rrs(self) -> 'Iterator':
264 serial = self.inc_serial()
265 yield self.RR(self._name, 'SOA',
266 ('{NS} {mail} {serial} {refresh} {retry} {expire} {NX_TTL}'+
267 ' ; primns mail serial refresh retry expire NX_TTL').format(
268 NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
269 refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
270 NX_TTL=time(self.getTTL('NX')))
273 for name in self._NS:
274 yield NS(name).generate_rr(self._name, self)
276 for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
277 for rr in self._domains[name].generate_rrs(name, self):
280 def write(self) -> None:
281 print(";; {0} zone file, generated by zonemaker <https://www.ralfj.de/projects/zonemaker> on {1}".format(self._name, datetime.datetime.now()))
282 for rr in self.generate_rrs():