Пример #1
0
    def generate_configuration(self):

        self.check_clients([('gluu_radius_client_id', '1701.')])

        if not Config.get('gluu_ro_encoded_pw'):
            Config.gluu_ro_pw = self.getPW()
            Config.gluu_ro_encoded_pw = self.obscure(Config.gluu_ro_pw)

        if not Config.get('radius_jwt_pass'):
            Config.radius_jwt_pass = self.getPW()

        radius_jwt_pass = self.obscure(Config.radius_jwt_pass)
        radius_jks_fn = os.path.join(Config.certFolder, 'gluu-radius.jks')

        raidus_client_jwks = self.gen_openid_jwks_jks_keys(
            radius_jks_fn, Config.radius_jwt_pass)
        raidus_client_jwks = ''.join(raidus_client_jwks).replace(
            '\'', '').replace(',,', ',').replace('{,', '{')
        raidus_client_jwks = json.loads(raidus_client_jwks)
        Config.templateRenderingDict['radius_jwt_pass'] = radius_jwt_pass
        raidus_client_jwks_json = json.dumps(raidus_client_jwks, indent=2)
        Config.templateRenderingDict[
            'gluu_ro_client_base64_jwks'] = base64.encodestring(
                raidus_client_jwks_json.encode('utf-8')).decode(
                    'utf-8').replace(' ', '').replace('\n', '')

        for k in raidus_client_jwks['keys']:
            if k.get('alg') == 'RS512':
                Config.templateRenderingDict['radius_jwt_keyId'] = k['kid']
Пример #2
0
    def generate_configuration(self):
        if not Config.get('oxauth_openid_jks_pass'):
            Config.oxauth_openid_jks_pass = self.getPW()

        if not Config.get('admin_inum'):
            Config.admin_inum = str(uuid.uuid4())

        Config.encoded_admin_password = self.ldap_encode(Config.admin_password)

        self.check_clients([('oxauth_client_id', '1001.')])

        if not Config.get('oxauthClient_pw'):
            Config.oxauthClient_pw = self.getPW()
            Config.oxauthClient_encoded_pw = self.obscure(
                Config.oxauthClient_pw)

        self.logIt("Generating OAuth openid keys", pbar=self.service_name)
        sig_keys = 'RS256 RS384 RS512 ES256 ES384 ES512 PS256 PS384 PS512'
        enc_keys = 'RSA1_5 RSA-OAEP'
        jwks = self.gen_openid_jwks_jks_keys(self.oxauth_openid_jks_fn,
                                             Config.oxauth_openid_jks_pass,
                                             key_expiration=2,
                                             key_algs=sig_keys,
                                             enc_keys=enc_keys)
        self.write_openid_keys(self.oxauth_openid_jwks_fn, jwks)
Пример #3
0
    def check_clients(self, client_var_id_list, resource=False):
        field_name, ou = ('jansId', 'resources') if resource else ('inum', 'clients')

        for cids in client_var_id_list:
            client_var_name = cids[0] 
            client_id_prefix = cids[1]
            if len(cids) > 2:
                client_pw = cids[2]['pw']
                client_encoded_pw = cids[2]['encoded']
            else:
                client_pw = None
                client_encoded_pw = None

            self.logIt("Checking ID for client {}".format(client_var_name))
            if not Config.get(client_var_name):
                result = self.dbUtils.search('ou={},o=jans'.format(ou), '(&({}={}*)(objectClass=jansClnt))'.format(field_name, client_id_prefix))
                if result:
                    setattr(Config, client_var_name, result[field_name])
                    self.logIt("{} was found in backend as {}".format(client_var_name, result[field_name]))
                    if client_encoded_pw:
                        if 'jansClntSecret' in result:
                            setattr(Config, client_encoded_pw, result['jansClntSecret'])
                            setattr(Config, client_pw, self.unobscure(result['jansClntSecret']))

            if not Config.get(client_var_name):
                setattr(Config, client_var_name, client_id_prefix + str(uuid.uuid4()))
                self.logIt("Client ID for {} was created as {}".format(client_var_name, Config.get(client_var_name)))
Пример #4
0
 def make_salt(self, enforce=False):
     if not Config.get('pairwiseCalculationKey') or enforce:
         Config.pairwiseCalculationKey = self.genRandomString(
             random.randint(20, 30))
     if not Config.get('pairwiseCalculationSalt') or enforce:
         Config.pairwiseCalculationSalt = self.genRandomString(
             random.randint(20, 30))
