Ejemplo n.º 1
0
    def check_encryption(self):
        """
        check if a value, which got written into config, got encrypted
        :return:
        """
        test_key = 'linotp.testkey'

        linotp_conf = LinOtpConfig()

        if test_key not in linotp_conf:
            storeConfig(test_key, '', typ='password', desc=None)

        old_value = getFromConfig(test_key, defVal=None)

        now = datetime.datetime.now()
        new_value_plain = unicode(now)

        storeConfig(test_key, new_value_plain, typ='password', desc=None)

        new_value_enc = getFromConfig(test_key, defVal=None)

        # if new_value_enc != old_value: something new was written into db
        # if new_value_enc != new_value_plain: the new value got encrypted
        if new_value_enc and new_value_plain != new_value_enc != old_value:
            return True

        return False
Ejemplo n.º 2
0
    def check_encryption(self):
        """
        check if a value, which got written into config, got encrypted
        :return:
        """
        test_key = 'linotp.testkey'

        linotp_conf = LinOtpConfig()

        if test_key not in linotp_conf:
            storeConfig(test_key, '', typ='password', desc=None)

        old_value = getFromConfig(test_key, defVal=None)

        now = datetime.datetime.now()
        new_value_plain = unicode(now)

        storeConfig(test_key, new_value_plain, typ='password', desc=None)

        new_value_enc = getFromConfig(test_key, defVal=None)

        # if new_value_enc != old_value: something new was written into db
        # if new_value_enc != new_value_plain: the new value got encrypted
        if new_value_enc and new_value_plain != new_value_enc != old_value:
            return True

        return False
Ejemplo n.º 3
0
def setProvider(params):
    """
    save the provider info in linotp config

    :param params: generic parameter dictionary to support later more complex
                   provider definitions
                   in the dictionary currently required keys are
                   :param type: push,sms or email
                   :param name: the provider name
                   :param config: the provider config
                   :param timeout: the provider timeout
                   :param: default: boolean

    :return: success - boolean
    """

    provider_type = params['type']
    provider_name = params['name']

    if provider_name == Legacy_Provider_Name:
        save_legacy_provider(provider_type, params)
    else:
        save_new_provider(provider_type, provider_name, params)

    if 'default' in params:
        default_provider_key = Default_Provider_Key[provider_type]
        if params['default'] is True or params['default'].lower() == 'true':
            storeConfig(key=default_provider_key, val=provider_name)

    # uncomment this if you want to get provider config as ini file:
    # from linotp.provider.create_provider_ini import create_provider_config
    # create_provider_config()

    return True, {}
Ejemplo n.º 4
0
def setProvider(params):
    """
    save the provider info in linotp config

    :param params: generic parameter dictionary to support later more complex
                   provider definitions
                   in the dictionary currently required keys are
                   :param type: push,sms or email
                   :param name: the provider name
                   :param config: the provider config
                   :param timeout: the provider timeout
                   :param: default: boolean

    :return: success - boolean
    """

    provider_type = params['type']
    provider_name = params['name']

    if provider_name == Legacy_Provider_Name:
        save_legacy_provider(provider_type, params)
    else:
        save_new_provider(provider_type, provider_name, params)

    if 'default' in params:
        default_provider_key = Default_Provider_Key[provider_type]
        if params['default'] is True or params['default'].lower() == 'true':
            storeConfig(key=default_provider_key, val=provider_name)

    # uncomment this if you want to get provider config as ini file:
    # from linotp.provider.create_provider_ini import create_provider_config
    # create_provider_config()

    return True, {}
Ejemplo n.º 5
0
def setSupportLicenseInfo(lic_dict, lic_sign):
    """
    set the license to be the current one

    :param lic_dict: the license with description
    :param lic_sign: the license signature
    :return: tuple with status (boolean) and if an error occured, the reason
    """

    verifyLicenseInfo(lic_dict, lic_sign, raiseException=True)

    lic_str = lic_dict.info()
    log.debug("[setSupportLicense] license %r", lic_str)

    licTemp = "-----BEGIN LICENSE-----\n"
    licTemp += lic_str
    licTemp += "-----END LICENSE-----\n"
    licTemp += "-----BEGIN LICENSE SIGNATURE-----\n"
    licTemp += base64.b64encode(lic_sign)
    licTemp += "\n-----END LICENSE SIGNATURE-----"

    storeConfig("license", binascii.hexlify(licTemp))
    log.info("[setLicense] license saved!")

    return True
Ejemplo n.º 6
0
def setSupportLicenseInfo(lic_dict, lic_sign):
    """
    set the license to be the current one

    :param lic_dict: the license with description
    :param lic_sign: the license signature
    :return: tuple with status (boolean) and if faild, the reason
    """

    verifyLicenseInfo(lic_dict, lic_sign, raiseException=True)

    lic_str = lic_dict.info()
    log.debug("[setSupportLicense] license %r", lic_str)

    licTemp = "-----BEGIN LICENSE-----\n"
    licTemp += lic_str
    licTemp += "-----END LICENSE-----\n"
    licTemp += "-----BEGIN LICENSE SIGNATURE-----\n"
    licTemp += base64.b64encode(lic_sign)
    licTemp += "\n-----END LICENSE SIGNATURE-----"

    storeConfig("license", binascii.hexlify(licTemp))
    log.info("[setLicense] license saved!")

    return True
