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 deleteToken(self): # some DBs (eg. DB2) run in deadlock, if the TokenRealm entry # is deleteted via foreign key relation # so we delete it explicit Session.query(TokenRealm).filter(TokenRealm.token_id == self.privacyIDEATokenId).delete() Session.delete(self) return True
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 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 get_resolver_list(self, action, **params): res = {} try: from privacyidea.config.environment import get_resolver_list as getlist list = getlist() res['resolverlist'] = [l for l in list] res['resolvertypes'] = [l.split(".")[-1] for l in list] return sendResult(response, res, 1) except Exception as exx: Session.rollback() return sendError(response, exx) finally: Session.close()
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 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 __before__(self, action, **params): ''' Here we see, what action is to be called and check the authorization ''' try: c.audit['success'] = False c.audit['client'] = get_client() self.Policy = PolicyClass(request, config, c, get_privacyIDEA_config(), token_type_list = get_token_type_list()) if action != "check_t": self.before_identity_check(action) return response except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.error("%r webob.exception %r" % (action, acc)) log.error(traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as exx: log.error("%r exception %r" % (action, exx)) log.error(traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: pass
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 __before__(self, action, **params): try: c.audit['client'] = get_client() self.before_identity_check(action) except Exception as exx: log.error("%r exception %r" % (action, exx)) log.error(traceback.format_exc()) Session.rollback() return sendError(response, exx, context='before') 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 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 get_options(machine_id=None, token_id=None, application=None, machinetoken_id=None): """ returns a dictionary of the options for a given tuple of machine, token and application from the table MachineTokenOptions. :param machine_id: id of the machine :param token_id: id ot the token :param application: name of the application :param machinetoken_id: id of the machineToken-entry :return: option dictionary You either need to specify (machine_ind, token_id, application) or the machinetoken_id. """ options = {} if machinetoken_id: sqlquery = Session.query(MachineTokenOptions).\ filter(MachineTokenOptions.machinetoken_id == machinetoken_id) for option in sqlquery: options[option.mt_key] = option.mt_value elif (machine_id and token_id and application): raise NotImplementedError("the tuple machine_id, token_id, " "application is not implemented, yet.") else: raise Exception("You either need to specify the machinetoken_id" "or the tuple token_id, machine_id, application.") return options
def __before__(self, action, **params): try: c.audit['client'] = get_client() self.Policy = PolicyClass(request, config, c, get_privacyIDEA_config(), token_type_list = get_token_type_list()) return response 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 __before__(self, action, **params): try: c.version = get_version() c.licenseinfo = get_copyright_info() self.set_language() except Exception as exx: log.error("%r exception %r" % (action, exx)) log.error(traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: pass
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 get_token_in_realm(realm, active=True): ''' This returns the number of tokens in one realm. You can either query only active token or also disabled tokens. ''' if active: sqlQuery = Session.query(TokenRealm, Realm, Token).filter(and_( TokenRealm.realm_id == Realm.id, Realm.name == u'' + realm, Token.privacyIDEAIsactive == True, TokenRealm.token_id == Token.privacyIDEATokenId)).count() else: sqlQuery = Session.query(TokenRealm, Realm).filter(and_( TokenRealm.realm_id == Realm.id, Realm.name == realm)).count() return sqlQuery
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 _get_machinetoken_id(machine_id, token_id, application): r = None sqlquery = Session.query(MachineToken.id)\ .filter(and_(MachineToken.token_id == token_id, MachineToken.machine_id == machine_id, MachineToken.application == application)) for row in sqlquery: r = row.id return r
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 set_config(key, value, typ, description=None): ''' create an intial config entry, if it does not exist :param key: the key :param value: the value :param description: the description of the key :return: nothing ''' count = Session.query(model.Config).filter( model.Config.Key == "privacyidea." + key).count() if count == 0: config_entry = model.Config(key, value, Type=typ, Description=description) Session.add(config_entry) return
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 _removeConfigDB(key): if (not key.startswith("privacyidea.")): if not key.startswith('encprivacyidea.'): key = u"privacyidea." + key confEntries = Session.query(Config).filter(Config.Key == unicode(key)) num = confEntries.count() if num == 1: theConf = confEntries[0] try: #Session.add(theConf) Session.delete(theConf) except Exception as e: log.error('failed') raise ConfigAdminError("remove Config failed for %r: %r" % (key, e), id=1133) return num
def delete_challenges(self, challenges): ''' delete challenges, which match those listed ones :param challenges: list of (dict|int|str) challenges :return: result of the delete operation ''' challenge_ids = [] for challenge in challenges: if type(challenge) == dict: if challenge.has_key('id'): challenge_id = challenge.get('id') elif type(challenge) == Challenge: challenge_id = challenge.get('id') elif type(challenge) in (unicode , str , int): challenge_id = challenge try: challenge_ids.append(int(challenge_id)) except ValueError: ## ignore LOG.warning("failed to concert the challengeId %r to int()" % challenge_id) res = 1 # 1. get all challeges which are to be deleted # 2. self.token.select_challenges() if len(challenge_ids) > 0: del_challes = Session.query(Challenge).\ filter(Challenge.tokenserial == u'' + self.token.getSerial()).\ filter(Challenge.id.in_(challenge_ids)).all() for dell in del_challes: Session.delete(dell) #pass return res
def deloption(mtid=None, name=None, serial=None, application=None, key=None): """ delete option from a machine token definition :param mtid: id of the machinetoken :param name: the machine name :param serial: the serial number of the token :param app: the application """ if not mtid: mtid = _get_machinetoken_id(_get_machine_id(name), _get_token_id(serial), application) num = Session.query(MachineTokenOptions).\ filter(and_(MachineTokenOptions.machinetoken_id == mtid, MachineTokenOptions.mt_key == key)).delete() Session.commit() return num == 1
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 setup_app(conf, conf_global=None, unitTest=False): ''' setup_app is the hook, which is called, when the application is created :param conf: the application configuration :return: - nothing - ''' if conf_global is not None: if "sqlalchemy.url" in conf_global: log.info("sqlalchemy.url") else: conf.get("sqlalchemy.url", None) if unitTest is True: log.info("Deleting previous tables...") meta.metadata.drop_all(bind=meta.engine) # Create the tables if they don't already exist log.info("Creating tables...") meta.metadata.create_all(bind=meta.engine) if "privacyideaSecretFile" in conf: filename = conf.get("privacyideaSecretFile") try: with open(filename): pass except IOError: log.warning("The privacyIDEA Secret File could not be found " + "-creating a new one: %s" % filename) f_handle = open(filename, 'ab+') secret = os.urandom(32 * 5) f_handle.write(secret) f_handle.close() os.chmod(filename, 0400) log.info("privacyideaSecretFile: %s" % filename) set_defaults() Session.commit() log.info("Successfully set up.")
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 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)