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