Ejemplo n.º 7
0
def setSupportLicenseInfo(lic_dict, lic_sign):
    """
    set the license to be the current one

    :param lic_dict: the license with description
    :param lic_sign: the license signature
    :return: tuple with status (boolean) and if faild, the reason
    """

    verifyLicenseInfo(lic_dict, lic_sign, raiseException=True)

    # first set the duration if there is one
    if not set_duration(lic_dict, raiseException=True):
        return False

    lic_str = lic_dict.info()
    log.debug("Setting licence to %r", lic_str)

    licTemp = "-----BEGIN LICENSE-----\n"
    licTemp += lic_str
    licTemp += "-----END LICENSE-----\n"
    licTemp += "-----BEGIN LICENSE SIGNATURE-----\n"
    licTemp += base64.b64encode(lic_sign).decode()
    licTemp += "\n-----END LICENSE SIGNATURE-----"

    storeConfig("license", binascii.hexlify(licTemp.encode('utf-8')).decode())
    log.info("License saved.")

    return True
Ejemplo n.º 8
0
def save_new_provider(provider_type, provider_name, params):
    """
    save the provider in the new provider format

    remarks:
        alternative to storing the whole config in encrypted way, we
        might look if it's a json and store the next Config.  level
        and look for the reserved additional appended type: encrypted_data

    :param provider_type: push, sms or email provider
    :param provider_name: the name of the provider
    :param params: the provider description dict with 'class', 'config',
                   and 'timeout'

    """

    prefix = Provider_types.get(provider_type, {}).get('prefix')
    if not prefix:
        raise Exception('unknown provider type %r' % provider_type)

    provider_prefix = prefix + provider_name

    storeConfig(key=provider_prefix, val=params['class'])

    config_mapping = {
        'timeout': ('Timeout', None),
        'config': ('Config', 'encrypted_data')}

    #
    # alternative config entries are supported by the the adjustable config
    # entries if the provider supports the 'getConfigMapping' interface:
    #
    try:
        provider_class = _load_provider_class(params['class'])
        config_mapping = provider_class.getConfigMapping()
    except AttributeError as exx:
        log.debug("provider %r does not support ConfigMapping: %r",
                  provider_name, exx)

    # add the extra parameter for each resolver that it could be a managed one

    config_mapping['managed'] = ('Managed', None)

    for config_entry in list(config_mapping.keys()):

        if config_entry not in params:
            continue

        # get the mapping entry and split the config name and type
        mapping_entry = config_mapping[config_entry]
        config_key, config_type = mapping_entry

        value = params[config_entry]

        # store the config entry
        storeConfig(key=provider_prefix + '.' + config_key,
                    val=value,
                    typ=config_type)

    return True, {}
Ejemplo n.º 9
0
def set_duration(lic_dict, raiseException=False):
    """
    set the duration value in linotp config and thus in config database

    :param lic_dict: the license info object
    :param raiseException: switch to control if an exception should be thrown
           in case of a problem
    """
    # if there is no expiration in the license we just can go on
    if not (
        lic_dict.license_expiration and "days" in lic_dict.license_expiration
    ):
        return True

    lic_sign = lic_dict.signature
    days = lic_dict.license_expiration.replace("days", "").strip()
    try:
        days = int(days)
    except ValueError as _val:
        raise LicenseException(
            "Unable to interpret duration in license description"
        )

    # we have a timely limited version, so we have to check if there is
    # already a license like this installed by comparing the signatures
    date_format = "%d%m%y"

    # get the decrypted value from the config, if there is one
    expiration = _get_license_duration()

    if expiration:
        # fetch config and split the signature and the expiration date
        signature, _sep, _date_str = expiration.rpartition(":")

        # here we only verify that the license signature is not the same
        # - we only take a slice as the stored signature will be
        #   stored in an encrypted way and then will become too long
        if base64.b64encode(lic_sign)[:500] == signature:
            error = _("License already installed!")
            if raiseException:
                raise LicenseException(error)
            else:
                log.error(error)
                return False

    # so we calculate the expiration and store this together
    # with the license signature
    expires = datetime.datetime.now() + datetime.timedelta(days=days)
    expires_str = expires.strftime(date_format)

    # we take only some bytes as it is encrypted afterwards
    signature = base64.b64encode(lic_sign)[:500].decode()
    license_expire = "%s:%s" % (signature, expires_str)

    enc_license_expire = EncryptedData.from_unencrypted(license_expire)
    storeConfig("license_duration", enc_license_expire)
    log.info("Set license expiration to %s", license_expire)

    return True