Пример #5
0
    def generate_configuration(self):

        self.generate_api_configuration()

        client_var_id_list = (
                    ('oxtrust_resource_server_client_id', '1401.'),
                    ('oxtrust_requesting_party_client_id', '1402.'),
                    )

        self.check_clients(client_var_id_list)
        self.check_clients([('oxtrust_resource_id', '1403.')], resource=True)

        if not Config.get('admin_inum'):
            Config.admin_inum = str(uuid.uuid4())


        Config.encoded_oxtrust_admin_password = self.ldap_encode(Config.oxtrust_admin_password)

        # We need oxauth cleint id and encoded password
        if not Config.get('oxauth_client_id'):
            result = self.dbUtils.search('ou=clients,o=gluu', '(inum=1001.*)')
            if result:
                Config.oxauth_client_id = result['inum']
                self.logIt("oxauth_client_id was found in backend as {}".format(Config.oxauth_client_id))

                Config.oxauthClient_encoded_pw = result['oxAuthClientSecret']
                self.logIt("oxauthClient_encoded_pw was found in backend as {}".format(Config.oxauthClient_encoded_pw))

        if not Config.get('oxauth_client_id'):
            self.logIt("FATAL: oxauth_client_id was neither found in config nor backend. Can't continue ...", True, True)
Пример #6
0
    def import_ldif(self):
        ldif_files = []

        if Config.mappingLocations['default'] == 'rdbm':
            ldif_files += Config.couchbaseBucketDict['default']['ldif']

        ldap_mappings = self.getMappingType('rdbm')

        for group in ldap_mappings:
            ldif_files += Config.couchbaseBucketDict[group]['ldif']

        if Config.get('ldif_metric') in ldif_files:
            ldif_files.remove(Config.ldif_metric)

        if Config.get('ldif_site') in ldif_files:
            ldif_files.remove(Config.ldif_site)

        Config.pbar.progress(
            self.service_name,
            "Importing ldif files to {}".format(Config.rdbm_type), False)
        if not Config.ldif_base in ldif_files:
            if Config.rdbm_type == 'mysql':
                force = BackendTypes.MYSQL
            elif Config.rdbm_type == 'pgsql':
                force = BackendTypes.PGSQL
            elif Config.rdbm_type == 'spanner':
                force = BackendTypes.SPANNER
            self.dbUtils.import_ldif([Config.ldif_base], force=force)

        self.dbUtils.import_ldif(ldif_files)
Пример #7
0
    def generate_configuration(self):
        self.logIt("Generating {} configuration".format(self.service_name))
        client_var_id_list = (
                    ('scim_rs_client_id', '1201.'),
                    ('scim_rp_client_id', '1202.'),
                    )
        self.check_clients(client_var_id_list)
        self.check_clients([('scim_resource_oxid', '1203.')], resource=True)

        if not Config.get('scim_rs_client_jks_pass'):
            Config.scim_rs_client_jks_pass = self.getPW()
        
        Config.scim_rs_client_jks_pass_encoded = self.obscure(Config.scim_rs_client_jks_pass)

        if not Config.get('scim_rp_client_jks_pass'):
            Config.scim_rp_client_jks_pass = '******'

        Config.scimTestMode = Config.get('scimTestMode', 'false')
        Config.enable_scim_access_policy = 'true' if Config.installPassport else 'false'

        #backup current jks files if exists
        for jks_fn in (self.scim_rs_client_jks_fn, self.scim_rp_client_jks_fn):
            if os.path.exists(jks_fn):
                self.backupFile(jks_fn, move=True)

        Config.scim_rs_client_jwks = self.gen_openid_jwks_jks_keys(self.scim_rs_client_jks_fn, Config.scim_rs_client_jks_pass)
        Config.templateRenderingDict['scim_rs_client_base64_jwks'] = self.generate_base64_string(Config.scim_rs_client_jwks, 1)

        Config.scim_rp_client_jwks = self.gen_openid_jwks_jks_keys(self.scim_rp_client_jks_fn, Config.scim_rp_client_jks_pass)
        Config.templateRenderingDict['scim_rp_client_base64_jwks'] = self.generate_base64_string(Config.scim_rp_client_jwks, 1)
