def __before__(self, action, **params): ''' ''' try: c.audit['success'] = False c.audit['client'] = get_client() self.Policy = PolicyClass(request, config, c, get_privacyIDEA_config(), tokenrealms=request.params.get('serial'), token_type_list=get_token_type_list()) self.set_language() self.before_identity_check(action) Session.commit() return request except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.info("%r: webob.exception %r" % (action, acc)) log.info(traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as exx: log.error("exception %r" % (action, exx)) log.error(traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: pass
def delete(self, action, **params): ''' Delete an existing client machine entry :param name: the unique name of the machine :return: value is either true (success) or false (fail) ''' try: res = {} param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'delete') param.update(request.params) machine_name = getParam(param, "name", required) res = delete_machine(machine_name) Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def getResolvers(self, action, **params): """ method: system/getResolvers descriptions: returns a json list of all useridresolvers arguments: returns: a json result with a list of all available resolvers exception: if an error occurs an exception is serialized and returned """ res = {} try: res = getResolverList() c.audit['success'] = True Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("error getting resolvers: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def show(self, action, **params): ''' Returns a list of the client machines. :param name: Optional parameter to only show this single machine :return: JSON details ''' try: res = {} param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'show') param.update(request.params) machine_name = getParam(param, "name", optional) res = show_machine(machine_name) Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def delResolver(self, action, **params): """ method: system/delResolver description: this function deletes an existing resolver All config keys of this resolver get deleted arguments: resolver - the name of the resolver to delete. returns: success state exception: if an error occurs an exception is serialized and returned """ res = {} try: param = getLowerParams(request.params) resolver = getParam(param, "resolver", required) ### only delete a resolver, if it is not used by any realm found = False fRealms = [] realms = getRealms() for realm in realms: info = realms.get(realm) reso = info.get('useridresolver') for idRes in reso: if resolver == get_resolver_name(idRes): fRealms.append(realm) found = True if found == True: c.audit['failed'] = res err = 'Resolver %r still in use by the realms: %r' % \ (resolver, fRealms) c.audit['info'] = err raise Exception('%r !' % err) res = deleteResolver(resolver) c.audit['success'] = res c.audit['info'] = resolver Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("error deleting resolver: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def setResolver(self, action, **params): """ method: system/setResolver description: creates or updates a useridresolver arguments: name - the name of the resolver type - the type of the resolver [ldapsersolver, sqlresolver] LDAP: LDAPURI LDAPBASE BINDDN BINDPW TIMEOUT SIZELIMIT LOGINNAMEATTRIBUTE LDAPSEARCHFILTER LDAPFILTER USERINFO NOREFERRALS - True|False SQL: Database Driver Server Port User Password Table Map returns: a json result with the found value exception: if an error occurs an exception is serialized and returned """ res = {} param = {} try: param.update(request.params) res = defineResolver(param) Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("error saving config: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def delConfig(self, action, **params): """ delete a configuration key * if an error occurs an exception is serializedsetConfig and returned :param key: configuration key name :returns: a json result with the deleted value """ res = {} try: param = getLowerParams(request.params) key = getParam(param, "key", required) ret = removeFromConfig(key) string = "delConfig " + key res[string] = ret c.audit['success'] = ret c.audit['info'] = key Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("error deleting config: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def __after__(self, action, **params): ''' ''' params = {} try: params.update(request.params) c.audit['administrator'] = getUserFromRequest(request).get("login") if 'serial' in params: c.audit['serial'] = request.params['serial'] c.audit['token_type'] = getTokenType(params.get('serial')) self.audit.log(c.audit) Session.commit() return request except Exception as e: log.error("unable to create a session cookie: %r" % e) log.error(traceback.format_exc()) Session.rollback() return sendError(response, e, context='after') finally: Session.close()
def deltoken(self, action, **params): ''' delete a token and a application from a machine :param name: Name of the machine :param serial: serial number of the token :param application: name of the application ''' try: res = False param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'deltoken') param.update(request.params) machine_name = getParam(param, "name", required) serial = getParam(param, "serial", required) application = getParam(param, "application", required) res = deltoken(machine_name, serial, application) Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0)
def check_yubikey(self, action, **params): ''' This function is used to validate the output of a yubikey method: validate/check_yubikey :param pass: The password that consist of the static yubikey prefix and the otp :type pass: string :return: JSON Object returns: JSON response:: { "version": "privacyIDEA 2.4", "jsonrpc": "2.0", "result": { "status": true, "value": false }, "detail" : { "username": username, "realm": realm }, "id": 0 } ''' param = request.params passw = getParam(param, "pass", required) try: ok = False try: ok, opt = checkYubikeyPass(passw) c.audit['success'] = ok except AuthorizeException as exx: log.warning("authorization failed for validate/check_yubikey: %r" % exx) c.audit['success'] = False c.audit['info'] = unicode(exx) ok = False Session.commit() return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.error("validate/check_yubikey failed: %r" % exx) log.error(traceback.format_exc()) c.audit['info'] = unicode(exx) Session.rollback() return sendError(response, u"validate/check_yubikey failed: %s" % unicode(exx), 0) finally: Session.close()
def addtoken(self, action, **params): ''' Add a token and a application to a machine :param name: Name of the machine :param serial: serial number of the token :param application: name of the application :param option_*: parameter is passed as additional option to the machinetoken to be stored in machine_t_options table. In case of LUKS application this can be "option_slot" ''' try: res = False param = {} options = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'addtoken') param.update(request.params) machine_name = getParam(param, "name", required) serial = getParam(param, "serial", required) application = getParam(param, "application", required) if application.lower() not in config.get("applications").keys(): log.error("Unknown application %r. Available applications: " "%r" % (application, config.get("applications").keys())) raise Exception("Unkown application!") for p in param.keys(): if p.startswith("option_"): options[p] = param.get(p) mt = addtoken(machine_name, serial, application, options=options) if mt: res = True Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: # pragma: no cover log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def setRealm(self, action, **params): """ method: system/setRealm description: this function is used to define a realm with the given useridresolvers arguments: realm - name of the realm resolvers - comma seperated list of resolvers, that should be in this realm returns: a json result with a list of Realms exception: if an error occurs an exception is serialized and returned """ res = False err = "" realm = "" param = {} try: param.update(request.params) realm = getParam(param, "realm", required) resolvers = getParam(param, "resolvers", required) realm_resolvers = [] for resolver in resolvers.split(','): # check resolver returns the correct resolver description (res, realm_resolver) = checkResolverType(resolver) if res is False: raise Exception("Error in resolver %r please check the" " logfile!" % resolver) realm_resolvers.append(realm_resolver) resolvers = ",".join(realm_resolvers) res = setRealm(realm, resolvers) c.audit['success'] = res c.audit['info'] = "realm: %r, resolvers: %r" % (realm, resolvers) Session.commit() return sendResult(response, res, 1) except Exception as exx: err = ("Failed to set realm with %r " % param) log.error("%r %r" % (err, exx)) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def addoption(self, action, **params): ''' Add an option to a machinetoken definition :param mtid: id of the machine token definition :param name: machine_name :param serial: serial number of the token :param application: application :param option_*: name of the option. In case of LUKS application this can be "option_slot" You either need to provide the machine-token-id (mtid) directly or you need to provide the tuple (name, serial, application) ''' try: num = -1 param = {} options = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'addtoken') param.update(request.params) mtid = getParam(param, "mtid", optional) machine_name = getParam(param, "name", optional) serial = getParam(param, "serial", optional) application = getParam(param, "application", optional) if not (mtid or (machine_name and serial and application)): raise ParameterError("You need to specify either mtid or" "the tuple name, serial, application", id=201) for p in param.keys(): if p.startswith("option_"): options[p] = param.get(p) num = addoption(mtid, name=machine_name, serial=serial, application=application, options=options) Session.commit() c.audit["success"] = True return sendResult(response, num, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: # pragma: no cover log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def __init__(self, machinetoken_id, key, value): log.debug("setting %r to %r for MachineToken %s" % (key, value, machinetoken_id)) self.machinetoken_id = machinetoken_id self.mt_key = key self.mt_value = value Session.add(self) Session.commit()
def __init__(self, machineuser_id, key, value): log.debug("setting %r to %r for MachineUser %s" % (key, value, machineuser_id)) self.machineuser_id = machineuser_id self.mu_key = key self.mu_value = value Session.add(self) Session.commit()
def getRealms(self, action, **params): ''' method: system/getRealms description: returns all realm definitinos as a json result. arguments: returns: a json result with a list of Realms exception: if an error occurs an exception is serialized and returned Either the admin has the policy scope=system, action=read or he is rights in scope=admin for some realms. If he does not have the system-read-right, then he will only see the realms, he is admin of. ''' ### config settings from here try: param = getLowerParams(request.params) res = getRealms() c.audit['success'] = True # If the admin is not allowed to see all realms, (policy scope=system, action=read) # the realms, where he has no administrative rights need, to be stripped. polPost = self.Policy.checkPolicyPost('system', 'getRealms', { 'realms' : res }) res = polPost['realms'] Session.commit() return sendResult(response, res, 1) except PolicyException as pex: log.error("policy exception: %r" % pex) log.error(traceback.format_exc()) Session.rollback() return sendError(response, pex) except Exception as exx: log.error("error getting realms: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def deltoken(machine_name, serial, application): machine_id = _get_machine_id(machine_name) token_id = _get_token_id(serial) num = Session.query(MachineToken).\ filter(and_(MachineToken.token_id == token_id, MachineToken.machine_id == machine_id, MachineToken.application == application)).delete() Session.commit() # 1 -> success return num == 1
def deloption(self, action, **params): ''' Delete an option from a machinetoken definition :param mtid: id of the machine token definition :param name: machine_name :param serial: serial number of the token :param application: application :param key: key of the option to delete You either need to provide the machine-token-id (mtid) directly or you need to provide the tuple (name, serial, application) ''' try: num = -1 param = {} options = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'deltoken') param.update(request.params) mtid = getParam(param, "mtid", optional) machine_name = getParam(param, "name", optional) serial = getParam(param, "serial", optional) option_key = getParam(param, "key", required) application = getParam(param, "application", optional) if not (mtid or (machine_name and serial and application)): raise ParameterError("You need to specify either mtid or" "the tuple name, serial, application", id=201) num = deloption(mtid, name=machine_name, serial=serial, application=application, key=option_key) Session.commit() c.audit["success"] = True return sendResult(response, num, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: # pragma: no cover log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def delete(name): ''' Delete the machine with the name and return the number of deleted machines Should always be 1 Should be 0 if such a machine did not exist. ''' mid = _get_machine_id(name) _assigns = Session.query(MachineToken)\ .filter(MachineToken.machine_id == mid).delete() num = Session.query(Machine).filter(Machine.cm_name == name).delete() Session.commit() # 1 -> success return num == 1
def showtoken(self, action, **params): ''' show a token and a application from a machine This function is used in the flexigrid management :param name: Name of the machine :param serial: serial number of the token :param application: name of the application :param flexi: if set to 1, we do return flexigrid input ''' try: res = False param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'showtoken') param.update(request.params) machine_name = getParam(param, "name", optional) serial = getParam(param, "serial", optional) application = getParam(param, "application", optional) # if set, this should be returned for flexigrid flexi = getParam(param, "flexi", optional) res = showtoken(machine_name, serial, application, flexi=flexi, params=param) Session.commit() c.audit["success"] = True if flexi: response.content_type = 'application/json' return json.dumps(res, indent=3) else: return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: # pragma: no cover log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def create(self, action, **params): ''' Create a new client machine entry :param name: the unique name of the machine (required). Can be the FQDN. :param desc: description of the machine :param ip: The IP address of the machine (required) :param decommission: A date when the machine will not be valid anymore :return: True or False if the creation was successful. ''' try: res = False param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'create') param.update(request.params) machine_name = getParam(param, "name", required) ip = getParam(param, "ip", required) desc = getParam(param, "desc", optional) decommission = getParam(param, "decommission", optional) machine = create_machine(machine_name, ip=ip, desc=desc, decommission=decommission) if machine: res = True Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: # pragma: no cover log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def login(self, action): log.debug("privacyidea login screen") # referrer and path_url to check if the login failed. referrer = request.referrer path_url = request.path_url identity = request.environ.get('repoze.who.identity') if identity is not None: # After login we either redirect to the manage interface or # selfservice if is_admin_identity(identity, exception=False): redirect("/manage/") else: redirect("/") res = {} try: c.defaultRealm = getDefaultRealm() res = getRealms() c.realmArray = ["admin"] for (k, _v) in res.items(): c.realmArray.append(k) c.realmbox = getRealmBox() log.debug("displaying realmbox: %i" % int(c.realmbox)) c.login_help = get_login_help() c.status = "" if referrer == path_url: # We come from the login page, so obviously we # have entered a wrong password! c.status = _("Wrong credentials.") Session.commit() response.status = '%i Logout from privacyIDEA selfservice' %\ LOGIN_CODE return render('/selfservice/login.mako') except Exception as e: log.error('failed %r' % e) log.error(traceback.format_exc()) Session.rollback() return sendError(response, e) finally: Session.close()
def save(self): ''' enforce the saveing of a challenge - will guarentee the uniqness of the transaction id :return: transaction id of the stored challeng ''' try: Session.add(self) Session.commit() log.debug('save challenge : success') except Exception as exce: log.error('Error during saving challenge: %r' % exce) log.error("%s" % traceback.format_exc()) return self.transid
def autosms(self): ''' This function is used to test the autosms policy method: testing/autosms arguments: user - username / loginname realm - additional realm to match the user to a useridresolver returns: JSON response ''' log.debug('[autosms]') param = request.params try: if isSelfTest() is False: Session.rollback() return sendError(response, "The testing controller can " "only be used in SelfTest mode!", 0) _user = getUserFromParam(param, required) Policy = PolicyClass(request, config, c, get_privacyIDEA_config()) ok = Policy.get_auth_AutoSMSPolicy() Session.commit() return sendResult(response, ok, 0) except Exception as e: log.error("[autosms] validate/check failed: %r", e) log.error("[autosms] %s" % traceback.format_exc()) Session.rollback() return sendError(response, "validate/check failed:" + unicode(e), 0) finally: Session.close() log.debug('[autosms] done')
def getActivationCode(self, action, **params): ''' method: orcra/getActivationCode description: returns an valid example activcation code arguments: ./. returns: JSON with "activationcode": "JZXW4ZI=2A" ''' from privacyidea.lib.crypto import createActivationCode res = {} #description = 'ocra/getActivationCode' try: params = getLowerParams(request.params) self.Policy.checkPolicyPre('ocra', "activationcode") ac = str(params.get('activationcode')) activationCode = createActivationCode(acode=ac) res = {'activationcode':activationCode} Session.commit() return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def getPolicyDef(self, action, **params): ''' method: system/getPolicyDef description: This is a helper function that returns the POSSIBLE policy definitions, that can be used to define your policies. arguments: scope - optional - if given, the function will only return policy definitions for the given scope. returns: the policy definitions of - allowed scopes - allowed actions in scopes - type of actions exception: if an error occurs an exception is serialized and returned ''' pol = {} try: param = getLowerParams(request.params) log.debug("getting policy definitions: %r" % param) scope = getParam(param, "scope", optional) pol = get_policy_definitions(scope) dynpol = self._add_dynamic_tokens(scope) pol.update(dynpol) c.audit['success'] = True c.audit['info'] = scope Session.commit() return sendResult(response, pol, 1) except Exception as exx: log.error("error getting policy definitions: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def setDefaultRealm(self, action, **params): """ method: system/setDefaultRealm description: this function sets the given realm to the default realm arguments: realm - the name of the realm, that should be the default realm returns: a json result with a list of Realms exception: if an error occurs an exception is serialized and returned """ res = False try: param = getLowerParams(request.params) defRealm = getParam(param, "realm", optional) if defRealm is None: defRealm = "" defRealm = defRealm.lower().strip() res = setDefaultRealm(defRealm) if res == False and defRealm != "" : c.audit['info'] = "The realm %s does not exist" % defRealm c.audit['success'] = True c.audit['info'] = defRealm Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("setting default realm failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()
def deltoken(machine_name, serial, application): """ Delete a machine token. Also deletes the corresponding MachineTokenOptions """ machine_id = _get_machine_id(machine_name) token_id = _get_token_id(serial) mtid = _get_machinetoken_id(machine_id, token_id, application) num = Session.query(MachineToken).\ filter(and_(MachineToken.token_id == token_id, MachineToken.machine_id == machine_id, MachineToken.application == application)).delete() Session.query(MachineTokenOptions).\ filter(MachineTokenOptions.machinetoken_id == mtid).delete() Session.commit() # 1 -> success return num == 1
def addtoken(self, action, **params): ''' Add a token and a application to a machine :param name: Name of the machine :param serial: serial number of the token :param application: name of the application ''' try: res = False param = {} # check machine authorization self.Policy.checkPolicyPre('machine', 'addtoken') param.update(request.params) machine_name = getParam(param, "name", required) serial = getParam(param, "serial", required) application = getParam(param, "application", required) if application.lower() not in config.get("applications").keys(): log.error("Unknown application %r. Available applications: " "%r" % (application, config.get("applications").keys())) raise Exception("Unkown application!") mt = addtoken(machine_name, serial, application) if mt: res = True Session.commit() c.audit["success"] = True return sendResult(response, res, 1) except PolicyException as pe: log.error("policy failed: %r" % pe) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("failed: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close()
def getResolver(self, action, **params): """ method: system/getResolver description: this function retrieves the definition of the resolver arguments: resolver - the name of the resolver returns: a json result with the configuration of a specified resolver exception: if an error occurs an exception is serialized and returned """ res = {} try: param = getLowerParams(request.params) resolver = getParam(param, "resolver", required) if (len(resolver) == 0): raise Exception ("[getResolver] missing resolver name") res = getResolverInfo(resolver) c.audit['success'] = True c.audit['info'] = resolver Session.commit() return sendResult(response, res, 1) except Exception as exx: log.error("error getting resolver: %r" % exx) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx) finally: Session.close()