Ejemplo n.º 10
0
def set_duration(lic_dict, raiseException=False):
    """
    set the duration value in linotp config and thus in config database

    :param lic_dict: the license info object
    :param raiseException: switch to control if an exception should be thrown
           in case of a problem
    """

    # if there is no expiration in the license we just can go on
    if not (lic_dict.license_expiration and
            'days' in lic_dict.license_expiration):
        return True

    lic_sign = lic_dict.signature
    days = lic_dict.license_expiration.replace('days', '').strip()
    try:
        days = int(days)
    except ValueError as _val:
        raise Exception('Unable to interpret duration in'
                        ' license description')

    # we have a timely limited version, so we have to check if there is
    # already a license like this installed by comparing the signatures
    date_format = "%d%m%y"

    # get the decrypted value from the config, if there is one
    expiration = getFromConfig('enclinotp.license_duration', None)
    if expiration:
        # fetch config and split the signature and the expiration date
        signature, _sep, _date_str = expiration.rpartition(':')

        # here we only verify that the license signature is not the same
        # - we only take a slice as the stored signature will be
        #   stored in an encrypted way and then will become too long
        if base64.b64encode(lic_sign)[:500] == signature:
            error = _('License already installed!')
            if raiseException:
                raise Exception(error)
            else:
                log.error(error)
                return False

    # so we calculate the expiration and store this together
    # with the license signature
    expires = datetime.datetime.now() + datetime.timedelta(days=days)
    expires_str = expires.strftime(date_format)

    # we take only some bytes as it is encrypted afterwards
    signature = base64.b64encode(lic_sign)[:500]
    license_expire = "%s:%s" % (signature, expires_str)

    storeConfig("license_duration", license_expire, typ='password')
    log.info("license_expiration %s" % license_expire)


    return True
Ejemplo n.º 11
0
def do_nagging(lic_info, nag_days=7):
    """
    do nagging - answer the question if nagging should be done

    :param lic_info: the license info
    :return: boolean - True if nagging should be displayed
    """
    d_fmt = "%Y-%m-%d"

    # we start 7 days after download license was installed
    nag_offset = nag_days

    if not (
        lic_info.license_type
        and (
            lic_info.license_type == "download"
            or lic_info.license_type == "demo"
        )
    ):
        return False

    # in case there is no duration definition in 'xx days' we do the nagging
    if not lic_info.license_expiration:
        log.error(
            "Download license format error: Missing expiration definition!"
        )
        return True

    now_date = datetime.datetime.now().date()

    expire = get_expiration_date(lic_info)
    expire_date = datetime.datetime.strptime(expire, d_fmt).date()

    # calculate back, when the license was enrolled
    duration = int(lic_info.license_expiration.replace("days", "").strip())
    lic_start_date = expire_date - datetime.timedelta(days=duration)

    # calulate the nagging start date with given nag_offset
    nag_start_date = lic_start_date + datetime.timedelta(days=nag_offset)

    if now_date <= nag_start_date:
        return False

    # ok, we are in the nagging time frame, so start nagging
    last_nagged = getFromConfig("last_nagged")
    if last_nagged:
        # nag only once a day: check, if we nagged already today
        last_nag_date = datetime.datetime.strptime(last_nagged, d_fmt).date()
        # check if we nagged already today
        if last_nag_date >= now_date:
            return False

    datum = now_date.strftime(d_fmt)
    storeConfig("last_nagged", datum, desc="last nagged")

    return True
Ejemplo n.º 12
0
def do_nagging(lic_info):
    """
    do nagging - answer the question if nagging should be done

    :param lic_info: the license info
    :return: boolean - True if nagging should be displayed
    """

    d_fmt = "%Y-%m-%d"

    # we start 20 days after download license was installed
    nag_offset = 20

    if not (lic_info.license_type and lic_info.license_type == 'download'):
        return False

    # in case there is no duration definition in 'xx days' we do the nagging
    if not lic_info.license_expiration:
        log.error("download license format error: "
                  "missing expiration definition!")
        return True

    now_date = datetime.datetime.now().date()

    expire = get_expiration_date(lic_info)
    expire_date = datetime.datetime.strptime(expire, d_fmt).date()

    # calculate back, when the license was enrolled
    duration = int(lic_info.license_expiration.replace('days', '').strip())
    lic_start_date = expire_date - datetime.timedelta(days=duration)

    # calulate the nagging start date with given nag_offset
    nag_start_date = lic_start_date + datetime.timedelta(days=nag_offset)

    if now_date <= nag_start_date:
        return False

    # ok, we are in the nagging time frame, so start nagging
    last_nagged = getFromConfig('last_nagged')
    if last_nagged:
        # nag only once a day: check, if we nagged already today
        last_nag_date = datetime.datetime.strptime(last_nagged, d_fmt).date()
        # check if we nagged already today
        if last_nag_date >= now_date:
            return False

    datum = now_date.strftime(d_fmt)
    storeConfig('last_nagged', datum, desc='last nagged')

    return True
Ejemplo n.º 13
0
def setSupportLicense(licString):
    """
    set the license to be the current one

    :param licString: the license with description and signature
    :return: tuple with status (boolean) and if faild, the reason
    """

    log.debug("[setSupportLicense] license %r", licString)
    valid, msg = isSupportLicenseValid(licString, raiseException=True)

    storeConfig("license", binascii.hexlify(licString))
    log.info("[setLicense] license saved!")

    return (valid, msg)