Пример #8
0
    def check_clients(self, client_var_id_list, resource=False, create=True):
        field_name, ou = ('jansId', 'resources') if resource else ('inum',
                                                                   'clients')

        ret_val = {}

        for cids in client_var_id_list:
            client_var_name = cids[0]
            client_id_prefix = cids[1]
            if len(cids) > 2:
                client_pw = cids[2]['pw']
                client_encoded_pw = cids[2]['encoded']
            else:
                tmp_ = client_var_name.split('_')
                client_pw = '_'.join(tmp_[:-1]) + '_pw'
                client_encoded_pw = '_'.join(tmp_[:-1]) + '_encoded_pw'

            self.logIt("Checking ID for client {}".format(client_var_name))
            rv = 1
            if not Config.get(client_var_name):
                result = self.dbUtils.search(
                    'ou={},o=jans'.format(ou),
                    '(&({}={}*)(objectClass=jansClnt))'.format(
                        field_name, client_id_prefix))
                if result:
                    setattr(Config, client_var_name, result[field_name])
                    self.logIt("{} was found in backend as {}".format(
                        client_var_name, result[field_name]))
                    if 'jansClntSecret' in result:
                        setattr(Config, client_encoded_pw,
                                result['jansClntSecret'])
                        setattr(Config, client_pw,
                                self.unobscure(result['jansClntSecret']))
                else:
                    rv = -1

            ret_val[client_id_prefix] = rv

            if create:

                if not Config.get(client_var_name):
                    setattr(Config, client_var_name,
                            client_id_prefix + str(uuid.uuid4()))
                    self.logIt("Client ID for {} was created as {}".format(
                        client_var_name, Config.get(client_var_name)))
                else:
                    self.logIt(
                        "Client {} exists in current configuration as {}".
                        format(client_var_name,
                               getattr(Config, client_var_name)))

                if not Config.get(client_pw):
                    self.logIt("Generating password for {}".format(client_pw))
                    client_pw_s = self.getPW()
                    client_encoder_pw_s = self.obscure(client_pw_s)
                    setattr(Config, client_pw, client_pw_s)
                    setattr(Config, client_encoded_pw, client_encoder_pw_s)

        return ret_val
Пример #9
0
    def install(self):

        if Config.couchbase_hostname == 'localhost':
            Config.couchbase_hostname = Config.hostname

        if not Config.get('couchebaseClusterAdmin'):
            Config.couchebaseClusterAdmin = 'admin'

        if Config.cb_install == InstallTypes.LOCAL:
            Config.isCouchbaseUserAdmin = True

        if not Config.get('couchbaseTrustStorePass'):
            Config.couchbaseTrustStorePass = '******'
            Config.encoded_couchbaseTrustStorePass = self.obscure(
                Config.couchbaseTrustStorePass)

        if not Config.get('cb_query_node'):
            Config.cb_query_node = Config.couchbase_hostname

        if not Config.get('couchbase_bucket_prefix'):
            Config.couchbase_bucket_prefix = 'jans'

        if Config.cb_install == InstallTypes.LOCAL:
            Config.couchbase_hostname = Config.hostname

        self.dbUtils.set_cbm()

        if Config.cb_install == InstallTypes.LOCAL:
            self.add_couchbase_post_messages()
            self.couchbaseInstall()
            self.checkIfJansBucketReady()
            self.couchebaseCreateCluster()

        self.couchbaseSSL()

        self.create_couchbase_buckets()

        Config.pbar.progress(self.service_name,
                             "Importing documents into Couchbase",
                             incr=False)

        couchbase_mappings = self.getMappingType('couchbase')

        if Config.mappingLocations['default'] == 'couchbase':
            self.dbUtils.import_ldif(
                Config.couchbaseBucketDict['default']['ldif'],
                Config.couchbase_bucket_prefix)
        else:
            self.dbUtils.import_ldif([Config.ldif_base],
                                     force=BackendTypes.COUCHBASE)

        for group in couchbase_mappings:
            bucket = '{}_{}'.format(Config.couchbase_bucket_prefix, group)
            if Config.couchbaseBucketDict[group]['ldif']:
                self.dbUtils.import_ldif(
                    Config.couchbaseBucketDict[group]['ldif'], bucket)

        self.couchbaseProperties()
