'''
product: LinOTP2
module: linotpd
edition: Community Edition
Copyright (C) 2010 - 2013 LSE Leading Security Experts GmbH
License: AGPLv3
contact: http://www.linotp.org
http://www.lsexperts.de
linotp@lsexperts.de
Description: This file is part of the linotpd service
Dependencies: -
'''
import logging
from pylons import tmpl_context as c
from pylons import request, response, config
from pylons.controllers.util import abort
from linotp.lib.base import BaseController
from linotp.lib.util import getParam
from linotp.lib.user import getUserFromParam, getUserList
from linotp.lib.realm import getDefaultRealm
from linotp.lib.user import getUserInfo
from linotp.lib.user import getUserId
from linotp.lib.config import initLinotpConfig
from linotp.lib.config import getFromConfig
from linotp.lib.token import checkUserPass, checkSerialPass
from linotp.lib.token import checkSMSPass
from linotp.lib.reply import sendResult, sendError
from linotp.model.meta import Session
from linotp.lib.selftest import isSelfTest
from linotp.lib.policy import check_user_authorization
from linotp.lib.policy import check_auth_tokentype
from linotp.lib.policy import AuthorizeException
from linotp.lib.policy import get_auth_AutoSMSPolicy
from linotp.lib.policy import set_realm
import traceback
audit = config.get('audit')
optional = True
required = False
log = logging.getLogger(__name__)
#from paste.debug.profile import profile_decorator
[docs]class ValidateController(BaseController):
'''
The linotp.controllers are the implementation of the web-API to talk to the LinOTP server.
The ValidateController is used to validate the username with its given OTP value.
An Authentication module like pam_linotp2 or rlm_linotp2 uses this ValidateController.
The functions of the ValidateController are invoked like this
https://server/validate/<functionname>
The functions are described below in more detail.
'''
''' we take the init from the BaseController '''
#def __init__(self):
### here we try to create a server singleton
# initLinotpConfig()
def __before__(self):
audit.initialize()
def __after__(self):
audit.log(c.audit)
def _check(self, param):
'''
basic check function, that can be used by different controllers
'''
options = None
passw = getParam(param,"pass",optional)
user = getUserFromParam(param,optional)
''' support for ocra application challenge verification'''
challenge = getParam(param,"challenge",optional)
if challenge != None:
options = {}
options['challenge'] = challenge
c.audit['user'] = user.login
realm = user.realm or getDefaultRealm()
c.audit['realm'] = realm
# AUTHORIZATION Pre Check
realm = set_realm(user.login, realm, exception=True)
check_user_authorization(user.login, realm, exception=True)
if isSelfTest() == True:
initTime = getParam(param,"init",optional)
if initTime == None:
initTime=""
ok = checkUserPass(user,passw,initTime,options=options)
else:
ok = checkUserPass(user,passw,options=options)
c.audit['success'] = ok
if ok:
# AUTHORIZATION post check
check_auth_tokentype(c.audit['serial'], exception=True)
return ok
""" @profile_decorator(log_file="/tmp/validate.prof") """
[docs] def check(self):
'''
This function is used to validate the username and the otp value/password.
method:
validate/check
arguments:
* user: The username or loginname
* pass: The password that consist of a possible fixed password component and the OTP value
* realm (optional): An optional realm to match the user to a useridresolver
* challenge (optional): optional challenge + otp verification for ocra tokens
returns:
JSON response::
{
"version": "LinOTP 2.4",
"jsonrpc": "2.0",
"result": {
"status": true,
"value": false
},
"id": 0
}
If ``status`` is ``true`` the request was handled successfully.
If ``value`` is ``true`` the user was authenticated successfully.
'''
param = request.params
try:
ok = self._check(param)
except AuthorizeException, e:
log.warning("[check] authorization failed for validate/check: %s" % str(e))
c.audit['success'] = False
c.audit['action_detail'] = str(e)
ok=False
except Exception, e:
log.error("[check] validate/check failed: %s", (str(e)))
log.error("[check] %s" % traceback.format_exc())
Session.rollback()
return sendError(response,"validate/check failed:" + str(e),0)
try:
Session.commit()
except Exception, e :
log.error('[check] commit failed')
return sendError(response,"Commit failed: " + str(e),0)
Session.close()
return sendResult(response,ok,0)
def check_url(self):
'''
This function works with pam_url.
'''
ok = False
param = request.params
try:
ok = self._check(param)
except AuthorizeException, e:
log.warning("[check_url] authorization failed for validate/check_url: %s" % str(e))
c.audit['success'] = False
c.audit['action_detail'] = str(e)
ok=False
except Exception, e:
log.error("[check_url] validate/check_url failed: %s", (str(e)))
log.error("[check_url] %s" % traceback.format_exc())
ok=False
Session.rollback()
try:
Session.commit()
except Exception, e :
log.error('[check_url] commit failed')
Session.close()
response.headers['blablafoo'] = 'application/json'
if not ok:
abort(403)
else:
return "Preshared Key Todo"
[docs] def samlcheck(self):
'''
This function is used to validate the username and the otp value/password
in a SAML environment. If ``linotp.allowSamlAttributes = True``
then the attributes of the authenticated users are also contained
in the response.
method:
validate/samlcheck
arguments:
* user: username / loginname
* pass: the password that consists of a possible fixes password component and the OTP value
* realm: optional realm to match the user to a useridresolver
returns:
JSON response
'''
param = request.params
try:
ok = self._check(param)
except Exception, e:
log.error("[samlcheck] validate/check failed: %s", (str(e)))
Session.rollback()
return sendError(response,"validate/samlcheck failed:" + str(e),0)
attributes = {}
if True == ok:
allowSAML = False
try:
allowSAML = getFromConfig("allowSamlAttributes")
except:
log.warning("[samlcheck] Calling controller samlcheck. But allowSamlAttributes == False.")
if "True" == allowSAML:
'''
Now we get the attributes of the user
'''
user = getUserFromParam(param,optional)
(uid,resId,resIdC) = getUserId(user)
userInfo = getUserInfo(uid, resId, resIdC)
#users = getUserList({ 'username':user.getUser()} , user)
log.debug("[samlcheck] getting attributes for: %s@%s" % (user.getUser(), user.getRealm()) )
res = userInfo
for key in ['username',
'surname',
'mobile',
'phone',
'givenname',
'email']:
if key in res:
attributes[key] = res[key]
try:
Session.commit()
except Exception, e :
log.error('[samlcheck] commit failed')
return sendError(response,"Commit failed: " + str(e),0)
Session.close()
return sendResult(response, { 'auth': ok, 'attributes' : attributes } ,0)
[docs] def check_s(self):
'''
This function is used to validate the serial and the otp value/password.
method:
validate/check_s
arguments:
* serial: the serial number of the token
* pass: the password that consists of a possible fixes password component
and the OTP value
returns:
JSON response
'''
param = request.params
try:
passw = getParam(param,"pass",required)
serial = getParam(param,'serial',required)
c.audit['serial'] = serial
if isSelfTest() == True:
initTime = getParam(param,"init",optional)
if initTime == None:
initTime=""
ok = checkSerialPass(serial,passw,initTime)
else:
ok = checkSerialPass(serial,passw)
c.audit['success'] = ok
except Exception, e:
log.error("[check_s] validate/check_s failed: %s" % (str(e)))
log.error("[check_s] %s" % str(traceback.format_exc()))
Session.rollback()
return sendError(response,"validate/check_s failed:" + str(e),0)
try:
Session.commit()
except Exception, e :
log.error('[check_s] commit failed')
return sendError(response,"Commit failed: " + str(e),0)
Session.close()
return sendResult(response,ok,0)
[docs] def simplecheck(self):
'''
This function is used to validate the username and the otp value/password.
method:
validate/simplecheck
arguments:
* user: username / loginname
* pass: the password that consists of a possible fixes password component
and the OTP value
* realm: additional realm to match the user to a useridresolver
returns:
Simple ascii response:
:-)
in case of success
:-(
in case of failed authentication
:-/
in case of any error
'''
param = request.params
try:
ok = self._check(param)
except AuthorizeException, e:
log.warning("[simplecheck] validate/simplecheck: %s" % str(e))
c.audit['success'] = False
c.audit['action_detail'] = str(e)
ok=False
except Exception, e:
log.error("[simplecheck] failed: %s", (str(e)))
Session.rollback()
return ":-/"
try:
Session.commit()
except Exception, e :
log.error('[simplecheck] commit failed')
return ":-/"
Session.close()
if ok == True:
ret = ":-)"
else:
ret = ":-("
return ret
def ok(self):
return sendResult(response,"TRUE",0)
def fail(self):
return sendResult(response,"FALSE",0)
[docs] def smspin(self):
'''
This function is used in conjunction with an SMS token:
the user authenticates with user and pin (pass) and
will receive on his mobile an OTP as message
method:
validate/smspin
arguments:
* user: username / loginname
* pass: the password that consists of a possible fixed password
* realm: additional realm to match the user to a useridresolver
returns:
JSON response
'''
ret = False
param = request.params
try:
passw = getParam(param,"pass",required)
user = getUserFromParam(param,optional)
(ret, otp) = checkSMSPass(user, passw)
if True == isSelfTest():
ret = { 'result': ret,
'otp' : otp }
except Exception, e:
log.error("[smspin] validate/smspin failed: %s", (str(e)))
Session.rollback()
return sendError(response,"validate/smspin failed:" + str(e),0)
try:
Session.commit()
except Exception, e :
log.error('[smspin] commit failed')
return sendError(response,"Commit failed: " + str(e),0)
Session.close()
return sendResult(response,ret,0)