Ejemplo n.º 14
0
def setSupportLicense(licString):
    """
    set the license to be the current one

    :param licString: the license with description and signature
    :return: tuple with status (boolean) and if faild, the reason
    """

    log.debug("[setSupportLicense] license %r", licString)
    valid, msg = isSupportLicenseValid(licString)

    storeConfig("license", binascii.hexlify(licString))
    log.info("[setLicense] license saved!")

    return (valid, msg)
Ejemplo n.º 15
0
def setPolicy(policy):
    '''
    define and store a policy definition

    :param policy: dict  with the following keys:

          * name
          * action
          * scope
          * realm
          * user
          * time
          * client

    :return: dict with the results of the stored entries
    '''

    ret = {}
    _ = context['translate']

    name = policy.get('name')

    if 'active' not in policy:
        policy['active'] = "True"

    # check that the name does not contain any bad characters
    if not PolicyNameRegex.match(name):
        raise Exception(
            _("The name of the policy may only contain "
              "the characters  a-zA-Z0-9_."))

    # verify the required policy attributes
    required_attributes = ['action', 'scope', 'realm']
    for required_attribute in required_attributes:
        if (required_attribute not in policy
                or not policy[required_attribute]):
            raise PolicyWarning("Missing attribute %s in "
                                "policy %s" % (required_attribute, name))

    # before storing the policy, we have to check the impact:
    # if there is a problem, we will raise an exception with a warning

    _check_policy_impact(**policy)

    # transpose the forwardServer policy action as it might
    # contain sensitive data
    policy["action"] = ForwardServerPolicy.prepare_forward(policy["action"])

    attributes = [
        'action', 'scope', 'realm', 'user', 'time', 'client', 'active'
    ]

    for attr in attributes:
        key = "Policy.%s.%s" % (name, attr)
        value = policy[attr]
        typ = ""
        descr = "a policy definition"
        ret[attr] = storeConfig(key, value, typ, descr)

    return ret
Ejemplo n.º 16
0
def setRealm(realm, resolvers):

    realm = realm.lower().strip()
    realm = realm.replace(" ", "-")

    nameExp = "^[A-Za-z0-9_\-\.]*$"
    res = re.match(nameExp, realm)
    if res is None:
        e = Exception("non conformant characters in realm name:"
                      " %s (not in %s)" % (realm, nameExp))
        raise e

    ret = storeConfig("useridresolver.group.%s" % realm, resolvers)
    if ret == False:
        return ret

    createDBRealm(realm)

    ## if this is the first one, make it the default
    realms = getRealms()
    if 1 == len(realms):
        for name in realms:
            setDefaultRealm(name)

    return True
Ejemplo n.º 17
0
def setDefaultRealm(defaultRealm):
    """
    set the defualt realm attrbute

    :note: verify, if the defualtRealm could be empty :""

    :param defaultRealm: the default realm name
    :type  defualtRealm: string

    :return:  success or not
    :rtype:   boolean
    """
    ret = isRealmDefined(defaultRealm)
    if True == ret or defaultRealm == "":
        storeConfig(u"linotp.DefaultRealm", defaultRealm);
    return ret
Ejemplo n.º 18
0
def save_resolver_config(resolver, config, prefix, name):
    """
    save the processed config to the global linotp config and to the db

    """

    res = True

    for key, value in config.items():

        # if the config contains something starting with 'linotp.'
        # it does not belong to the resolver rather then to linotp

        if key.startswith('linotp.'):
            continue

        # use a the fully qualified key name
        l_key = '%s.%s.%s' % (prefix, key, name)

        # do some type naming
        typ = 'unknown'
        if key in resolver.resolver_parameters:
            (_req, _def, data_typ) = resolver.resolver_parameters.get(key)
            try:
                typ = data_typ.__name__
            except Exception as _exx:
                log.error("unknown data type for %s", key)

        res = storeConfig(l_key, value, typ=typ)

    return res
Ejemplo n.º 19
0
def save_resolver_config(resolver, config, prefix, name):
    """
    save the processed config to the global linotp config and to the db

    """

    res = True

    for key, value in list(config.items()):

        # if the config contains something starting with 'linotp.'
        # it does not belong to the resolver rather then to linotp

        if key.startswith('linotp.'):
            continue

        # use a the fully qualified key name
        l_key = '%s.%s.%s' % (prefix, key, name)

        # do some type naming
        typ = 'unknown'
        if key in resolver.resolver_parameters:
            (_req, _def, data_typ) = resolver.resolver_parameters.get(key)
            try:
                typ = data_typ.__name__
            except Exception as _exx:
                log.error("unknown data type for %s", key)

        res = storeConfig(l_key, value, typ=typ)

    return res
