-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig.py
313 lines (271 loc) · 11.5 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import os.path
import warnings
import pwd
import grp
from twisted.names import dns
from IPy import IP
class ConfigurationError(Exception):
pass
class MissingSectionError(ConfigurationError):
pass
class InstanceRedifinitionError(ConfigurationError):
pass
class ConfigurationWarning(UserWarning):
pass
class UnusedOptionWarning(ConfigurationWarning):
pass
class OptionRedifinitionWarning(ConfigurationWarning):
pass
def extract_status_file_path(config_path):
""" Extracts the path to the openvpn status file from a openvpn config.
:raises EnvironmentError: if the config does not contain a status file
entry
:return: the absolute path to the status file"""
import re
status_search = re.compile(r'^\s*(?P<option>(status|server|server-ipv6))'
r'\s+(?P<value>[^#]+)(#.*)?$')
status_file = None
subnet4 = None
subnet6 = None
with open(config_path, 'r') as conf_file:
for conf_line in conf_file:
match = status_search.match(conf_line)
if not match:
continue
if match.group('option') == 'status':
status_file = os.path.abspath(os.path.join(config_path, '..',
match.group('value').strip()))
elif match.group('option') == 'server':
subnet4 = match.group('value').strip()
elif match.group('option') == 'server-ipv6':
subnet6 = match.group('value').strip()
if not status_file:
raise EnvironmentError('You must specify a status entry!')
return (status_file, subnet4, subnet6)
class SetSingleValueMixin:
def set_single_option(self, name, value, convert=None):
old_value = getattr(self, name, object())
if old_value is not None:
warnings.warn('Overwrite old {0} option value ({1})'
.format(name, old_value), OptionRedifinitionWarning,
stacklevel=2)
if convert is not None:
try:
value = convert(value)
except Exception as e:
raise ConfigurationError(e)
setattr(self, name, value)
class OpenVpnInstance(SetSingleValueMixin):
def __init__(self, name):
self.name = name
self.status_file = None
self.notify = []
self.rname = None
self.mname = None
self.refresh = None
self.retry = None
self.expire = None
self.minimum = None
self.forward_records = []
self.backward4_records = []
self.backward6_records = []
self.suffix = None
self.subnet4 = None
self.subnet6 = None
self.version = 0
class ConfigParser(SetSingleValueMixin):
""" Parser and data storage for configuration information.
The file format uses the INI syntax but with multiple use of option
names per section therefore the config module is not usable.
:param str filename: file path to configuration file"""
def __init__(self, filename=None):
self.listen_addresses = []
self.daemon = None
self.drop = None
self.user = None
self.group = None
self.log = None
self.pidfile = None
self.reactor = None
self.instances = {}
if filename:
self.read_file(filename)
@staticmethod
def read_data(filename):
""" Reads the given file name. It assumes that the file has a INI file
syntax. The parser returns the data without comments and fill
characters. It supports multiple option with the same name per
section but not multiple sections with the same name.
:param str filename: path to INI file
:return: a dictionary - the key is the section name value, the
option is a array of (option name, option value) tuples"""
sections = {}
with open(filename) as f:
section = None
options = None
for line in f:
# ignore comments:
if line.startswith('#'):
continue
line = line.strip()
if not line:
continue
# handle section header:
if line.startswith('[') and line.endswith(']'):
if section: # save old section data
sections[section] = options
section = line[1:-1]
options = []
continue
if section is None:
warnings.warn('Option without sections: {0}'.format(line),
UnusedOptionWarning, stacklevel=2)
continue
option, value = line.split('=', 1)
options.append((option.strip(), value.strip()))
if section: # save old section data
sections[section] = options
return sections
def read_file(self, file_name):
""" Read and parse the configuration file"""
self.parse_data(self.read_data(file_name))
@staticmethod
def parse_boolean(value):
if value.lower() in ['true', 't', 'yes', 'y', '1']:
return True
if value.lower() in ['false', 'f', 'no', 'n', '0']:
return False
raise ValueError(f'Could not parse boolean value: "{value!r}"')
@staticmethod
def parse_filename(value):
if not os.path.isfile(value):
raise ValueError('Could not found config file {0}'.format(value))
return value
@staticmethod
def parse_userid(value):
try:
return int(value)
except ValueError:
pass
try:
return pwd.getpwnam(value)[2]
except KeyError:
raise ValueError('Unknown user name or id: {0}'.format(value))
@staticmethod
def parse_groupid(value):
try:
return int(value)
except ValueError:
pass
try:
return grp.getgrnam(value)[2]
except KeyError:
raise ValueError('Unknown group name or id: {0}'.format(value))
@staticmethod
def parse_net(value):
return IP(value.replace(' ', '/')).reverseName()[:-1]
def parse_data(self, data):
""" Parse configuration data
:param dict data: data extracted from :meth:`read_data`
:raises ConfigurationError: missing information"""
# store data for other methods:
self.data = data
# handle main options:
if 'options' not in data:
raise MissingSectionError('Missing options section')
for option, value in data['options']:
if option == 'listen':
self.add_listen_address(value)
elif option == 'instance':
self.parse_instance(value)
elif option == 'reactor':
self.set_single_option('reactor', value)
elif option == 'log':
self.set_single_option('log', value)
elif option == 'daemon':
self.set_single_option('daemon', value, self.parse_boolean)
elif option == 'drop-privileges':
self.set_single_option('drop', value, self.parse_boolean)
elif option == 'user':
self.set_single_option('user', value, self.parse_userid)
elif option == 'group':
self.set_single_option('group', value, self.parse_groupid)
elif option == 'pidfile':
self.set_single_option('pidfile', value, self.parse_boolean)
else:
warnings.warn('Unknown option {0} in options section'
.format(option), UnusedOptionWarning,
stacklevel=2)
def add_listen_address(self, listen):
""" Add a listen information
:param str listen: listen information (name, ip, port)"""
address, port = listen.split(':', 1)
self.listen_addresses.append((address, int(port)))
def parse_instance(self, name):
""" register one openvpn status instance
:param str name: name for this instance (used as zone name)"""
if name in self.instances:
raise InstanceRedifinitionError('Instance {0} already defined'
.format(name))
instance = OpenVpnInstance(name)
if name not in self.data:
raise MissingSectionError('section for instance {0}'.format(name))
for option, value in self.data[name]:
# openvpn server information:
if option == 'server_config':
status, subnet4, subnet6 = extract_status_file_path(value)
instance.set_single_option('status_file', status)
if subnet4:
instance.set_single_option('subnet4', subnet4, self.parse_net)
if subnet6:
instance.set_single_option('subnet6', subnet6, self.parse_net)
elif option == 'status_file':
instance.set_single_option('status_file', os.path.abspath(value))
elif option == 'subnet4':
instance.set_single_option('subnet4', value, self.parse_net)
elif option == 'subnet6':
instance.set_single_option('subnet6', value, self.parse_net)
# slave name server notifies:
elif option == 'notify':
instance.notify.append((value, 53))
elif option == 'suffix':
instance.suffix = value
# SOA entries:
elif option in ('rname', 'mname', 'refresh', 'retry', 'expire',
'minimum'):
if option == 'rname':
value = value.replace('@', '.', 1)
if getattr(instance, option) is not None:
warnings.warn('Overwrite SOA value {0}'.format(option),
OptionRedifinitionWarning, stacklevel=2)
setattr(instance, option, value)
# additional entries:
elif option in ['add_entries',
'add_forward_entries', 'add_backward_entries',
'add_backward4_entries', 'add_backward6_entries']:
if value not in self.data:
raise MissingSectionError('Referencing unknown section {0}'
.format(value))
records = self.parse_entry_section(self.data[value])
type = option[4:-8]
if type in ('', 'forward'):
instance.forward_records += records
if type in ('', 'backward', 'backward4'):
instance.backward4_records += records
if type in ('', 'backward', 'backward6'):
instance.backward6_records += records
else:
warnings.warn('Unknown option {0} in section {1}'.format(option,
name), UnusedOptionWarning, stacklevel=2)
self.instances[name] = instance
return instance
@staticmethod
def parse_entry_section(options, name=None):
records = []
for entry, value in options:
parts = value.split(' ')
record = getattr(dns, 'Record_%s' % parts[0], None)
if not record:
raise NotImplementedError("Record type %r not supported" % parts[0])
records.append((entry, record(*[s.encode('utf-8') for s in parts[1:]])))
return records