Пример #10
0
    def generate_configuration(self):

        self.logIt("Generating Passport configuration")
        if not Config.get('passportSpKeyPass'):
            Config.passportSpKeyPass = self.getPW()
            Config.passportSpJksPass = self.getPW()

        if not Config.get('passport_rp_client_cert_alg'):
            Config.passport_rp_client_cert_alg = 'RS512'

        if not Config.get('passport_rp_client_jks_pass'):
            Config.passport_rp_client_jks_pass = '******'

        if not Config.get('passport_rs_client_jks_pass'):
            Config.passport_rs_client_jks_pass = self.getPW()
            Config.passport_rs_client_jks_pass_encoded = self.obscure(Config.passport_rs_client_jks_pass)

        client_var_id_list = (
                    ('passport_rs_client_id', '1501.'),
                    ('passport_rp_client_id', '1502.'),
                    ('passport_rp_ii_client_id', '1503.'),
                    )

        self.check_clients(client_var_id_list)
        self.check_clients([('passport_resource_id', '1504.')], resource=True)

        # backup existing files
        for f in glob.glob(os.path.join(Config.certFolder, 'passport-*')):
            if not f.endswith('~'):
                self.backupFile(f, move=True)

        # create certificates
        self.gen_cert('passport-sp', Config.passportSpKeyPass, 'ldap', Config.ldap_hostname)

        # set owner and mode of certificate files
        cert_files = glob.glob(os.path.join(Config.certFolder, 'passport*'))
        for fn in cert_files:
            self.run([paths.cmd_chmod, '500', fn])
            self.run([paths.cmd_chown, 'root:gluu', fn])

        Config.passport_rs_client_jwks = self.gen_openid_jwks_jks_keys(self.passport_rs_client_jks_fn, Config.passport_rs_client_jks_pass)
        Config.templateRenderingDict['passport_rs_client_base64_jwks'] = self.generate_base64_string(Config.passport_rs_client_jwks, 1)

        Config.passport_rp_client_jwks = self.gen_openid_jwks_jks_keys(self.passport_rp_client_jks_fn, Config.passport_rp_client_jks_pass)
        Config.templateRenderingDict['passport_rp_client_base64_jwks'] = self.generate_base64_string(Config.passport_rp_client_jwks, 1)

        self.logIt("Preparing Passport OpenID RP certificate...")

        passport_rp_client_jwks_json = json.loads(''.join(Config.passport_rp_client_jwks))

        for jwks_key in passport_rp_client_jwks_json["keys"]:
            if jwks_key["alg"]  == Config.passport_rp_client_cert_alg:
                Config.passport_rp_client_cert_alias = jwks_key["kid"]
                break

        self.export_openid_key(self.passport_rp_client_jks_fn, Config.passport_rp_client_jks_pass, Config.passport_rp_client_cert_alias, self.passport_rp_client_cert_fn)
    def prompt_remote_couchbase(self):
    
        while True:
            Config.couchbase_hostname = self.getPrompt("    Couchbase hosts", Config.get('couchbase_hostname'))
            Config.couchebaseClusterAdmin = self.getPrompt("    Couchbase User", Config.get('couchebaseClusterAdmin'))
            Config.cb_password =self.getPrompt("    Couchbase Password", Config.get('cb_password'))

            result = self.test_cb_servers(Config.get('couchbase_hostname'))

            if result['result']:
                break
    def fix_init_scripts(self, serviceName, initscript_fn):
        if base.snap:
            return

        changeTo = None

        couchbase_mappings = self.getMappingType('couchbase')

        if Config.persistence_type == 'couchbase' or 'default' in couchbase_mappings:
            changeTo = 'couchbase-server'

        if Config.get('opendj_install') == InstallTypes.REMOTE or Config.get(
                'cb_install') == InstallTypes.REMOTE:
            changeTo = ''

        if serviceName in Config.service_requirements:
            if changeTo != None:
                for service in Config.service_requirements:
                    Config.service_requirements[service][
                        0] = Config.service_requirements[service][0].replace(
                            'opendj', changeTo)

            with open(initscript_fn) as f:
                initscript = f.readlines()

            for i, l in enumerate(initscript):
                if l.startswith('# Provides:'):
                    initscript[i] = '# Provides:          {0}\n'.format(
                        serviceName)
                elif l.startswith('# description:'):
                    initscript[i] = '# description: Jetty 9 {0}\n'.format(
                        serviceName)
                elif l.startswith('# Required-Start:'):
                    initscript[
                        i] = '# Required-Start:    $local_fs $network {0}\n'.format(
                            Config.service_requirements[serviceName][0])
                elif l.startswith('# chkconfig:'):
                    initscript[i] = '# chkconfig: 345 {0} {1}\n'.format(
                        Config.service_requirements[serviceName][1],
                        100 - Config.service_requirements[serviceName][1])

            if (base.clone_type == 'rpm' and base.os_initdaemon
                    == 'systemd') or base.deb_sysd_clone:
                service_init_script_fn = os.path.join(Config.distFolder,
                                                      'scripts', serviceName)
            else:
                service_init_script_fn = os.path.join('/etc/init.d',
                                                      serviceName)

            with open(service_init_script_fn, 'w') as W:
                W.write(''.join(initscript))

            self.run([paths.cmd_chmod, '+x', service_init_script_fn])
Пример #13
0
    def encode_passwords(self):
        self.logIt("Encoding passwords")

        try:
            if Config.get('ldapPass'):
                Config.encoded_ox_ldap_pw = self.obscure(Config.ldapPass)
            if Config.get('cb_password'):
                Config.encoded_cb_password = self.obscure(Config.cb_password)
            if Config.get('opendj_p12_pass'):
                Config.encoded_opendj_p12_pass = self.obscure(Config.opendj_p12_pass)
        except:
            self.logIt("Error encoding passwords", True, True)