Ejemplo n.º 20
0
def setRealm(realm, resolvers):

    realm = realm.lower().strip()
    realm = realm.replace(" ", "-")

    nameExp = "^[A-Za-z0-9_\-\.]*$"
    res = re.match(nameExp, realm)
    if res is None:
        e = Exception("non conformant characters in realm name:"
                      " %s (not in %s)" % (realm, nameExp))
        raise e

    ret = storeConfig("useridresolver.group.%s" % realm, resolvers)
    if ret == False:
        return ret

    createDBRealm(realm)

    # if this is the first one, make it the default
    realms = getRealms()
    if 1 == len(realms):
        for name in realms:
            setDefaultRealm(name)

    return True
Ejemplo n.º 21
0
def getProvider(provider_type, provider_name=None, decrypted=False):
    """
    return a dict with  providers, each with it's description as dict

    :param provider_type: either push, sms or email
    :param provider_name: name of the provider (optional)
    :return: the dict with all providers
    """
    providers = {}

    if provider_type in Legacy_Provider.keys():
        legacy_provider = get_legacy_provider(provider_type)
        providers.update(legacy_provider)

    new_providers = get_all_new_providers(provider_type)
    providers.update(new_providers)

    if not providers:
        return {}

    # is there already one provider registered as default?
    default_provider_name = get_default_provider(provider_type)
    if default_provider_name and default_provider_name in providers:
        provider = providers.get(default_provider_name)
        provider['Default'] = True
    else:
        # we take the first one in the list as the default
        firstone = providers.keys()[0]
        provider = providers[firstone]
        provider['Default'] = True
        default_provider_key = Default_Provider_Key[provider_type]
        storeConfig(default_provider_key, firstone)

    if decrypted:
        for provider_def in providers.values():
            if 'Config' in provider_def:
                provider_def['Config'] = provider_def.get(
                                            'Config').get_unencrypted()

    if provider_name:
        if provider_name in providers:
            return {provider_name: providers[provider_name]}
        else:
            return {}

    return providers
Ejemplo n.º 22
0
def getProvider(provider_type, provider_name=None, decrypted=False):
    """
    return a dict with  providers, each with it's description as dict

    :param provider_type: either push, sms or email
    :param provider_name: name of the provider (optional)
    :return: the dict with all providers
    """
    providers = {}

    if provider_type in Legacy_Provider.keys():
        legacy_provider = get_legacy_provider(provider_type)
        providers.update(legacy_provider)

    new_providers = get_all_new_providers(provider_type)
    providers.update(new_providers)

    if not providers:
        return {}

    # is there already one provider registered as default?
    default_provider_name = get_default_provider(provider_type)
    if default_provider_name and default_provider_name in providers:
        provider = providers.get(default_provider_name)
        provider['Default'] = True
    else:
        # we take the first one in the list as the default
        firstone = providers.keys()[0]
        provider = providers[firstone]
        provider['Default'] = True
        default_provider_key = Default_Provider_Key[provider_type]
        storeConfig(default_provider_key, firstone)

    if decrypted:
        for provider_def in providers.values():
            if 'Config' in provider_def:
                provider_def['Config'] = provider_def.get(
                    'Config').get_unencrypted()

    if provider_name:
        if provider_name in providers:
            return {provider_name: providers[provider_name]}
        else:
            return {}

    return providers
Ejemplo n.º 23
0
def setPolicy(policy):
    '''
    define and store a policy definition

    :param policy: dict  with the following keys:

          * name
          * action
          * scope
          * realm
          * user
          * time
          * client

    :return: dict with the results of the stored entries
    '''

    ret = {}
    _ = context['translate']

    name = policy.get('name')

    if 'active' not in policy:
        policy['active'] = "True"

    # check that the name does not contain any bad characters
    if not PolicyNameRegex.match(name):
        raise Exception(_("The name of the policy may only contain "
                          "the characters  a-zA-Z0-9_."))

    # verify the required policy attributes
    required_attributes = ['action', 'scope', 'realm']
    for required_attribute in required_attributes:
        if (required_attribute not in policy or
           not policy[required_attribute]):
            raise PolicyWarning("Missing attribute %s in "
                                "policy %s" % (required_attribute, name))

    # before storing the policy, we have to check the impact:
    # if there is a problem, we will raise an exception with a warning

    _check_policy_impact(**policy)

    # transpose the forwardServer policy action as it might
    # contain sensitive data
    policy["action"] = ForwardServerPolicy.prepare_forward(policy["action"])

    attributes = ['action', 'scope', 'realm', 'user',
                  'time', 'client', 'active']

    for attr in attributes:
        key = "Policy.%s.%s" % (name, attr)
        value = policy[attr]
        typ = ""
        descr = "a policy definition"
        ret[attr] = storeConfig(key, value, typ, descr)

    return ret
