forked from LinOTP/LinOTP
/
base.py
486 lines (377 loc) · 15.7 KB
/
base.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# -*- coding: utf-8 -*-
#
# LinOTP - the open source solution for two factor authentication
# Copyright (C) 2010 - 2016 LSE Leading Security Experts GmbH
#
# This file is part of LinOTP server.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License, version 3, as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the
# GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# E-mail: linotp@lsexperts.de
# Contact: www.linotp.org
# Support: www.lsexperts.de
#
'''The Controller's Base class '''
import os
import re
from pylons.i18n.translation import _ as translate
from pylons.i18n.translation import set_lang
from pylons.i18n import LanguageError
from pylons.controllers import WSGIController
from pylons import tmpl_context as c
from pylons import config
from pylons import request
from linotp.lib.config import initLinotpConfig
from linotp.lib.resolver import initResolvers
from linotp.lib.resolver import setupResolvers
from linotp.lib.resolver import closeResolvers
from linotp.lib.user import getUserFromRequest
from linotp.lib.user import getUserFromParam
from linotp.lib.realm import getDefaultRealm
from linotp.lib.realm import getRealms
from linotp.lib.config import getGlobalObject
from linotp.model import meta
from linotp.lib.openid import SQLStorage
# this is a hack for the static code analyser, which
# would otherwise show session.close() as error
import linotp.model
Session = linotp.model.Session
from linotp.lib.config import getLinotpConfig
from linotp.lib.policy import getPolicies
from linotp.lib.util import get_client
import logging
log = logging.getLogger(__name__)
Audit = config.get('audit')
# HTTP-ACCEPT-LANGUAGE strings are in the form of i.e.
# de-DE, de; q=0.7, en; q=0.3
accept_language_regexp = re.compile(r'\s*([^\s;,]+)\s*[;\s*q=[0-9.]*]?\s*,?')
def set_config(key, value, typ, description=None):
'''
create an intial config entry, if it does not exist
:param key: the key
:param value: the value
:param description: the description of the key
:return: nothing
'''
count = Session.query(linotp.model.Config).filter(
linotp.model.Config.Key == "linotp." + key).count()
if count == 0:
config_entry = linotp.model.Config(key, value,
Type=typ, Description=description)
Session.add(config_entry)
return
def set_defaults():
'''
add linotp default config settings
:return: - nothing -
'''
log.info("Adding config default data...")
set_config(key=u"DefaultMaxFailCount",
value=u"10", typ=u"int",
description=u"The default maximum count for unsuccessful logins")
set_config(key=u"DefaultCountWindow",
value=u"10", typ=u"int",
description=u"The default lookup window for tokens out of sync ")
set_config(key=u"DefaultSyncWindow",
value=u"1000", typ=u"int",
description=u"The default lookup window for tokens out of sync ")
set_config(key=u"DefaultChallengeValidityTime",
value=u"120", typ=u"int",
description=u"The default time, a challenge is regarded as valid.")
set_config(key=u"DefaultResetFailCount",
value=u"True", typ=u"bool",
description=u"The default maximum count for unsucessful logins")
set_config(key=u"DefaultOtpLen",
value=u"6", typ=u"int",
description=u"The default len of the otp values")
set_config(key=u"PrependPin",
value=u"True", typ=u"bool",
description=u"is the pin prepended - most cases")
set_config(key=u"FailCounterIncOnFalsePin",
value=u"True", typ=u"bool",
description=u"increment the FailCounter, if pin did not match")
set_config(key=u"SMSProvider",
value=u"smsprovider.HttpSMSProvider.HttpSMSProvider", typ=u"text",
description=u"SMS Default Provider via HTTP")
set_config(key=u"SMSProviderTimeout",
value=u"300", typ=u"int",
description=u"Timeout until registration must be done")
set_config(key=u"SMSBlockingTimeout",
value=u"30", typ=u"int",
description=u"Delay until next challenge is created")
set_config(key=u"DefaultBlockingTimeout",
value=u"0", typ=u"int",
description=u"Delay until next challenge is created")
# setup for totp defaults
# "linotp.totp.timeStep";"60";"None";"None"
# "linotp.totp.timeWindow";"600";"None";"None"
# "linotp.totp.timeShift";"240";"None";"None"
set_config(key=u"totp.timeStep",
value=u"30", typ=u"int",
description=u"Time stepping of the time based otp token ")
set_config(key=u"totp.timeWindow",
value=u"300", typ=u"int",
description=u"Lookahead time window of the time based otp token ")
set_config(key=u"totp.timeShift",
value=u"0", typ=u"int",
description=u"Shift between server and totp token")
set_config(key=u"AutoResyncTimeout",
value=u"240", typ=u"int",
description=u"Autosync timeout for an totp token")
# setup for ocra defaults
# OcraDefaultSuite
# QrOcraDefaultSuite
# OcraMaxChallenges
# OcraChallengeTimeout
set_config(key=u"OcraDefaultSuite",
value=u"OCRA-1:HOTP-SHA256-8:C-QN08", typ=u"string",
description=u"Default OCRA suite for an ocra token ")
set_config(key=u"QrOcraDefaultSuite",
value=u"OCRA-1:HOTP-SHA256-8:C-QA64", typ=u"int",
description=u"Default OCRA suite for an ocra qr token ")
set_config(key=u"OcraMaxChallenges",
value=u"4", typ=u"int",
description=u"Maximum open ocra challenges")
set_config(key=u"OcraChallengeTimeout",
value=u"300", typ=u"int",
description=u"Timeout for an open ocra challenge")
# emailtoken defaults
set_config(key=u"EmailProvider",
value="linotp.lib.emailprovider.SMTPEmailProvider",
typ=u"string",
description=u"Default EmailProvider class")
set_config(key=u"EmailChallengeValidityTime",
value="600", typ=u"int",
description=u"Time that an e-mail token challenge stays valid"
" (seconds)")
set_config(key=u"EmailBlockingTimeout",
value="120", typ=u"int",
description=u"Time during which no new e-mail is sent out")
def setup_app(conf, conf_global=None, unitTest=False):
'''
setup_app is the hook, which is called, when the application is created
:param conf: the application configuration
:return: - nothing -
'''
if conf_global is not None:
if conf_global.has_key("sqlalchemy.url"):
log.info("sqlalchemy.url")
else:
conf.get("sqlalchemy.url", None)
if unitTest is True:
log.info("Deleting previous tables...")
meta.metadata.drop_all(bind=meta.engine)
# Create the tables if they don't already exist
log.info("Creating tables...")
meta.metadata.create_all(bind=meta.engine)
if conf.has_key("linotpSecretFile"):
filename = conf.get("linotpSecretFile")
try:
with open(filename):
pass
except IOError:
log.warning("The Linotp Secret File could not be found " +
"-creating a new one: %s" % filename)
f_handle = open(filename, 'ab+')
secret = os.urandom(32 * 5)
f_handle.write(secret)
f_handle.close()
os.chmod(filename, 0400)
log.info("linotpSecretFile: %s" % filename)
set_defaults()
Session.commit()
log.info("Successfully set up.")
class BaseController(WSGIController):
"""
BaseController class - will be called with every request
"""
def __init__(self, *args, **kw):
"""
base controller constructor
:param *args: generic argument array
:param **kw: generic argument dict
:return: None
"""
self.sep = None
self.set_language(request.headers)
self.base_auth_user = ''
self.parent = super(WSGIController, self)
self.parent.__init__(*args, **kw)
# make the OpenID SQL Instance globally available
openid_sql = config.get('openid_sql', None)
if openid_sql is None:
try:
openid_storage = SQLStorage()
config['openid_sql'] = openid_storage
except Exception as exx:
config['openid_sql'] = exx
log.error("Failed to configure openid_sql: %r" % exx)
app_setup_done = config.get('app_setup_done', False)
if app_setup_done is False:
try:
setup_app(config)
config['app_setup_done'] = True
except Exception as exx:
config['app_setup_done'] = False
log.error("Failed to serve request: %r" % exx)
raise exx
# set the decryption device before loading linotp config,
# so it contains the decrypted values as well
glo = getGlobalObject()
self.sep = glo.security_provider
try:
hsm = self.sep.getSecurityModule()
self.hsm = hsm
c.hsm = hsm
except Exception as exx:
log.exception('failed to assign hsm device: %r' % exx)
raise exx
l_config = initLinotpConfig()
resolver_setup_done = config.get('resolver_setup_done', False)
if resolver_setup_done is False:
try:
cache_dir = config.get("app_conf", {}).get("cache_dir", None)
setupResolvers(config=l_config, cache_dir=cache_dir)
config['resolver_setup_done'] = True
except Exception as exx:
config['resolver_setup_done'] = False
log.error("Failed to setup resolver: %r" % exx)
raise exx
initResolvers()
return
def __call__(self, environ, start_response):
'''Invoke the Controller'''
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
path = ""
self.create_context(request)
try:
if environ:
path = environ.get("PATH_INFO", "") or ""
try:
user_desc = getUserFromRequest(request)
self.base_auth_user = user_desc.get('login', '')
except UnicodeDecodeError as exx:
# we supress Exception here as it will be handled in the
# controller which will return corresponding response
log.info('Failed to identify user due to %r' % exx)
log.debug("request %r" % path)
ret = WSGIController.__call__(self, environ, start_response)
log.debug("reply %r" % ret)
finally:
meta.Session.remove()
# free the lock on the scurityPovider if any
if self.sep:
self.sep.dropSecurityModule()
closeResolvers()
# hint for the garbage collector to make the dishes
data_objects = ["resolvers_loaded", "resolver_types",
"resolver_clazzes", "linotpConfig", "audit", "hsm"]
for data_obj in data_objects:
if hasattr(c, data_obj):
data = getattr(c, data_obj)
del data
log.debug("request %r done!" % path)
return ret
def set_language(self, headers):
'''Invoke before everything else. And set the translation language'''
languages = headers.get('Accept-Language', '')
found_lang = False
for match in accept_language_regexp.finditer(languages):
# make sure we have a correct language code format
language = match.group(1)
if not language:
continue
language = language.replace('_', '-').lower()
# en is the default language
if language.split('-')[0] == 'en':
found_lang = True
break
try:
# set_lang needs a locale name formed parameter
set_lang(language.replace('-', '_'))
found_lang = True
break
except LanguageError:
log.debug("Cannot set requested language: %s. Trying next"
" language if available.", language)
if not found_lang and languages:
log.warning("Cannot set preferred language: %r", languages)
return
def create_context(self, request):
"""
create the request context for all controllers
"""
linotp_config = getLinotpConfig()
self.request_context = {}
self.request_context['Config'] = linotp_config
self.request_context['Policies'] = getPolicies(config=linotp_config)
self.request_context['translate'] = translate
request_params = {}
try:
request_params.update(request.params)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['Params'] = request_params
authUser = None
try:
authUser = getUserFromRequest(request)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['AuthUser'] = authUser
requestUser = None
try:
requestUser = getUserFromParam(request_params, True)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['RequestUser'] = requestUser
client = None
try:
client = get_client(request=request)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['Client'] = client
self.request_context['Audit'] = Audit
self.request_context['audit'] = Audit.initialize(request,
client=client)
defaultRealm = ""
try:
defaultRealm = getDefaultRealm(linotp_config)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['defaultRealm'] = defaultRealm
realms = None
try:
realms = getRealms(context=self.request_context)
except UnicodeDecodeError as exx:
log.error("Faild to decode request parameters %r" % exx)
self.request_context['Realms'] = realms
self.request_context['hsm'] = None
if hasattr(self, "hsm"):
self.request_context['hsm'] = self.hsm
# copy some system entries from pylons
syskeys = {
"radius.nas_identifier": "LinOTP",
"radius.dictfile": "/etc/linotp2/dictionary"
}
sysconfig = {}
for key, default in syskeys.items():
try:
sysconfig[key] = config.get(key, default)
except:
log.info('no sytem config entry %s' % key)
self.request_context['SystemConfig'] = sysconfig
###eof#########################################################################