Пример #14
0
def logIt(msg, errorLog=False, fatal=False):
    log_fn = paths.LOG_ERROR_FILE if errorLog else paths.LOG_FILE
    with open(log_fn, 'a') as w:
        w.write('{} {}\n'.format(time.strftime('%X %x'), msg))
        if errorLog and 'NoneType: None' not in traceback.format_exc():
             w.write('{} {}\n'.format(time.strftime('%X %x'), traceback.format_exc()))

    if fatal:
        print("FATAL:", errorLog)
        print(traceback.format_exc())
        Config.dump(True)
        sys.exit(1)
Пример #15
0
    def do_beforeEditing(self):
        self.ask_wrends.value = [int(Config.wrends_install)]

        if Config.wrends_install == static.InstallTypes.REMOTE:
            self.wrends_hosts.hidden = False
        else:
            self.wrends_hosts.hidden = True

        if not Config.wrends_install:
            self.wrends_password.hidden = True
        else:
            self.wrends_password.hidden = False

        if Config.wrends_install == static.InstallTypes.LOCAL:
            if not Config.ldapPass:
                self.wrends_password.value = Config.oxtrust_admin_password

        self.wrends_hosts.value = Config.ldap_hostname

        self.ask_cb.value = [int(Config.cb_install)]

        if not Config.cb_install:
            self.cb_admin.hidden = True
        else:
            self.cb_admin.hidden = False

        if Config.cb_install == static.InstallTypes.REMOTE:
            self.cb_hosts.hidden = False
        else:
            self.cb_hosts.hidden = True

        if not Config.cb_install:
            self.cb_password.hidden = True
        else:
            self.cb_password.hidden = False

        if Config.cb_install == static.InstallTypes.LOCAL:
            if not Config.cb_password:
                self.cb_password.value = Config.oxtrust_admin_password

        self.cb_hosts.value = Config.get('couchbase_hostname', '')
        self.cb_admin.value = Config.get('couchebaseClusterAdmin', '')

        self.wrends_hosts.update()
        self.ask_wrends.update()
        self.wrends_hosts.update()
        self.wrends_password.update()

        self.cb_hosts.update()
        self.ask_cb.update()
        self.cb_hosts.update()
        self.cb_password.update()
Пример #16
0
    def generate_api_configuration(self):

        # TODO: Question: Should we do if oxtrust_api installtion?
        if not Config.get('api_rs_client_jks_pass'):
            Config.api_rs_client_jks_pass = '******'
            Config.api_rs_client_jks_pass_encoded = self.obscure(Config.api_rs_client_jks_pass)
        self.api_rs_client_jwks = self.gen_openid_jwks_jks_keys(self.api_rs_client_jks_fn, Config.api_rs_client_jks_pass)
        Config.templateRenderingDict['api_rs_client_base64_jwks'] = self.generate_base64_string(self.api_rs_client_jwks, 1)

        if not Config.get('api_rp_client_jks_pass'):
            Config.api_rp_client_jks_pass = '******'
            Config.api_rp_client_jks_pass_encoded = self.obscure(Config.api_rp_client_jks_pass)
        self.api_rp_client_jwks = self.gen_openid_jwks_jks_keys(self.api_rp_client_jks_fn, Config.api_rp_client_jks_pass)
        Config.templateRenderingDict['api_rp_client_base64_jwks'] = self.generate_base64_string(self.api_rp_client_jwks, 1)