Ejemplo n.º 24
0
def setProvider(params):
    """
    save the provider info in linotp config

    :param params: generic parameter dictionary to support later more complex
                   provider definitions
                   in the dictionary currently required keys are
                   :param type: sms or email
                   :param name: the provider name
                   :param config: the provider config
                   :param timeout: the provider timeout
                   :param: default: boolean

    :return: success - boolean
    """

    provider_type = params['type']
    provider_name = params['name']

    prefix = Provider_types.get(provider_type, {}).get('prefix')
    if not prefix:
        raise Exception('unknown provider type %r' % provider_type)

    provider_prefix = prefix + provider_name
    storeConfig(key=provider_prefix, val=params['class'])
    storeConfig(key=provider_prefix + '.Timeout', val=params['timeout'])

    # alternative to storing the whole config in encrypted way, we
    # might look if it's a json and store the next Config.  level
    # and look for the reserved additional appended type: password
    storeConfig(key=provider_prefix + '.Config', val=params['config'],
                typ='password')

    # finally we handle the default setting and the
    # ability to delete legacy entries
    drop_legacy = False
    config = getLinotpConfig()
    default_provider_key = Default_Provider_Key[provider_type]

    if 'default' in params:
        if params['default'] == True or params['default'].lower() == 'true':
            storeConfig(key=default_provider_key, val=provider_name)
            drop_legacy = True

    elif provider_name == config.get(default_provider_key, ''):
        drop_legacy = True

    if drop_legacy:
        # at this point we can drop the legacy definition
        entries = Legacy_Provider[provider_type]
        for entry in entries.keys():
            if entry in config:
                removeFromConfig(entry)

    return True, {}
Ejemplo n.º 25
0
def setDefaultProvider(provider_type, provider_name):
    """
    interface to set the default provider wo. storing the provider

    :param provider_type: the type of the provider: sms or email
    :param provider_name: the name of the provider - must exist
    :return: boolean, success of storing default provider information
    """
    res = False
    detail = {}

    providers = getProvider(provider_type, provider_name)
    if provider_name in providers:
        default_provider_key = Default_Provider_Key[provider_type]
        storeConfig(key=default_provider_key, val=provider_name)
        res = True
    else:
        detail = {'message': _('Unknown provider! %r') % provider_name}
    return res, detail
Ejemplo n.º 26
0
def setDefaultProvider(provider_type, provider_name):
    """
    interface to set the default provider wo. storing the provider

    :param provider_type: the type of the provider: sms or email
    :param provider_name: the name of the provider - must exist
    :return: boolean, success of storing default provider information
    """
    res = False
    detail = {}

    providers = getProvider(provider_type, provider_name)
    if provider_name in providers or provider_name == Legacy_Provider_Name:
        default_provider_key = Default_Provider_Key[provider_type]
        storeConfig(key=default_provider_key, val=provider_name)
        res = True
    else:
        detail = {'message': _('Unknown provider! %r') % provider_name}
    return res, detail
Ejemplo n.º 27
0
def save_legacy_provider(provider_type, params):
    """
    save the provider to the legacy format

    :param provider_type: push, sms or email provider
    :param params: the provider description dict with 'class', 'config' and
                   'timeout'

    """

    defintion = Legacy_Provider.get(provider_type, {})
    if not defintion:
        raise Exception("unknown provider type %r" % provider_type)

    for config_name, spec in list(defintion.items()):
        if spec == "Class" and "class" in params:
            storeConfig(key=config_name, val=params["class"])
        if spec == "Config" and "config" in params:
            storeConfig(key=config_name,
                        val=params["config"],
                        typ="encrypted_data")
        if spec == "Timeout" and "timeout" in params:
            storeConfig(key=config_name, val=params["timeout"])

    return
Ejemplo n.º 28
0
def save_new_provider(provider_type, provider_name, params):
    """
    save the provider in the new provider format

    remarks:
        alternative to storing the whole config in encrypted way, we
        might look if it's a json and store the next Config.  level
        and look for the reserved additional appended type: password

    :param provider_type: sms or email provider
    :param provider_name: the name of the provider
    :param params: the provider description dict with 'class', 'config',
                   and 'timeout'

    """

    prefix = Provider_types.get(provider_type, {}).get('prefix')
    if not prefix:
        raise Exception('unknown provider type %r' % provider_type)

    provider_prefix = prefix + provider_name

    storeConfig(key=provider_prefix, val=params['class'])
    storeConfig(key=provider_prefix + '.Timeout', val=params['timeout'])

    storeConfig(key=provider_prefix + '.Config', val=params['config'],
                typ='password')

    return True, {}
Ejemplo n.º 29
0
def save_legacy_provider(provider_type, params):
    """
    save the provider to the legacy format

    :param provider_type: push, sms or email provider
    :param params: the provider description dict with 'class', 'config' and
                   'timeout'

    """

    defintion = Legacy_Provider.get(provider_type, {})
    if not defintion:
        raise Exception('unknown provider type %r' % provider_type)

    for config_name, spec in defintion.items():
        if spec == 'Class' and 'class' in params:
            storeConfig(key=config_name, val=params['class'])
        if spec == 'Config' and 'config' in params:
            storeConfig(key=config_name,
                        val=params['config'],
                        typ='encrypted_data')
        if spec == 'Timeout' and 'timeout' in params:
            storeConfig(key=config_name, val=params['timeout'])

    return
