Source code for linotp.controllers.admin

# -*- coding: utf-8 -*-
'''

  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 urllib import urlencode

from pylons import request, response, config, tmpl_context as c
from pylons.controllers.util import abort

from linotp.lib.base import BaseController

from linotp.lib.token import enableToken, assignToken , unassignToken, removeToken
from linotp.lib.token import setPin, setMaxFailCount, setOtpLen, setSyncWindow, setCounterWindow
from linotp.lib.token import resyncToken, resetToken, setPinUser, setPinSo, setHashLib, addTokenInfo
from linotp.lib.token import TokenIterator, initToken, setRealms, getTokenType, get_serial_by_otp, getTokensOfType
from linotp.lib.token import getTokens4UserOrSerial, copyTokenPin, copyTokenUser, losttoken, check_serial
from linotp.lib.token import getRolloutToken4User

from linotp.lib.config import initLinotpConfig
from linotp.lib.token import genSerial
from linotp.lib.config  import getFromConfig

from linotp.lib.tokenclass import TokenClass


from linotp.lib.error import ParameterError
from linotp.lib.util import getParam, getLowerParams, generate_otpkey
from linotp.lib.apps import create_google_authenticator_url, create_oathtoken_url
from linotp.lib.util import check_session, SESSION_KEY_LENGTH, remove_session_from_param
from linotp.lib.util import normalize_activation_code
from linotp.lib.user import getSearchFields, getUserList, User, getUserFromParam, getUserFromRequest
 
from linotp.lib.realm import getDefaultRealm

from linotp.lib.reply import sendResult, sendError, sendXMLResult, sendXMLError
from linotp.lib.reply import sendQRImageResult
from linotp.lib.reply import create_img

from linotp.model.meta import Session
from linotp.lib.policy import checkPolicyPre, checkPolicyPost, PolicyException, getAdminPolicies, getOTPPINEncrypt
from linotp.lib.audit import logTokenNum
# for loading XML file
from linotp.lib.ImportOTP import parseSafeNetXML, parseOATHcsv,  ImportException
from pylons.i18n.translation import _

from pylons import session

from tempfile import mkstemp
import os
import traceback


# For logout
from webob.exc import HTTPUnauthorized

audit = config.get('audit')


log = logging.getLogger(__name__)

optional = True
required = False
                

[docs]class AdminController(BaseController): ''' The linotp.controllers are the implementation of the web-API to talk to the LinOTP server. The AdminController is used for administrative tasks like adding tokens to LinOTP, assigning tokens or revoking tokens. The functions of the AdminController are invoked like this https://server/admin/<functionname> The functions are described below in more detail. ''' def __before__(self): audit.initialize() c.audit['success'] = False self.set_language() # Session handling check_session() def __after__(self): c.audit['administrator'] = getUserFromRequest(request).get("login") if request.params.has_key('serial'): c.audit['serial'] = request.params['serial'] c.audit['token_type'] = getTokenType( request.params['serial'] ) audit.log(c.audit) def test(self): session["test"] = "Hallo" session.save() def logout(self): # see http://docs.pylonsproject.org/projects/pyramid/1.0/narr/webob.html c.audit['action_detail'] = "logout" #response.status = "401 Not authenticated" import hashlib import time nonce = request.environ.get("nonce") realm = request.environ.get("realm") detail = "401 Unauthorized" #return HTTPUnauthorized(request=request) raise HTTPUnauthorized( str(detail), [('WWW-Authenticate', 'Digest realm="%s", nonce="%s", qop="auth"' % (realm, nonce))] ) #raise exc.HTTPUnauthorized( # str(detail), # [('WWW-Authenticate', 'Basic realm="%s"' % realm)] # ) #abort(401, "You are not authenticated") #raise HTTPUnauthorized()
[docs] def getsession(self): ''' This generates a session key and sets it as a cookie set_cookie is defined in python-webob: def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=None, httponly=False, version=None, comment=None, expires=None, overwrite=False): ''' import binascii try: web_host = request.environ.get('HTTP_HOST') # HTTP_HOST also contains the port number. We need to stript this! web_host = web_host.split(':')[0] log.debug("[getsession] environment: %s" % request.environ) log.debug("[getsession] found this web_host: %s" % web_host) random_key = os.urandom(SESSION_KEY_LENGTH) cookie = binascii.hexlify(random_key) log.debug("[getsession] adding session cookie %s to response." % cookie) # we send all three to cope with IE8 response.set_cookie('admin_session', value=cookie, domain=web_host ) # this produces an error with the gtk client # response.set_cookie('admin_session', value=cookie, domain=".%" % web_host ) response.set_cookie('admin_session', value=cookie, domain="" ) except Exception, e: log.error("[getsession] unable to create a session cookie: %s" % str(e)) return sendError(response,e) return sendResult(response,True)
def dropsession(self): #request.cookies.pop( 'admin_session', None ) # FIXME: Does not seem to work response.set_cookie('admin_session', None, expires=1) return
[docs] def show(self): """ method: admin/show description: displays the list of the available tokens arguments: serial - optional: only this serial will be displayed user - optional: only the tokens of this user will be displayed filter - optional: takes a substring to search in table token columns viewrealm - optional: takes a realm, only the tokens in this realm will be displayed sortby - optional: sort the output by column sortdir - optional: asc/desc page - optional: reqeuest a certain page pagesize- optional: limit the number of returned tokens returns: a json result with { "head": [], "data": [ [row1], [row2] .. ] } exception: if an error occurs an exception is serialized and returned """ param = request.params try: serial = getParam(param,"serial",optional) page = getParam(param,"page",optional) filter = getParam(param,"filter",optional) sort = getParam(param,"sortby",optional) dir = getParam(param,"sortdir",optional) psize = getParam(param,"pagesize",optional) realm = getParam(param,"viewrealm",optional) user = getUserFromParam(param,optional) filterRealm = [] # check admin authorization try: res = checkPolicyPre('admin', 'show', param , user=user) filterRealm = res['realms'] # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. pol = getAdminPolicies( "show" ) # If there are no admin policies, we are allowed to see all realms if not pol['active']: filterRealm=["*"] except PolicyException as pe: return sendError(response, str(pe), 1) # If the admin wants to see only one realm, then do it: log.debug("[show] checking to only see tokens in realm <%s>" % realm) if realm: if realm in filterRealm or '*' in filterRealm: filterRealm=[realm] log.info("[show] admin >%s< may display the following realms: %s" % (res['admin'], filterRealm)) log.info("[show] displaying tokens: serial: %s, page: %s, filter: %s, user: %s", serial, page, filter, user.login) toks = TokenIterator(user,serial,page,psize,filter,sort,dir,filterRealm) c.audit['success'] = True c.audit['info'] = "realm: %s, filter: %s" % (filterRealm, filter) except Exception, e: log.warning("[show] failed!") Session.rollback() return sendError(response,e) # put in the result result = {} ### now row by row lines = [] for tok in toks: # CKO: log.debug("tokenline: %s" % tok) lines.append(tok) result["data"] = lines result["resultset"] = toks.getResultSetInfo() try: Session.commit() except Exception, e : log.error('[show] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response,result) ########################################################
[docs] def remove(self): """ method: admin/remove description: deletes either a certain token given by serial or all tokens of a user arguments: serial - optional user - optional returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[remove] calling remove ") param = request.params try: serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) # check admin authorization try: checkPolicyPre('admin', 'remove', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[remove] removing token with serial %s for user %s", serial, user.login) ret = removeToken(user,serial) c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() logTokenNum() c.audit['success'] = ret except Exception, e: log.error("[remove] remove failed!") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[remove] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if everything is ok the new counter is 0, which is returned Session.close() return sendResult(response,ret) ########################################################
[docs] def enable (self): """ method: admin/enable description: enables a token or all tokens of a user arguments: serial - optional user - optional returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[enable] calling enable to enable/disable a token") param = request.params try: serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) # check admin authorization try: checkPolicyPre('admin', 'enable', param , user=user) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[enable] enable token with serial %s for user %s@%s.",serial,user.login,user.realm) ret = enableToken(True,user,serial) c.audit['success'] = ret c.audit['user'] = user.login c.audit['realm'] = user.realm logTokenNum() if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() except Exception, e: Session.rollback() log.error('[enable] error enabling token') return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[enable] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if the token after the action has the same state all is ok Session.close() return sendResult(response,ret,1) ########################################################
[docs] def getSerialByOtp (self): """ method: admin/getSerialByOtp description: searches for the token, that generates the given OTP value. The search can be restricted by several critterions arguments: otp - required. Will search for the token, that produces this OTP value type - optional, will only search in tokens of type realm - optional, only search in this realm assigned - optional. 1: only search assigned tokens, 0: only search unassigned tokens returns: a json result with the serial exception: if an error occurs an exception is serialized and returned """ log.debug("[getSerialByOtp] entering function") ret = {} param = request.params try: otp = getParam(param,"otp",required) typ = getParam(param,"type",optional) realm = getParam(param,"realm",optional) assigned = getParam(param,"assigned",optional) serial = "" username = "" resolver ="" # check admin authorization try: checkPolicyPre('admin', 'getserial', param ) except PolicyException as pe: return sendError(response, str(pe), 1) serial, username, resolverClass = get_serial_by_otp(None, otp, 10, typ=typ, realm=realm, assigned=assigned) log.debug("[getSerialByOtp] found %s with user %s" % (serial, username) ) if "" != serial: try: checkPolicyPost('admin', 'getserial', {'serial' : serial} ) except PolicyException as pe: return sendError(response, str(pe), 1) c.audit['success'] = 1 c.audit['serial'] = serial ret['success'] = True ret['serial'] = serial ret['user_login'] = username ret['user_resolver'] = resolverClass except Exception, e: c.audit['success'] = 0 Session.rollback() log.error('[getSerialByOtp] error: %s' % str(e)) log.error("[getSerialByOtp] %s" % traceback.format_exc()) return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[getSerialByOtp] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if the token after the action has the same state all is ok Session.close() return sendResult(response,ret,1) ########################################################
[docs] def disable (self): """ method: admin/disable description: disables a token given by serial or all tokens of a user arguments: serial - optional user - optional returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("calling enable to enable/disable a token") param = request.params try: serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) # check admin authorization try: checkPolicyPre('admin', 'disable', param , user=user) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[disable] disable token with serial %s for user %s@%s.",serial,user.login,user.realm) ret = enableToken(False, user,serial) c.audit['success'] = ret c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() except Exception, e: Session.rollback() log.error('[disable] error disabling token') return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[disable] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if the token after the action has the same state all is ok Session.close() return sendResult(response,ret,1) #######################################################
[docs] def check_serial(self): ''' method admin/check_serial description: This function checks, if a given serial will be unique. It returns True if the serial does not yet exist and new_serial as a new value for a serial, that does not exist,yet arguments: serial - required- the serial to be checked returns: a json result with a new suggestion for the serial exception: if an error occurs an exception is serialized and returned ''' log.debug("calling check_serial") ret = True param = request.params try: serial = getParam(param,"serial",required) # check admin authorization #try: # checkPolicyPre('admin', 'disable', param ) #except PolicyException as pe: # return sendError(response, str(pe), 1) log.info("[check_serial] checking serial %s" % serial) (unique, new_serial) = check_serial(serial) c.audit['success'] = True c.audit['serial'] = serial c.audit['action_detail'] = "%s - %s" % (str(unique), new_serial) except Exception, e: Session.rollback() log.error('[check_serial] %s' % str(e)) return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[check_serial] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if the token after the action has the same state all is ok Session.close() return sendResult(response,{"unique":unique, "new_serial":new_serial},1) ########################################################
[docs] def init(self): """ method: admin/init description: creates a new token. arguments: otpkey - required - the hmac Key of the token genkey - required - =1, if key should be generated. We either need otpkey or genkey keysize - optional - either 20 or 32. Default is 20 serial - required - the serial number / identifier of the token description - optional pin - optional - the pin of the user pass user - optional - login user name realm - optional - realm of the user type - optional - the type of the token tokenrealm - optional - the realm a token should be put into otplen - optional - length of the OTP value hashlib - optional - used hashlib sha1 oder sha256 ocra arguments: for generating OCRA Tokens type=ocra you can specify the following parameters: ocrasuite - optional - if you do not want to use the default ocra suite OCRA-1:HOTP-SHA256-8:QA64 sharedsecret - optional - if you are in Step0 of enrolling an OCRA/QR token the sharedsecret=1 specifies, that you want to generate a shared secret activationcode -optional - if you are in Step1 of enrolling an OCRA token you need to pass the activation code, that was generated in the QRTAN-App returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[init] calling the init controller function") ret = False param = request.params response_detail = {} helper_param = {} try: tokenrealm = None for k, v in param.iteritems(): helper_param[k] = v user = getUserFromParam(param,optional) serial = getParam(param,"serial",optional) tok_type = getParam(param,"type",optional) key_size = getParam(param, "keysize", optional) genkey = getParam(param, "genkey", optional) if tok_type == 'ocra': ''' take the keysize from the ocrasuite ''' ocrasuite = getParam(param, "ocrasuite", optional) activationcode = getParam(param, "activationcode", optional) sharedsecret = getParam(param, "sharedsecret", optional) if activationcode != None: ''' dont create a new key ''' genkey = None serial = getRolloutToken4User(user=user, serial=serial, tok_type=tok_type) if serial == None: raise Exception('no token found for user: %s or serial: %s' %(str(user),str(serial))) helper_param['serial'] = serial helper_param['activationcode'] = normalize_activation_code(activationcode) if ocrasuite == None: if sharedsecret != None or activationcode!= None: ocrasuite = getFromConfig("QrOcraDefaultSuite",'OCRA-1:HOTP-SHA256-6:C-QA64') else: ocrasuite = getFromConfig("OcraDefaultSuite",'OCRA-1:HOTP-SHA256-8:C-QN08') helper_param['ocrasuite'] = ocrasuite if genkey != None: if ocrasuite.find('-SHA256'): key_size = 32 elif ocrasuite.find('-SHA512'): key_size = 64 else: key_size = 20 if serial == None: serial = genSerial(tok_type) helper_param['serial'] = serial if None == key_size: key_size = 20 ''' if the key should be generated by the server ''' if None != genkey: otpkey = generate_otpkey(int(key_size)) helper_param["otpkey"] = otpkey if tok_type != 'ocra': response_detail["otpkey"] = { "description": _("OTP seed"), "value" : "seed://%s" % otpkey, "img" : create_img(otpkey, width=200), } goo_url = create_google_authenticator_url(user.login,user.realm,otpkey,tok_type.lower(),serial=serial) response_detail["googleurl"] = { "description": _("URL for google Authenticator"), "value" : goo_url, "img" : create_img(goo_url, width=250)} oath_url = create_oathtoken_url(user.login, user.realm,otpkey,tok_type, serial=serial) response_detail["oathurl"] = { "description" : _("URL for OATH token"), "value" : oath_url, "img" : create_img(oath_url, width=250)} # check admin authorization try: # this needs to return the valid realms of the admin. res = checkPolicyPre('admin', 'init', param, user=user) # if no user is given, we put the token in all realms of the admin if user.login == "": log.debug("[init] setting tokenrealm %s" % res['realms']) tokenrealm = res['realms'] except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[init] initialize token. user: %s, serial: %s" % (user.login, serial)) (ret,tokenObj) = initToken(helper_param, user, tokenrealm=tokenrealm) if tok_type == 'ocra': if tokenObj != None: info = tokenObj.getInfo() ocra_url = info.get('app_import') response_detail["ocraurl"] = { "description" : _("URL for OCRA token"), "value" : ocra_url, "img" : create_img(ocra_url, width=250)} response_detail.update(info) c.audit['success'] = ret c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() logTokenNum() c.audit['success'] = ret try: checkPolicyPost('admin', 'init', param, user=user) except PolicyException as pe: return sendError(response, str(pe), 1) except Exception, e: log.error("[init] token initialization failed! " + str(e)) log.error("[init] %s" % traceback.format_exc()) Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) #if the token after the action has the same state all is ok Session.close() qr = getParam(param, 'qr',optional) if qr != None and tok_type in ('ocra','hmac','totp'): hparam = {} if tok_type == 'ocra': hparam['alt'] = response_detail.get('ocraurl') return sendQRImageResult(response, ocra_url, hparam) elif tok_type in ('hmac','totp'): hparam['alt'] = response_detail.get('googleurl') return sendQRImageResult(response, goo_url, hparam) else: return sendResult(response,ret,opt=response_detail) ########################################################
[docs] def unassign(self): """ method: admin/unassign - remove the assigned user from the token description: unassigns a token from a user. i.e. the binding between the token and the user is removed arguments: serial - required - the serial number / identifier of the token user - optional returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[unassign] entering function unassign") param = request.params try: serial = getParam(param,"serial",required) user = getUserFromParam(param,optional) log.debug("[unassign] unassigning serial %s, user %s" %( serial, str(user) ) ) # check admin authorization try: checkPolicyPre('admin', 'unassign', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[unassign] unassigning token with serial %s from user %s@%s" % (serial, user.login, user.realm)) res = unassignToken(serial, user, None) c.audit['success'] = res c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm']: c.audit['realm'] = getDefaultRealm() except Exception, e: log.error("[unassign] token assignment failed! " + str(e)) Session.rollback() return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[unassign] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response,res,1) ########################################################
[docs] def assign(self): """ method: admin/assign description: assigns a token to a user, i.e. a binding between the token and the user is created. arguments: serial - required - the serial number / identifier of the token user - required - login user name pin - optional - the pin of the user pass returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[assign] entering function assign") param = request.params try: upin = getParam(param,"pin",optional) serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) # check admin authorization try: checkPolicyPre('admin', 'assign', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[assign] assigning token with serial %s to user %s@%s" % (serial, user.login, user.realm)) res = assignToken(serial, user, upin, param) c.audit['success'] = res c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm']: c.audit['realm'] = getDefaultRealm() except Exception, e: log.error("[assign] token assignment failed!" + str(e)) Session.rollback() return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response,res,1) ########################################################
[docs] def setPin(self): """ method: admin/set description: This function sets the smartcard PINs of a eTokenNG OTP. The userpin is used to store the mOTP PIN of mOTP tokens! !!! For setting the OTP PIN, use the function /admin/set! arguments: serial - required userpin - optional: store the userpin sopin - optional: store the sopin returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ res = {} count = 0 description = "setPin: parameters are\ serial\ userpin\ sopin\ " log.debug('[setPin]') param = getLowerParams(request.params) ## if there is a pin if param.has_key("userpin"): try: userPin = getParam(param,"userpin",required) serial = getParam(param,"serial",required) # check admin authorization try: checkPolicyPre('admin', 'setPin', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[setPin] setting userPin for token with serial %s" % serial) ret = setPinUser(userPin, serial) res["set userpin"]=ret count = count +1 c.audit['action_detail'] += "userpin," except Exception, e: log.error("[setPin] setting userPin failed") Session.rollback() return sendError(response,e,1) if param.has_key("sopin"): try: soPin = getParam(param,"sopin",required) serial = getParam(param,"serial",required) # check admin authorization try: checkPolicyPre('admin', 'setPin', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[setPin] setting soPin for token with serial %s" % serial) ret = setPinSo(soPin, serial) res["set sopin"]=ret count = count +1 c.audit['action_detail'] += "sopin," except Exception, e: log.error("[setPin] setting soPin failed") Session.rollback() return sendError(response,e,1) if count == 0 : Session.rollback() return sendError(response,ParameterError(77,"Usage:" + description)) c.audit['success'] = count try: Session.commit() except Exception, e : log.error('[setPin] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, res, 1) ########################################################
[docs] def set(self): """ method: admin/set description: this function is used to set many different values of a token. arguments: serial - optional user - optional pin - optional - set the OTP PIN MaxFailCount - optional - set the maximum fail counter of a token SyncWindow - optional - set the synchronization window of the token OtpLen - optional - set the OTP Lenght of the token CounterWindow - optional - set the counter window (blank presses) hashlib - optioanl - set the hashing algo for HMAC tokens. This can be sha1, sha256, sha512 timeWindow - optional - set the synchronize window for timebased tokens (in seconds) timeStep - optional - set the timestep for timebased tokens (usually 30 or 60 seconds) timeShift - optional - set the shift or timedrift of this token countAuthSuccessMax - optional - set the maximum allowed successful authentications countAuthSuccess\ - optional - set the counter of the successful authentications countAuth - optional - set the counter of authentications countAuthMax - optional - set the maximum allowed authentication tries validityPeriodStart - optional - set the start date of the validity period. The token can not be used before this date validityPeriodEnd - optional - set the end date of the validaity period. The token can not be used after this date returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ res = {} count = 0 log.debug("[set]") description = "set: parameters are\ pin\ MaxFailCount\ SyncWindow\ OtpLen\ CounterWindow\ hashlib\ timeWindow\ timeStep\ timeShift\ countAuthSuccessMax\ countAuthSuccess\ countAuth\ countAuthMax\ validityPeriodStart\ validityPeriodEnd\ " log.debug('[set]') param = getLowerParams(request.params) serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) # check admin authorization try: checkPolicyPre('admin', 'set', param, user=user ) except PolicyException as pe: return sendError(response, str(pe), 1) ## if there is a pin if param.has_key("pin"): try: upin = getParam(param,"pin",required) log.info("[set] setting pin for token with serial %s" % serial) if 1 == getOTPPINEncrypt( serial=serial, user=user): param['encryptpin'] = "True" ret = setPin(upin,user,serial, param) res["set pin"]=ret count = count +1 c.audit['action_detail'] += "pin," except Exception, e: log.error("[set] setting pin failed") Session.rollback() return sendError(response,e,1) if param.has_key("MaxFailCount".lower()): try: maxFail = getParam(param,"MaxFailCount".lower(),required) log.info("[set] setting maxFailCount (%s) for token with serial %s" % (maxFail, serial)) ret = setMaxFailCount(maxFail,user,serial) res["set MaxFailCount"]=ret count = count +1 c.audit['action_detail'] += "maxFailCount=%s," % str(maxFail) except Exception, e: log.error("[set] setting MaxFailCount failed") Session.rollback() return sendError(response,e,1) if param.has_key("SyncWindow".lower()): try: syncWindow = getParam(param,"SyncWindow".lower(),required) log.info("[set] setting syncWindow (%s) for token with serial %s" % (syncWindow, serial)) ret = setSyncWindow(syncWindow,user,serial) res["set SyncWindow"]=ret count = count +1 c.audit['action_detail'] += "syncWindow=%s," % str(syncWindow) except Exception, e: log.error("[set] setting SyncWindow failed") Session.rollback() return sendError(response,e,1) if param.has_key("CounterWindow".lower()): try: counterWindow = getParam(param,"CounterWindow".lower(),required) log.info("[set] setting counterWindow (%s) for token with serial %s" % (counterWindow, serial)) ret = setCounterWindow(counterWindow,user,serial) res["set CounterWindow"]=ret count = count +1 c.audit['action_detail'] += "counterWindow=%s," % str(counterWindow) except Exception, e: log.error("[set] setting CounterWindow failed") Session.rollback() return sendError(response,e,1) if param.has_key("OtpLen".lower()): try: otpLen = getParam(param,"OtpLen".lower(),required) log.info("[set] setting OtpLen (%s) for token with serial %s" % (otpLen, serial)) ret = setOtpLen(otpLen,user,serial) res["set OtpLen"]=ret count = count +1 c.audit['action_detail'] += "otpLen=%s," % str(otpLen) except Exception, e: log.error("[set] setting OtpLen failed") Session.rollback() return sendError(response,e,1) if param.has_key("hashlib".lower()): try: hashlib = getParam(param,"hashlib".lower(),required) log.info("[set] setting hashlib (%s) for token with serial %s" % (hashlib, serial)) ret = setHashLib(hashlib,user,serial) res["set hashlib"]=ret count = count +1 c.audit['action_detail'] += "hashlib=%s," % str(hashlib) except Exception, e: log.error("[set] setting hashlib failed") Session.rollback() return sendError(response,e,1) if param.has_key("timeWindow".lower()): try: timeWindow = getParam(param,"timeWindow".lower(),required) log.info("[set] setting timeWindow (%s) for token with serial %s" % (timeWindow, serial)) ret = addTokenInfo("timeWindow", timeWindow ,user,serial) res["set timeWindow"]=ret count = count +1 c.audit['action_detail'] += "timeWindow=%s," % str(timeWindow) except Exception, e: log.error("[set] setting timeWindow failed") Session.rollback() return sendError(response,e,1) if param.has_key("timeStep".lower()): try: timeStep = getParam(param,"timeStep".lower(),required) log.info("[set] setting timeStep (%s) for token with serial %s" % (timeStep, serial)) ret = addTokenInfo("timeStep", timeStep ,user,serial) res["set timeStep"]=ret count = count +1 c.audit['action_detail'] += "timeStep=%s," % str(timeStep) except Exception, e: log.error("[set] setting timeStep failed") Session.rollback() return sendError(response,e,1) if param.has_key("timeShift".lower()): try: timeShift = getParam(param,"timeShift".lower(),required) log.info("[set] setting timeShift (%s) for token with serial %s" % (timeShift, serial)) ret = addTokenInfo("timeShift", timeShift ,user,serial) res["set timeShift"]=ret count = count +1 c.audit['action_detail'] += "timeShift=%s," % str(timeShift) except Exception, e: log.error("[set] setting timeShift failed") Session.rollback() return sendError(response,e,1) if param.has_key("countAuth".lower()): try: ca = getParam(param,"countAuth".lower(),required) log.info("[set] setting count_auth (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_count_auth(int(ca)) count = count +1 ret +=1 res["set countAuth"]=ret c.audit['action_detail'] += "countAuth=%s," % str(ca) except Exception, e: log.error("[set] setting countAuth failed") Session.rollback() return sendError(response,e,1) if param.has_key("countAuthMax".lower()): try: ca = getParam(param,"countAuthMax".lower(),required) log.info("[set] setting count_auth_max (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_count_auth_max(int(ca)) count = count +1 ret +=1 res["set countAuthMax"]=ret c.audit['action_detail'] += "countAuthMax=%s," % str(ca) except Exception, e: log.error("[set] setting countAuthMax failed") Session.rollback() return sendError(response,e,1) if param.has_key("countAuthSuccess".lower()): try: ca = getParam(param,"countAuthSuccess".lower(),required) log.info("[set] setting count_auth_success (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_count_auth_success(int(ca)) count = count +1 ret +=1 res["set countAuthSuccess"]=ret c.audit['action_detail'] += "countAuthSuccess=%s," % str(ca) except Exception, e: log.error("[set] setting countAuthSuccess failed") Session.rollback() return sendError(response,e,1) if param.has_key("countAuthSuccessMax".lower()): try: ca = getParam(param,"countAuthSuccessMax".lower(),required) log.info("[set] setting count_auth_success_max (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_count_auth_success_max(int(ca)) count = count +1 ret +=1 res["set countAuthSuccessMax"]=ret c.audit['action_detail'] += "countAuthSuccessMax=%s," % str(ca) except Exception, e: log.error("[set] setting countAuthSuccessMax failed") Session.rollback() return sendError(response,e,1) if param.has_key("validityPeriodStart".lower()): try: ca = getParam(param,"validityPeriodStart".lower(),required) log.info("[set] setting validity_period_start (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_validity_period_start(ca) count = count +1 ret +=1 res["set validityPeriodStart"]=ret c.audit['action_detail'] += "validityPeriodStart=%s," % str(ca) except Exception, e: log.error("[set] setting validityPeriodStart failed") Session.rollback() return sendError(response,e,1) if param.has_key("validityPeriodEnd".lower()): try: ca = getParam(param,"validityPeriodEnd".lower(),required) log.info("[set] setting validity_period_end (%s) for token with serial %s" % (ca, serial)) tokens = getTokens4UserOrSerial(user,serial) ret = 0 for tok in tokens: tok.set_validity_period_end(ca) count = count +1 ret +=1 res["set validityPeriodEnd"]=ret c.audit['action_detail'] += "validityPeriodEnd=%s," % str(ca) except Exception, e: log.error("[set] setting validityPeriodEnd failed") Session.rollback() return sendError(response,e,1) if count == 0 : Session.rollback() return sendError(response,ParameterError(77,"Usage:" + description)) c.audit['success'] = count c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() try: Session.commit() except Exception, e : log.error('[set] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, res, 1) ########################################################
[docs] def resync(self): """ method: admin/resync - resync a token to a new counter description: this function resync the token, if the counter on server side is out of sync with the physica token. arguments: serial - serial or user required user - s.o. otp1 - the next otp to be found otp2 - the next otp after the otp1 returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[resync]") param = request.params serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) try: otp1 = getParam(param,"otp1",required) otp2 = getParam(param,"otp2",required) ''' to support the challenge based resync, we have to pass the challenges down to the token implementation ''' chall1 = getParam(param,"challenge1",optional) chall2 = getParam(param,"challenge2",optional) options = None if chall1 != None and chall2 != None: options = {'challenge1' : chall1, 'challenge2':chall2 } # check admin authorization try: checkPolicyPre('admin', 'resync', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[resync] resyncing token with serial %s, user %s@%s" % (serial, user.login, user.realm)) res = resyncToken(otp1, otp2, user, serial, options) c.audit['success'] = res c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() except Exception, e: log.error('[resync] resyncing token failed') Session.rollback() return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[resync] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, res, 1) ########################################################
[docs] def userlist(self): """ method: admin/userlist - list all users description: lists the used in a realm arguments: <searchexpr> - will be retrieved from the UserIdResolverClass realm - a realm, which is a collection of resolver configurations resConf - a destinct resolver configuration returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ users = [] param = request.params realm = getParam(param,"realm",optional) _resolver = getParam(param,"resConf",optional) # check admin authorization # check if we got a realm or resolver, that is ok! try: checkPolicyPre('admin', 'userlist', { 'user': "dummy", 'realm':realm} ) except PolicyException as pe: return sendError(response, str(pe), 1) up = 0 user = getUserFromParam(param,optional) log.info("[userlist] displaying users with param: %s, ", param) if (len(user.realm) >0): up = up +1 if (len(user.conf) >0): up = up +1 """ # Here we need to list the users, that are only visible in the realm!! we could also only list the users in the realm, if the admin got the right "userlist". """ try: ### list searchfields if no other param if len(param) == up: usage = {"usage":"list available users matching the given search patterns:"} usage["searchfields"] = getSearchFields(user) res = usage else: users = getUserList(remove_session_from_param(param),user) res = users c.audit['success'] = True c.audit['info'] = "realm: %s" % realm except Exception, e: log.error("[userlist] failed") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[userlist] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, res) ########################################################
[docs] def tokenrealm(self): ''' method: admin/tokenrealm - set the realms a token belongs to description: sets the realms of a token arguments: serial - required - serialnumber of the token realm - required - comma seperated list of realms ''' log.debug("[tokenrealm] calling tokenrealm") param = request.params try: serial = getParam(param,"serial",required) realms = getParam(param,"realms",required) # check admin authorization try: checkPolicyPre('admin', 'tokenrealm', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[tokenrealm] setting realms for token %s to %s" % (serial, realms)) realmList = realms.split(',') ret = setRealms(serial, realmList) c.audit['success'] = ret c.audit['info'] = realms except Exception, e: Session.rollback() log.error('[tokenrealm] error setting realms for token') return sendError(response,e,1) try: Session.commit() except Exception, e : log.error('[tokenrealm] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response,ret,1) ########################################################
[docs] def reset(self): """ method: admin/reset description: reset the FailCounter of a Token arguments: user or serial - to identify the tokens returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[reset]") users = [] param = request.params serial = getParam(param,"serial",optional) user = getUserFromParam(param,optional) try: # check admin authorization try: checkPolicyPre('admin', 'reset', param , user=user) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[reset] resetting the FailCouter for token with serial %s" % serial) ret = resetToken(user,serial) c.audit['success'] = ret c.audit['user'] = user.login c.audit['realm'] = user.realm if "" == c.audit['realm'] and "" != c.audit['user']: c.audit['realm'] = getDefaultRealm() except Exception, e: log.error("[reset] Error resetting failcounter") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[reset] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, ret) ########################################################
[docs] def copyTokenPin(self): """ method: admin/copyTokenPin description: copies the token pin from one token to another arguments: from - required - serial of token from to - required - serial of token to returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[copyTokenPin]") ret = 0 err_string = "" param = request.params serial_from = getParam(param,"from",required) serial_to = getParam(param,"to",required) try: # check admin authorization try: checkPolicyPre('admin', 'copytokenpin', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[copyTokenPin] copying Pin from token %s to token %s" % (serial_from, serial_to)) ret = copyTokenPin(serial_from, serial_to) c.audit['success'] = ret c.audit['serial'] = serial_to c.audit['action_detail'] = "from %s" % serial_from err_string = str(ret) if -1 == ret: err_string = "can not get PIN from source token" if -2 == ret: err_string = "can not set PIN to destination token" if 1 != ret: c.audit['action_detail'] += ","+err_string c.audit['success'] = 0 except Exception, e: log.error("[copyTokenPin] Error copying token pin") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[copyTokenPin] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() # Success if 1 == ret: return sendResult(response, True) return sendError(response, "copying token pin failed: %s" % err_string) ########################################################
[docs] def copyTokenUser(self): """ method: admin/copyTokenUser description: copies the token user from one token to another arguments: from - required - serial of token from to - required - serial of token to returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[copyTokenUser]") ret = 0 err_string = "" param = request.params serial_from = getParam(param,"from",required) serial_to = getParam(param,"to",required) try: # check admin authorization try: checkPolicyPre('admin', 'copytokenuser', param ) except PolicyException as pe: return sendError(response, str(pe), 1) log.info("[copyTokenUser] copying User from token %s to token %s" % (serial_from, serial_to)) ret = copyTokenUser(serial_from, serial_to) c.audit['success'] = ret c.audit['serial'] = serial_to c.audit['action_detail'] = "from %s" % serial_from err_string = str(ret) if -1 == ret: err_string = "can not get user from source token" if -2 == ret: err_string = "can not set user to destination token" if 1 != ret: c.audit['action_detail'] += ","+err_string c.audit['success'] = 0 except Exception, e: log.error("[copyTokenUser] Error copying token user") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[copyTokenUser] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() # Success if 1 == ret: return sendResult(response, True) return sendError(response, "copying token user failed: %s" % err_string) ########################################################
[docs] def losttoken(self): """ method: admin/losttoken description: creates a new password token and copies the PIN and the user of the old token to the new token. The old token is disabled. arguments: serial - serial of the old token returns: a json result with the new serial an the password exception: if an error occurs an exception is serialized and returned """ log.debug("[losttoken]") ret = 0 res = {} err_string = "" param = request.params serial = getParam(param,"serial",required) try: # check admin authorization try: checkPolicyPre('admin', 'losttoken', param ) except PolicyException as pe: return sendError(response, str(pe), 1) res = losttoken(serial) c.audit['success'] = ret c.audit['serial'] = res.get('serial') c.audit['action_detail'] = "from %s" % serial except Exception, e: log.error("[losttoken] Error doing losttoken") Session.rollback() return sendError(response,e) try: Session.commit() except Exception, e : log.error('[losttoken] commit failed') Session.rollback() return sendError(response,"Commit failed: " + str(e),0) Session.close() return sendResult(response, res) ########################################################
[docs] def loadtokens(self): """ method: admin/loadtokens description: loads a whole token file to the server arguments: file - the file in a post request type - the file type. returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ log.debug("[loadtokens]") res = "Loading token file failed!" known_types = ['aladdin-xml', 'oathcsv'] TOKENS = {} res = None sendResultMethod = sendResult sendErrorMethod = sendError try: from linotpee.lib.ImportOTP import getKnownTypes known_types.extend(getKnownTypes()) log.info("[loadtokens] importing linotpee.lib. Running Enterprise Edition. Known import types: %s" % known_types) from linotpee.lib.ImportOTP.PSKC import parsePSKCdata log.info("[loadtokens] loaded parsePSKCdata") from linotpee.lib.ImportOTP.DPWplain import parseDPWdata log.info("[loadtokens] loaded parseDPWdata") from linotpee.lib.ImportOTP.vasco import parseVASCOdata log.info("[loadtokens] loaded parseVASCOdata") except Exception, e: log.warning("[loadtokens] Unable to load linotpee.lib. Running Community Edition: %s" % str(e)) try: #if 1==1: log.debug("[loadtokens] getting POST request") log.debug("[loadtokens] %s" % str(request.POST)) tokenFile = request.POST['file'] fileType = request.POST['type'] pskc_type = None pskc_password = None pskc_preshared = None pskc_checkserial= False hashlib = None if "pskc" == fileType: pskc_type = request.POST['pskc_type'] pskc_password = request.POST['pskc_password'] pskc_preshared = request.POST['pskc_preshared'] if 'pskc_checkserial' in request.POST: pskc_checkserial= True fileString = "" typeString = "" log.debug("[loadtokens] loading token file to server using POST request. Filetype: %s. File: %s" % (fileType, tokenFile) ) # In case of form post requests, it is a "instance" of FieldStorage # i.e. the Filename is selected in the browser and the data is transferred # in an iframe. see: http://jquery.malsup.com/form/#sample4 # if type(tokenFile).__name__=='instance': log.debug("[loadtokens] Field storage file: %s",tokenFile) fileString = tokenFile.value sendResultMethod = sendXMLResult sendErrorMethod = sendXMLError else: fileString = tokenFile log.debug("[loadtokens] fileString: %s",fileString) if type(fileType).__name__=='instance': log.debug("[loadtokens] Field storage type: %s",fileType) typeString = fileType.value else: typeString = fileType log.debug("[loadtokens] typeString: <<%s>>",typeString) if "pskc" == typeString: log.debug("[loadtokens] passing password: %s, key: %s, checkserial: %s" % (pskc_password,pskc_preshared,pskc_checkserial)) if fileString == "" or typeString == "": log.error("[loadtokens] file: %s", fileString) log.error("[loadtokens] type: %s", typeString) log.error("[loadtokens] Error loading/importing token file. file or type empty!") return sendErrorMethod(response, "Error loading tokens. File or Type empty!") if typeString not in known_types: log.error("[loadtokens] Unknown file type: >>%s<<. We only know the types: %s" % (type, ','.join(known_types) ) ) return sendErrorMethod(response, "Unknown file type: >>%s<<. We only know the types: %s" % (type, ','.join(known_types) )) # Parse the tokens from file and get dictionary if typeString == "aladdin-xml": TOKENS = parseSafeNetXML( fileString ) # we only do hashlib for aladdin at the moment. if 'aladdin_hashlib' in request.POST: hashlib = request.POST['aladdin_hashlib'] elif typeString == "oathcsv": TOKENS = parseOATHcsv( fileString ) elif typeString == "dpw": TOKENS = parseDPWdata( fileString ) elif typeString == "feitian": TOKENS = parsePSKCdata( fileString, do_feitian=True ) elif typeString == "pskc": if "key" == pskc_type: TOKENS = parsePSKCdata( fileString, preshared_key_hex=pskc_preshared, do_checkserial=pskc_checkserial ) elif "password" == pskc_type: TOKENS = parsePSKCdata( fileString, password=pskc_password, do_checkserial=pskc_checkserial ) #log.debug(TOKENS) elif "plain" == pskc_type: TOKENS = parsePSKCdata( fileString, do_checkserial=pskc_checkserial ) elif typeString == "vasco": vasco_otplen = request.POST['vasco_otplen'] (fh, filename) = mkstemp() f = open(filename, "w") f.write(fileString) f.close() TOKENS = parseVASCOdata( filename, int(vasco_otplen) ) os.remove(filename) if TOKENS == None: raise ImportException("Vasco DLL was not properly loaded. Importing of VASCO token not possible. Please check the log file for more details.") log.debug("[loadtokens] read %i tokens. starting import now" % len(TOKENS)) # Now import the Tokens from the dictionary ret = "" for serial in TOKENS: log.debug("[loadtokens] importing token %s" % TOKENS[serial]) # this needs to return the valid realms of the admin. # it also checks the license token number res = checkPolicyPre('admin', 'import', {} ) # we put the token in the FIRST realm of the admin. # so tokenrealm will either be ONE realm or NONE log.error("[loadtokens] setting tokenrealm %s" % res['realms']) tokenrealm = None if res['realms']: tokenrealm = res.get('realms')[0] log.info("[loadtokens] initialize token. serial: %s, realm: %s" % (serial, tokenrealm)) init_param = {'serial':serial, 'type':TOKENS[serial]['type'], 'description': "imported", 'otpkey' : TOKENS[serial]['hmac_key'], 'otplen' : TOKENS[serial].get('otplen'), 'timeStep' : TOKENS[serial].get('timeStep'), 'hashlib' : TOKENS[serial].get('hashlib')} # add additional parameter for vasco tokens if TOKENS[serial]['type'] == "vasco": init_param['vasco_appl'] = TOKENS[serial]['tokeninfo'].get('application') init_param['vasco_type'] = TOKENS[serial]['tokeninfo'].get('type') init_param['vasco_auth'] = TOKENS[serial]['tokeninfo'].get('auth') # add ocrasuite for ocra tokens, only if ocrasuite is not empty if TOKENS[serial]['type'] == 'ocra': if TOKENS[serial].get('ocrasuite', "") != "": init_param['ocrasuite'] = TOKENS[serial].get('ocrasuite') if hashlib and hashlib != "auto": init_param['hashlib'] = hashlib try: if tokenrealm: checkPolicyPre('admin', 'loadtokens', { 'tokenrealm' : tokenrealm } ) except PolicyException as pe: log.error("[loadtokens] Failed checking policy: %s" % str(pe)) return sendError(response, str(pe), 1) (ret,tokenObj) = initToken(init_param ,User('','',''), tokenrealm=tokenrealm) log.info ("[loadtokens] %i tokens imported." % len(TOKENS)) res = { 'value' : True, 'imported' : len(TOKENS) } c.audit['info'] = "%s, %s (imported: %i)" %(fileType,tokenFile,len(TOKENS)) c.audit['serial'] = ','.join(TOKENS.keys()) logTokenNum() c.audit['success'] = ret except Exception, e: log.error("[loadtokens] failed! %s" % str(e) ) log.error("[loadtokens] %s" % traceback.format_exc()) Session.rollback() #return sendError(response, "%s\n%s" % (str(e), traceback.format_exc()) ) return sendErrorMethod(response, str(e) ) try: Session.commit() except Exception, e : log.error('[loadtokens] commit failed') Session.rollback() return sendErrorMethod(response,"Commit failed: " + str(e),0) Session.close() return sendResultMethod(response,res)
[docs] def testresolver(self): """ method: admin/testresolver description: This method tests a useridresolvers configuration arguments: type - "LDAP": depending on the type there are other parameters: - "SQL" LDAP: BINDDN BINDPW LDAPURI TIMEOUT LDAPBASE LOGINNAMEATTRIBUTE LDAPSEARCHFILTER LDAPFILTER USERINFO LDAPSEARCHFILTER SIZELIMIT NOREFERRALS SQL: Driver Server Port Database User Password Table returns: a json result with a boolean "result": true exception: if an error occurs an exception is serialized and returned """ res = {} count = 0 description = "testresolver: parameters are\ type=LDAP \ and others.\ " param = getLowerParams(request.params) try: type = getParam(param, "type", required) log.debug("[testresolver] testing resolver of type %s" % type) if type == "ldap": import useridresolveree.LDAPIdResolver param['BINDDN']=getParam(param,"ldap_binddn",required) param['BINDPW']=getParam(param,"ldap_password",required) param['LDAPURI']=getParam(param,"ldap_uri",required) param['TIMEOUT']=getParam(param,"ldap_timeout",required) param['LDAPBASE']=getParam(param,"ldap_basedn",required) param['LOGINNAMEATTRIBUTE']=getParam(param,"ldap_loginattr",required) param['LDAPSEARCHFILTER']=getParam(param,"ldap_searchfilter",required) param['LDAPFILTER']=getParam(param,"ldap_userfilter",required) param['USERINFO']=getParam(param,"ldap_mapping",required) param['SIZELIMIT']=getParam(param,"ldap_sizelimit",required) param['NOREFERRALS']=getParam(param,"noreferrals",optional) (success, desc) = useridresolveree.LDAPIdResolver.testconnection(param) res['result']=success res['desc']=desc elif type == "sql": import useridresolveree.SQLIdResolver param["Driver"]=getParam(param,"sql_driver",required) param["Server"]=getParam(param,"sql_server",required) param["Port"]=getParam(param,"sql_port",required) param["Database"]=getParam(param,"sql_database",required) param["User"]=getParam(param,"sql_user",required) param["Password"]=getParam(param,"sql_password",required) param["Table"]=getParam(param,"sql_table",required) param["Where"]=getParam(param,"sql_where",optional) num = useridresolveree.SQLIdResolver.testconnection(param) res['result']=True res['rows']=num except Exception, e: Session.rollback() return sendError(response,e,1) return sendResult(response,res)