-
Notifications
You must be signed in to change notification settings - Fork 832
/
config.py
364 lines (309 loc) · 12 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import os
import pwd
import stat
import yaml
import logging
from jadi import interface, component, service
import aj
from aj.util import public
class BaseConfig():
"""
A base class for config implementations. Your implementation must be able to save
arbitrary mixture of ``dict``, ``list``, and scalar values.
.. py:attribute:: data
currently loaded config content
"""
def __init__(self):
self.data = None
def load(self):
"""
Should load config content into :attr:`data`.
"""
raise NotImplementedError()
def save(self):
"""
Should save config content from :attr:`data`.
"""
raise NotImplementedError()
def ensure_structure(self):
# Global options
self.data.setdefault('name', None)
self.data.setdefault('trusted_domains', [])
self.data.setdefault('trusted_proxies', [])
self.data.setdefault('max_sessions', 99)
self.data.setdefault('session_max_time', 3600)
self.data.setdefault('language', 'en')
self.data.setdefault('restricted_user', 'nobody')
self.data.setdefault('logo', os.path.dirname(__file__) + '/static/images/Logo.png')
# Main view
self.data.setdefault('view', {})
self.data['view'].setdefault('plugin', 'core')
self.data['view'].setdefault('filepath', 'content/pages/index.html')
# Authentication
self.data.setdefault('auth', {})
self.data['auth'].setdefault('emails', {})
self.data['auth'].setdefault('provider', 'os')
self.data['auth'].setdefault('users_file', '/etc/ajenti/users.yml')
# SSL
self.data.setdefault('ssl', {})
self.data['ssl'].setdefault('enable', False)
self.data['ssl'].setdefault('certificate', None)
self.data['ssl'].setdefault('fqdn_certificate', None)
self.data['ssl'].setdefault('force', False)
self.data['ssl'].setdefault('client_auth', {})
self.data['ssl']['client_auth'].setdefault('enable', False)
self.data['ssl']['client_auth'].setdefault('force', False)
self.data['ssl']['client_auth'].setdefault('certificates', [])
if self.data['ssl']['client_auth']['certificates'] is None:
self.data['ssl']['client_auth']['certificates'] = []
# Emails
self.data.setdefault('email', {})
self.data['email'].setdefault('enable', False)
self.data['email'].setdefault('templates', {})
# Before Ajenti 2.1.38, the users were stored in config.yml
if 'users' in self.data['auth'].keys():
logging.warning(f"Users should be stored in {self.data['auth']['users_file']}, migrating it ...")
self.migrate_users_to_own_configfile()
def migrate_users_to_own_configfile(self):
users_path = self.data['auth']['users_file']
if os.path.isfile(users_path):
logging.info(f"{users_path} already existing, backing it up")
os.rename(users_path, users_path + '.bak')
to_write = {'users': self.data['auth']['users']}
with open(users_path, 'w') as f:
f.write(yaml.safe_dump(to_write, default_flow_style=False, encoding='utf-8', allow_unicode=True).decode('utf-8'))
del self.data['auth']['users']
self.save()
logging.info(f"{users_path} correctly written")
def get_non_sensitive_data(self):
return {
'color': self.data['color'],
'language': self.data['language'],
'name': self.data['name'],
'session_max_time': self.data['session_max_time'],
}
class SmtpConfig(BaseConfig):
"""
Class to handle the smtp config file in order to store credentials of the email
server relay.
Config file is located at /etc/ajenti/smtp.yml and should have the following
structure :
smtp:
port: starttls or ssl
server: myserver.domain.com
user: user to authenticate
password: password of the mail user
"""
def __init__(self):
BaseConfig.__init__(self)
self.data = {}
self.path = '/etc/ajenti/smtp.yml'
def ensure_structure(self):
self.data.setdefault('smtp', {})
self.data['smtp'].setdefault('password', None)
self.data['smtp'].setdefault('port', None)
self.data['smtp'].setdefault('server', None)
self.data['smtp'].setdefault('user', None)
def get_smtp_password(self):
# if smtp.yml is not provided
if self.data['smtp']['password'] is None:
return ''
with open(self.path, 'r') as smtp:
smtp_config = yaml.load(smtp, Loader=yaml.SafeLoader).get('smtp', {})
return smtp_config.get('password', None)
def load(self):
if not os.path.exists(self.path):
logging.error(f'Smtp credentials file "{self.path}" not found')
else:
if os.geteuid() == 0:
os.chmod(self.path, 384) # 0o600
with open(self.path, 'r') as smtp:
self.data = yaml.load(smtp, Loader=yaml.SafeLoader) or {}
# Prevent password leak
self.ensure_structure()
self.data['smtp']['password'] = ''
def save(self, data):
# Prevent emptying password from settings plugin
if not data['smtp']['password']:
data['smtp']['password'] = self.get_smtp_password()
with open(self.path, 'w') as smtp:
smtp.write(
yaml.safe_dump(
data,
default_flow_style=False,
encoding='utf-8',
allow_unicode=True
).decode('utf-8')
)
class TFAConfig(BaseConfig):
"""
Class to handle the TFA yaml file which contains secrets for e.g. TOTP
Config file is located at /etc/ajenti/tfa.yml and should have the following
structure :
totp:
user@auth_id:
secret_id:
created: DATE
description: DESCRIPTION
secret: random key in base32 with 32 chars
"""
def __init__(self):
BaseConfig.__init__(self)
self.data = {}
self.path = '/etc/ajenti/tfa.yml'
self.verify_totp = {}
def ensure_structure(self):
self.data.setdefault('users', {})
def get_user_totp_secrets(self, userid):
with open(self.path, 'r') as tfa:
tfa_config = yaml.load(tfa, Loader=yaml.SafeLoader).get('users', {})
user_secrets = tfa_config.get(userid, {}).get('totp', [])
return [details['secret'] for details in user_secrets]
def append_user_totp(self, data):
config = self._read()
userid = data['userid']
if config['users'].get(userid, {}).get('totp', []):
config['users'][userid]['totp'].append(data['secret_details'])
self.verify_totp[userid] = None
else:
config['users'][userid] = {'totp': [data['secret_details']]}
self._save(config)
self.load()
def delete_user_totp(self, data):
config = self._read()
userid = data['userid']
totps = config['users'].get(userid, {}).get('totp', [])
for secret in totps:
if str(secret['created']) == data['timestamp']:
if len(totps) == 1:
# Remove completely user entry
del config['users'][userid]
else:
config['users'][userid]['totp'].remove(secret)
break
self._save(config)
self.load()
def _read(self):
if os.path.exists(self.path):
with open(self.path, 'r') as tfa:
return yaml.load(tfa, Loader=yaml.SafeLoader)
else:
return {'users': {}}
def load(self):
if os.path.exists(self.path):
os.chmod(self.path, 384) # 0o600
with open(self.path, 'r') as tfa:
self.data = yaml.load(tfa, Loader=yaml.SafeLoader).get('users', {})
# Don't keep secrets in memory and prepare verify values per user involved
for userid, tfa_methods in self.data.items():
self.verify_totp[userid] = None
for tfa_method, values in tfa_methods.items():
for entry in values:
entry['secret'] = ''
else:
self.ensure_structure()
def _save(self, data):
with open(self.path, 'w') as tfa:
tfa.write(
yaml.safe_dump(
data,
default_flow_style=False,
encoding='utf-8',
allow_unicode=True
).decode('utf-8')
)
os.chmod(self.path, 384) # 0o600
class AjentiUsers(BaseConfig):
"""
Class to handle the users config file for the auth-user plugin.
Config file is located at /etc/ajenti/users.yml and should have the following
structure :
users:
username:
email: ...@...
password: hash
permissions: {}
uid: int
fs_root: file system root directory
"""
def __init__(self, path):
BaseConfig.__init__(self)
self.data = None
self.path = os.path.abspath(path)
def __str__(self):
return self.path
def load(self):
# Find default users file
if not self.path:
# Check for users file in /etc/ajenti/users.yml
if os.path.isfile('/etc/ajenti/users.yml'):
config_path = '/etc/ajenti/users.yml'
elif os.path.isfile(os.path.join(sys.path[0], 'users.yml')):
# Try local users file
config_path = os.path.join(sys.path[0], 'users.yml')
if not os.path.exists(self.path):
logging.error(f'Users file "{self.path}" not found')
self.data = {'users': {}}
else:
if os.geteuid() == 0:
os.chmod(self.path, 384) # 0o600
with open(self.path, 'r') as users:
self.data = yaml.load(users, Loader=yaml.SafeLoader)
if self.data['users'] is None:
self.data['users'] = {}
def save(self):
with open(self.path, 'w') as f:
f.write(yaml.safe_dump(self.data, default_flow_style=False, encoding='utf-8', allow_unicode=True).decode('utf-8'))
@interface
class UserConfigProvider():
id = None
name = None
def __init__(self, context):
self.data = None
def load(self):
raise NotImplementedError
def harden(self):
raise NotImplementedError
def save(self):
raise NotImplementedError
class UserConfigError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
@public
@service
class UserConfigService():
def __init__(self, context):
self.context = context
def get_provider(self):
provider_id = aj.config.data['auth'].get('provider', 'os')
for provider in UserConfigProvider.all(self.context):
if provider.id == provider_id:
return provider
raise UserConfigError(f'User config provider {provider_id} is unavailable')
@component(UserConfigProvider)
class UserConfig(UserConfigProvider):
id = 'os'
name = 'OS users'
def __init__(self, context):
UserConfigProvider.__init__(self, context)
username = pwd.getpwuid(os.getuid())[0]
_dir = os.path.expanduser(f'~{username}/.config')
if not os.path.exists(_dir):
os.makedirs(_dir)
self.path = os.path.join(_dir, 'ajenti.yml')
if os.path.exists(self.path):
self.load()
else:
self.data = {}
def load(self):
self.data = yaml.load(open(self.path), Loader=yaml.SafeLoader)
def harden(self):
os.chmod(self.path, stat.S_IRWXU)
def save(self):
with open(self.path, 'w') as f:
f.write(yaml.safe_dump(
self.data, default_flow_style=False, encoding='utf-8', allow_unicode=True
).decode('utf-8'))
self.harden()