Ejemplo n.º 30
0
def setDefaultRealm(defaultRealm, check_if_exists=True):
    """
    set the defualt realm attrbute

    :note: verify, if the defualtRealm could be empty :""

    :param defaultRealm: the default realm name
    :type  defualtRealm: string

    :return:  success or not
    :rtype:   boolean
    """

    #TODO: verify merge
    if check_if_exists:
        ret = isRealmDefined(defaultRealm)
    else:
        ret = True

    if ret is True or defaultRealm == "":
        storeConfig("linotp.DefaultRealm", defaultRealm)

    return ret
Ejemplo n.º 31
0
def setDefaultRealm(defaultRealm, check_if_exists=True):
    """
    set the defualt realm attrbute

    :note: verify, if the defualtRealm could be empty :""

    :param defaultRealm: the default realm name
    :type  defualtRealm: string

    :return:  success or not
    :rtype:   boolean
    """

    #TODO: verify merge
    if check_if_exists:
        ret = isRealmDefined(defaultRealm)
    else:
        ret = True

    if ret is True or defaultRealm == "":
        storeConfig(u"linotp.DefaultRealm", defaultRealm)

    return ret
Ejemplo n.º 32
0
def setPolicy(param):
    '''
    Function to set a policy. It expects a dict of with the following keys:

      * name
      * action
      * scope
      * realm
      * user
      * time
      * client
    '''
    ret = {}

    name = param.get('name')
    action = param.get('action')
    scope = param.get('scope')
    realm = param.get('realm')
    user = param.get('user')
    time = param.get('time')
    client = param.get('client')
    active = param.get('active', "True")

    # before storing the policy, we have to check the impact:
    # if there is a problem, we will raise an exception with a warning
    if context and 'Policies' in context:
        policies = context['Policies']
    else:
        policies = getPolicies()

    _check_policy_impact(policies=policies, **param)

    action = ForwardServerPolicy.prepare_forward(action)

    ret["action"] = storeConfig("Policy.%s.action" % name, action, "",
                                "a policy definition")
    ret["scope"] = storeConfig("Policy.%s.scope" % name, scope, "",
                               "a policy definition")
    ret["realm"] = storeConfig("Policy.%s.realm" % name, realm, "",
                               "a policy definition")
    ret["user"] = storeConfig("Policy.%s.user" % name, user, "",
                              "a policy definition")
    ret["time"] = storeConfig("Policy.%s.time" % name, time, "",
                              "a policy definition")
    ret["client"] = storeConfig("Policy.%s.client" % name, client, "",
                                "a policy definition")
    ret["active"] = storeConfig("Policy.%s.active" % name, active, "",
                                "a policy definition")

    return ret
Ejemplo n.º 33
0
def setPolicy(param):
    '''
    Function to set a policy. It expects a dict of with the following keys:

      * name
      * action
      * scope
      * realm
      * user
      * time
      * client
    '''
    ret = {}

    name = param.get('name')
    action = param.get('action')
    scope = param.get('scope')
    realm = param.get('realm')
    user = param.get('user')
    time = param.get('time')
    client = param.get('client')
    active = param.get('active', "True")

    # before storing the policy, we have to check the impact:
    # if there is a problem, we will raise an exception with a warning
    if context and 'Policies' in context:
        policies = context['Policies']
    else:
        policies = getPolicies()

    _check_policy_impact(policies=policies, **param)

    action = ForwardServerPolicy.prepare_forward(action)

    ret["action"] = storeConfig("Policy.%s.action" % name,
                                action, "", "a policy definition")
    ret["scope"] = storeConfig("Policy.%s.scope" % name,
                               scope, "", "a policy definition")
    ret["realm"] = storeConfig("Policy.%s.realm" % name,
                               realm, "", "a policy definition")
    ret["user"] = storeConfig("Policy.%s.user" % name,
                              user, "", "a policy definition")
    ret["time"] = storeConfig("Policy.%s.time" % name,
                              time, "", "a policy definition")
    ret["client"] = storeConfig("Policy.%s.client" % name,
                                client, "", "a policy definition")
    ret["active"] = storeConfig("Policy.%s.active" % name,
                                active, "", "a policy definition")

    return ret
Ejemplo n.º 34
0
    def saveConfig(self):
        res = 'success'
        if self.name is None:
            return "no resolver name defined"
        # do the setConfig()'s
        prefix = self.type + "."
        postfix = "." + self.name

        for d in self.data:
            key = prefix + d + postfix
            val = self.data.get(d)
            typ = None
            desc = None
            if d in self.types:
                typ = self.types.get(d)

            if d in self.desc:
                desc = self.desc.get(d)

            res = storeConfig(key, val, typ, desc)

        return res
Ejemplo n.º 35
0
    def saveConfig(self):
        res = 'success'
        if self.name is None:
            return "no resolver name defined"
        # do the setConfig()'s
        prefix = self.type + "."
        postfix = "." + self.name

        for d in self.data:
            key = prefix + d + postfix
            val = self.data.get(d)
            typ = None
            desc = None
            if self.types.has_key(d) == True:
                typ = self.types.get(d)

            if self.desc.has_key(d) == True:
                desc = self.desc.get(d)

            res = storeConfig(key, val, typ, desc)

        return res