Пример #17
0
    def saml_couchbase_settings(self):

        if not Config.get('couchbaseShibUserPassword'):
            Config.couchbaseShibUserPassword = self.getPW()

        shib_user = '******'
        shib_user_roles = 'query_select[*]'
        if Config.get('isCouchbaseUserAdmin'):
            self.logIt("Creating couchbase readonly user for shib")
            self.dbUtils.cbm.create_user(shib_user,
                                         Config.couchbaseShibUserPassword,
                                         'Shibboleth IDP', shib_user_roles)
        else:
            Config.post_messages.append(
                '{}Please create a user on Couchbase Server with the following credidentals and roles{}'
                .format(gluu_utils.colors.WARNING, gluu_utils.colors.ENDC))
            Config.post_messages.append('Username: {}'.format(shib_user))
            Config.post_messages.append('Password: {}'.format(
                Config.couchbaseShibUserPassword))
            Config.post_messages.append('Roles: {}'.format(shib_user_roles))

        # Add couchbase bean to global.xml
        couchbase_bean_xml_fn = os.path.join(Config.staticFolder,
                                             'couchbase/couchbase_bean.xml')
        global_xml_fn = os.path.join(self.idp3ConfFolder, 'global.xml')
        couchbase_bean_xml = self.readFile(couchbase_bean_xml_fn)
        global_xml = self.readFile(global_xml_fn)
        global_xml = global_xml.replace('</beans>',
                                        couchbase_bean_xml + '\n\n</beans>')
        self.writeFile(global_xml_fn, global_xml)

        # Add datasource.properties to idp.properties
        idp3_configuration_properties_fn = os.path.join(
            self.idp3ConfFolder, self.idp3_configuration_properties)

        with open(idp3_configuration_properties_fn) as f:
            idp3_properties = f.readlines()

        for i, l in enumerate(idp3_properties[:]):
            if l.strip().startswith('idp.additionalProperties'):
                idp3_properties[i] = l.strip(
                ) + ', /conf/datasource.properties\n'

        new_idp3_props = ''.join(idp3_properties)
        self.writeFile(idp3_configuration_properties_fn, new_idp3_props)

        self.renderTemplateInOut(self.data_source_properties,
                                 self.templates_folder, self.output_folder)

        self.copyFile(self.data_source_properties, self.idp3ConfFolder)
Пример #18
0
    def configure(self, options={}):
        config = configparser.ConfigParser()
        if self.config_ini_fn.exists():
            config.read_file(self.config_ini_fn.open())

        if not 'DEFAULT' in config:
            config['DEFAULT'] = {}

        if not 'debug' in config['DEFAULT']:
            config['DEFAULT']['debug'] = 'false'

        if not 'jans_host' in config['DEFAULT']:
            config['DEFAULT']['jans_host'] = Config.hostname

        for key_ in options:
            config['DEFAULT'][key_] = options[key_]

        if Config.installConfigApi:
            config['DEFAULT']['jca_client_id'] = Config.role_based_client_id
            config['DEFAULT']['jca_client_secret_enc'] = Config.role_based_client_encoded_pw

        if Config.get('installScimServer'):
            config['DEFAULT']['scim_client_id'] = Config.scim_client_id
            config['DEFAULT']['scim_client_secret_enc'] = Config.scim_client_encoded_pw

        config.write(self.config_ini_fn.open('w'))
Пример #19
0
    def generate_configuration(self):
        self.logIt("Generating {} configuration".format(self.service_name))
        yml_str = self.readFile(os.path.join(self.source_files[1][0]))
        yml_str = yml_str.replace('\t', ' ')
        cfg_yml = ruamel.yaml.load(yml_str, ruamel.yaml.RoundTripLoader)
        config_scopes = cfg_yml['components']['securitySchemes']['scim_oauth'][
            'flows']['clientCredentials']['scopes']

        scope_ldif_fd = open(self.ldif_scopes_fn, 'wb')
        ldif_scopes_writer = LDIFWriter(scope_ldif_fd, cols=1000)

        scopes_dn = self.create_user_scopes()
        for scope in config_scopes:
            if scope in ('https://jans.io/scim/users.read',
                         'https://jans.io/scim/users.write'):
                continue
            inum = '1200.' + os.urandom(3).hex().upper()
            scope_dn = 'inum={},ou=scopes,o=jans'.format(inum)
            scopes_dn.append(scope_dn)
            display_name = 'Scim {}'.format(os.path.basename(scope))
            ldif_scopes_writer.unparse(
                scope_dn, {
                    'objectclass': ['top', 'jansScope'],
                    'description': [config_scopes[scope]],
                    'displayName': [display_name],
                    'inum': [inum],
                    'jansId': [scope],
                    'jansScopeTyp': ['oauth'],
                })

        scope_ldif_fd.close()

        client_ldif_fd = open(self.ldif_clients_fn, 'wb')
        client_scopes_writer = LDIFWriter(client_ldif_fd, cols=1000)

        self.check_clients([('scim_client_id', '1201.')])

        if not Config.get('scim_client_pw'):
            Config.scim_client_pw = self.getPW()
            Config.scim_client_encoded_pw = self.obscure(Config.scim_client_pw)

        scim_client_dn = 'inum={},ou=clients,o=jans'.format(
            Config.scim_client_id)
        client_scopes_writer.unparse(
            scim_client_dn, {
                'objectClass': ['top', 'jansClnt'],
                'displayName': ['SCIM client'],
                'jansAccessTknSigAlg': ['RS256'],
                'jansAppTyp': ['native'],
                'jansAttrs': ['{}'],
                'jansGrantTyp': ['client_credentials'],
                'jansScope': scopes_dn,
                'jansSubjectTyp': ['pairwise'],
                'jansTknEndpointAuthMethod': ['client_secret_basic'],
                'inum': [Config.scim_client_id],
                'jansClntSecret': [Config.scim_client_encoded_pw]
            })

        client_ldif_fd.close()