Ejemplo n.º 36
0
def save_legacy_provider(provider_type, params):
    """
    save the provider to the legacy format

    :param provider_type: push, sms or email provider
    :param params: the provider description dict with 'class', 'config' and
                   'timeout'

    """

    defintion = Legacy_Provider.get(provider_type, {})
    if not defintion:
        raise Exception('unknown provider type %r' % provider_type)

    for config_name, spec in defintion.items():
        if spec == 'Class' and 'class' in params:
            storeConfig(key=config_name, val=params['class'])
        if spec == 'Config' and 'config' in params:
            storeConfig(key=config_name, val=params['config'],
                        typ='encrypted_data')
        if spec == 'Timeout' and 'timeout' in params:
            storeConfig(key=config_name, val=params['timeout'])

    return
Ejemplo n.º 37
0
def save_new_provider(provider_type, provider_name, params):
    """
    save the provider in the new provider format

    remarks:
        alternative to storing the whole config in encrypted way, we
        might look if it's a json and store the next Config.  level
        and look for the reserved additional appended type: encrypted_data

    :param provider_type: push, sms or email provider
    :param provider_name: the name of the provider
    :param params: the provider description dict with 'class', 'config',
                   and 'timeout'

    """

    prefix = Provider_types.get(provider_type, {}).get('prefix')
    if not prefix:
        raise Exception('unknown provider type %r' % provider_type)

    provider_prefix = prefix + provider_name

    storeConfig(key=provider_prefix, val=params['class'])

    config_mapping = {
        'timeout': ('Timeout', None),
        'config': ('Config', 'encrypted_data')}

    #
    # alternative config entries are supported by the the adjustable config
    # entries if the provider supports the 'getConfigMapping' interface:
    #
    try:
        provider_class = _load_provider_class(params['class'])
        config_mapping = provider_class.getConfigMapping()
    except AttributeError as exx:
        log.debug("provider %r does not support ConfigMapping: %r",
                  provider_name, exx)

    # add the extra parameter for each resolver that it could be a managed one

    config_mapping['managed'] = ('Managed', None)

    for config_entry in config_mapping.keys():

        if config_entry not in params:
            continue

        # get the mapping entry and split the config name and type
        mapping_entry = config_mapping[config_entry]
        config_key, config_type = mapping_entry

        value = params[config_entry]
        if isinstance(params[config_entry], str):
            value = params[config_entry].decode('utf-8')

        # store the config entry
        storeConfig(key=provider_prefix + '.' + config_key,
                    val=value,
                    typ=config_type)

    return True, {}
Ejemplo n.º 38
0
def getProvider(provider_type, provider_name=None):
    """
    return a dict with  providers, each with it's description as dict

    :param provider_type: either sms or email
    :param provider_name: name of the provider (optional)
    """
    providers = {}

    # find out, which provider type we have, currently only sms or email
    prefix = Provider_types.get(provider_type, {}).get('prefix')
    if not prefix:
        raise Exception('unknow provider type %r' % provider_type)

    default_provider_key = Default_Provider_Key[provider_type]

    # find out, which providers we have
    config = getLinotpConfig()

    provider_names = {}

    default_provider = None

    # if provider by name is given, we select only this one
    if provider_name:
        name = prefix + provider_name
        if name in config:
            provider_names[name] = config[name]
    else:
        # first identify all providers by its name
        for key, value in config.items():
            if key[:len(prefix)] == prefix:
                parts = key.split('.')
                if len(parts) == 3:
                    provider_names[key] = value

    for provider, provider_class in provider_names.items():

        defintion = {}
        defintion['Class'] = provider_class
        prefix = provider + '.'

        for key, value in config.items():
            if key[:len(prefix)] == prefix:
                if 'enc' + key in config:
                    value = config.get('enc' + key)
                entry = key.replace(prefix, '')
                defintion[entry] = value

        defintion['Default'] = False
        name = provider.split('.')[2]
        providers[name] = defintion

    # finally care for the default provider
    if default_provider_key in config:
        default_provider = config.get(default_provider_key)
        if default_provider in providers:
            providers[default_provider]['Default'] = True

    # if searched for a dedicated provider, ignore the legacy one
    if not provider_name:
        if Legacy_Provider_Name not in providers:
            defintion = get_legacy_provider(provider_type=provider_type)
            if defintion:
                if not default_provider:
                    defintion['Default'] = True

                providers[Legacy_Provider_Name] = defintion

    #
    # finally check that we preserve and show the default:
    #
    # if in the current definition, we have a different default defined (s.o.)
    # we trust this and overwrite the one of Config table (if any)
    # This will create a consistent way to bootstrap a default even
    # from import

    for provider in providers:
        provider_info = providers[provider]
        if provider_info.get('Default', False):
            if config.get(default_provider_key, '') != provider:
                storeConfig(default_provider_key, provider)

    # if there is only one defined, it must be the default :-)
    if len(providers.keys()) == 1:
        for provider, provider_info in providers.items():
            provider_info['Default'] = True
            storeConfig(default_provider_key, provider)

    return providers