Пример #20
0
 def before_start(self):
     for service in self.services[:]:
         if service['name'] != 'post-setup':
             if Config.installed_instance:
                 if not service['install_var'] in Config.addPostSetupService:
                     self.services.remove(service)
             else:
                 if not Config.get(service['install_var']):
                     self.services.remove(service)
    def check_properties(self):
        self.logIt('Checking properties')
        while not Config.hostname:
            testhost = input('Hostname of this server: ').strip()
            if len(testhost.split('.')) >= 3:
                Config.hostname = testhost
            else:
                print('The hostname has to be at least three domain components. Try again\n')
        while not Config.ip:
            Config.ip = self.get_ip()
        while not Config.orgName:
            Config.orgName = input('Organization Name: ').strip()
        while not Config.countryCode:
            testCode = input('2 Character Country Code: ').strip()
            if len(testCode) == 2:
                Config.countryCode = testCode
            else:
                print('Country code should only be two characters. Try again\n')
        while not Config.city:
            Config.city = input('City: ').strip()
        while not Config.state:
            Config.state = input('State or Province: ').strip()
        if not Config.admin_email:
            tld = None
            try:
                tld = ".".join(self.hostname.split(".")[-2:])
            except:
                tld = Config.hostname
            Config.admin_email = "support@%s" % tld

        if not Config.oxtrust_admin_password and Config.ldapPass:
            Config.oxtrust_admin_password = Config.ldapPass
        
        if not Config.oxtrust_admin_password:
            Config.oxtrust_admin_password = self.getPW()

        if not Config.ldapPass:
            Config.ldapPass = Config.oxtrust_admin_password

        if Config.cb_install and not Config.get('cb_password'):
            Config.cb_password = Config.oxtrust_admin_password

        if Config.cb_install and not Config.wrends_install:
            Config.mappingLocations = { group: 'couchbase' for group in Config.couchbaseBucketDict }

        self.set_persistence_type()

        if not Config.opendj_p12_pass:
            Config.opendj_p12_pass = self.getPW()

        if not Config.encode_salt:
            Config.encode_salt = self.getPW() + self.getPW()

        if not Config.application_max_ram:
            Config.application_max_ram = int(base.current_mem_size * .83 * 1000) # 83% of physical memory

        self.check_oxd_server_https()
    def check_oxd_server_https(self):

        if Config.get('oxd_server_https'):
            Config.templateRenderingDict['oxd_hostname'], Config.templateRenderingDict['oxd_port'] = self.parse_url(Config.oxd_server_https)
            if not Config.templateRenderingDict['oxd_port']: 
                Config.templateRenderingDict['oxd_port'] = 8443
        else:
            Config.templateRenderingDict['oxd_hostname'] = Config.hostname
            Config.oxd_server_https = 'https://{}:8443'.format(Config.hostname)
Пример #23
0
    def do_beforeEditing(self):
        if not Config.hostname:
            Config.hostname = self.parentApp.jettyInstaller.detect_hostname()

        for k in self.myfields_:
            f = getattr(self, k)
            v = Config.get(k, '')
            if v:
                f.value = str(v)
                f.update()
Пример #24
0
    def check_clients(self, client_var_id_list, resource=False):
        field_name, ou = ('oxId', 'resources') if resource else ('inum',
                                                                 'clients')

        for client_var_name, client_id_prefix in client_var_id_list:
            self.logIt("Checking ID for client {}".format(client_var_name))
            if not Config.get(client_var_name):
                result = self.dbUtils.search(
                    'ou={},o=gluu'.format(ou),
                    '({}={}*)'.format(field_name, client_id_prefix))
                if result:
                    setattr(Config, client_var_name, result[field_name])
                    self.logIt("{} was found in backend as {}".format(
                        client_var_name, result[field_name]))

            if not Config.get(client_var_name):
                setattr(Config, client_var_name,
                        client_id_prefix + str(uuid.uuid4()))
                self.logIt("Client ID for {} was created as {}".format(
                    client_var_name, Config.get(client_var_name)))
Пример #25
0
    def load_test_data(self):
        if not self.installed():
            return

        self.check_clients([('jca_test_client_id', '1802.')])

        result = self.dbUtils.search(
            'ou=scopes,o=jans',
            search_filter='(&(inum=1800.*)(objectClass=jansScope))',
            fetchmany=True)
        scopes = []
        scopes_id_list = []

        for scope in result:
            scopes.append('jansScope: ' + (
                scope['dn'] if isinstance(scope, dict) else scope[1]['dn']))
            scopes_id_list.append(scope['jansId'] if isinstance(scope, dict)
                                  else scope[1]['jansId'])

        Config.templateRenderingDict['config_api_scopes'] = '\n'.join(scopes)
        Config.templateRenderingDict['config_api_scopes_list'] = ' '.join(
            scopes_id_list)

        if not Config.get('jca_test_client_pw'):
            Config.jca_test_client_pw = self.getPW()
            Config.jca_test_client_encoded_pw = self.obscure(
                Config.jca_test_client_pw)

        else:
            warning = "Test data for Config Api was allready loaded."
            self.logIt(warning)
            if Config.installed_instance:
                print(warning)
            return

        self.logIt("Loding Jans Config Api test data")

        if not base.argsp.t:
            self.render_templates_folder(
                os.path.join(Config.templateFolder, 'test/jans-config-api'))

        template_fn = os.path.join(
            Config.templateFolder,
            'test/jans-config-api/data/jans-config-api.ldif')

        template_text = self.readFile(template_fn)
        rendered_text = self.fomatWithDict(
            template_text,
            self.merge_dicts(Config.__dict__, Config.templateRenderingDict))
        out_fn = os.path.join(self.output_folder,
                              os.path.basename(template_fn))
        self.writeFile(out_fn, rendered_text)
        self.dbUtils.import_ldif([out_fn])
Пример #26
0
    def do_beforeEditing(self):
        for service in self.services:
            if Config.get(service):
                cb = getattr(self, service)
                cb.value = True
                if Config.installed_instance:
                    cb.editable = False
                    self.services_before_this_form.append(service)
                cb.update()

        if Config.installed_instance and 'installCasa' in self.services_before_this_form:
            self.oxd_url.hidden = True
            self.oxd_url.update()
Пример #27
0
    def render_templates(self, templates=None):
        self.logIt("Rendering templates")

        if not templates:
            templates = Config.ce_templates

        if Config.persistence_type in ('couchbase', 'sql', 'spanner') and Config.get('ox_ldap_properties'):
            Config.ce_templates[Config.ox_ldap_properties] = False

        for fullPath in templates:
            try:
                self.renderTemplate(fullPath)
            except:
                self.logIt("Error writing template %s" % fullPath, True)
Пример #28
0
    def calculate_selected_aplications_memory(self):
        Config.pbar.progress("jans", "Calculating application memory")

        installedComponents = []

        # Jetty apps
        for config_var, service in [('installOxAuth', 'jans-auth')]:
            if Config.get(config_var):
                installedComponents.append(
                    self.jetty_app_configuration[service])

        return self.calculate_aplications_memory(Config.application_max_ram,
                                                 self.jetty_app_configuration,
                                                 installedComponents)
Пример #29
0
    def generate_configuration(self):
        if not Config.get('oxauth_openid_jks_pass'):
            Config.oxauth_openid_jks_pass = self.getPW()

        if not Config.get('admin_inum'):
            Config.admin_inum = str(uuid.uuid4())

        if Config.profile == 'jans':
            Config.encoded_admin_password = self.ldap_encode(
                Config.admin_password)

        self.logIt("Generating OAuth openid keys", pbar=self.service_name)
        sig_keys = 'RS256 RS384 RS512 ES256 ES256K ES384 ES512 PS256 PS384 PS512 Ed25519 Ed448'
        enc_keys = 'RSA1_5 RSA-OAEP ECDH-ES'
        jwks = self.gen_openid_jwks_jks_keys(self.oxauth_openid_jks_fn,
                                             Config.oxauth_openid_jks_pass,
                                             key_expiration=2,
                                             key_algs=sig_keys,
                                             enc_keys=enc_keys)
        self.write_openid_keys(self.oxauth_openid_jwks_fn, jwks)

        if Config.get('use_external_key'):
            self.import_openbanking_key()
Пример #30
0
    def promptForOxd(self):

        if Config.installed_instance and Config.installOxd:
            return

        promptForOxd = self.getPrompt("Install Oxd?",
                                      self.getDefaultOption(
                                          Config.installOxd))[0].lower()
        Config.installOxd = True if promptForOxd == 'y' else False

        if Config.installOxd:
            promptForOxdJansStorage = self.getPrompt(
                "  Use Janssen Storage for Oxd?",
                self.getDefaultOption(
                    Config.get('oxd_use_jans_storage')))[0].lower()
            Config.oxd_use_jans_storage = True if promptForOxdJansStorage == 'y' else False

        if Config.installed_instance and Config.installOxd:
            Config.addPostSetupService.append('installOxd')