def passport_sp_ctx(self):
        self._set_secret("passportSpKeyPass", get_random_chars())
        self._set_config("passportSpTLSCACert", '/etc/certs/passport-sp.pem')
        self._set_config("passportSpTLSCert", '/etc/certs/passport-sp.crt')
        self._set_config("passportSpTLSKey", '/etc/certs/passport-sp.key')
        self._set_secret("passportSpJksPass", get_random_chars())
        self._set_config("passportSpJksFn", '/etc/certs/passport-sp.jks')

        generate_ssl_certkey(
            "passport-sp",
            self.ctx["secret"]["passportSpKeyPass"],
            self.ctx["config"]["admin_email"],
            self.ctx["config"]["hostname"],
            self.ctx["config"]["orgName"],
            self.ctx["config"]["country_code"],
            self.ctx["config"]["state"],
            self.ctx["config"]["city"],
        )
        with open(self.ctx["config"]["passportSpTLSCert"]) as f:
            self._set_secret(
                "passport_sp_cert_base64",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))

        with open(self.ctx["config"]["passportSpTLSKey"]) as f:
            self._set_secret(
                "passport_sp_key_base64",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))
    def oxtrust_api_rp_ctx(self):
        self._set_config("api_rp_client_jks_fn", "/etc/certs/api-rp.jks")
        self._set_config("api_rp_client_jwks_fn",
                         "/etc/certs/api-rp-keys.json")
        self._set_secret("api_rp_client_jks_pass", get_random_chars())
        self._set_secret(
            "api_rp_client_jks_pass_encoded",
            encode_text(self.ctx["secret"]["api_rp_client_jks_pass"],
                        self.ctx["secret"]["encoded_salt"]),
        )
        _, err, retcode = generate_openid_keys(
            self.ctx["secret"]["api_rp_client_jks_pass"],
            self.ctx["config"]["api_rp_client_jks_fn"],
            self.ctx["config"]["api_rp_client_jwks_fn"],
            self.ctx["config"]["default_openid_jks_dn_name"],
        )
        if retcode != 0:
            logger.error(
                "Unable to generate oxTrust API RP keys; reason={}".format(
                    err))
            raise click.Abort()

        basedir, fn = os.path.split(
            self.ctx["config"]["api_rp_client_jwks_fn"])
        self._set_secret("api_rp_client_base64_jwks",
                         encode_template(fn, self.ctx, basedir))

        self._set_config("oxtrust_requesting_party_client_id",
                         '1402.{}'.format(uuid.uuid4()))

        with open(self.ctx["config"]["api_rp_client_jks_fn"], "rb") as fr:
            self._set_secret(
                "api_rp_jks_base64",
                encode_text(fr.read(), self.ctx["secret"]["encoded_salt"]))
    def passport_rs_ctx(self):
        self._set_config("passport_rs_client_id",
                         "1501.{}".format(uuid.uuid4()))
        self._set_config("passport_rs_client_jks_fn",
                         "/etc/certs/passport-rs.jks")
        self._set_config("passport_rs_client_jwks_fn",
                         "/etc/certs/passport-rs-keys.json")
        self._set_secret("passport_rs_client_jks_pass", get_random_chars())
        self._set_secret(
            "passport_rs_client_jks_pass_encoded",
            encode_text(self.ctx["secret"]["passport_rs_client_jks_pass"],
                        self.ctx["secret"]["encoded_salt"]),
        )

        out, err, retcode = generate_openid_keys(
            self.ctx["secret"]["passport_rs_client_jks_pass"],
            self.ctx["config"]["passport_rs_client_jks_fn"],
            self.ctx["config"]["passport_rs_client_jwks_fn"],
            self.ctx["config"]["default_openid_jks_dn_name"],
        )
        if retcode != 0:
            logger.error(
                "Unable to generate Passport RS keys; reason={}".format(err))
            raise click.Abort()

        self._set_config("passport_rs_client_cert_alg", "RS512")

        cert_alias = ""
        for key in json.loads(out)["keys"]:
            if key["alg"] == self.ctx["config"]["passport_rs_client_cert_alg"]:
                cert_alias = key["kid"]
                break

        basedir, fn = os.path.split(
            self.ctx["config"]["passport_rs_client_jwks_fn"])
        self._set_secret(
            "passport_rs_client_base64_jwks",
            encode_template(fn, self.ctx, basedir),
        )

        self._set_config("passport_rs_client_cert_alias", cert_alias)

        with open(self.ctx["config"]["passport_rs_client_jks_fn"], "rb") as fr:
            self._set_secret(
                "passport_rs_jks_base64",
                encode_text(fr.read(), self.ctx["secret"]["encoded_salt"]))

        self._set_config("passport_resource_id",
                         "1504.{}".format(uuid.uuid4()))
        self._set_config("passport_rs_client_cert_alias", cert_alias)
    def oxauth_ctx(self):
        self._set_config("oxauth_client_id", "1001.{}".format(uuid.uuid4()))
        self._set_secret(
            "oxauthClient_encoded_pw",
            encode_text(get_random_chars(),
                        self.ctx["secret"]["encoded_salt"]),
        )
        self._set_config("oxauth_openid_jks_fn", "/etc/certs/oxauth-keys.jks")
        self._set_secret(
            "oxauth_openid_jks_pass",
            get_random_chars(),
        )
        self._set_config("oxauth_openid_jwks_fn",
                         "/etc/certs/oxauth-keys.json")
        self._set_config("oxauth_legacyIdTokenClaims", "false")
        self._set_config("oxauth_openidScopeBackwardCompatibility", "false")

        _, err, retcode = generate_openid_keys(
            self.ctx["secret"]["oxauth_openid_jks_pass"],
            self.ctx["config"]["oxauth_openid_jks_fn"],
            self.ctx["config"]["oxauth_openid_jwks_fn"],
            self.ctx["config"]["default_openid_jks_dn_name"],
            exp=2,
            sig_keys="RS256 RS384 RS512 ES256 ES384 ES512 PS256 PS384 PS512",
            enc_keys="RSA1_5 RSA-OAEP",
        )
        if retcode != 0:
            logger.error(
                "Unable to generate oxAuth keys; reason={}".format(err))
            raise click.Abort()

        basedir, fn = os.path.split(
            self.ctx["config"]["oxauth_openid_jwks_fn"])
        self._set_secret("oxauth_openid_key_base64",
                         encode_template(fn, self.ctx, basedir))

        # oxAuth keys
        self._set_config("oxauth_key_rotated_at", int(time.time()))

        with open(self.ctx["config"]["oxauth_openid_jks_fn"], "rb") as fr:
            self._set_secret(
                "oxauth_jks_base64",
                encode_text(fr.read(), self.ctx["secret"]["encoded_salt"]),
            )
    def radius_ctx(self):
        self._set_config("gluu_radius_client_id",
                         '1701.{}'.format(uuid.uuid4()))
        # self._set_config("ox_radius_client_id", '0008-{}'.format(uuid.uuid4()))
        self._set_secret(
            "gluu_ro_encoded_pw",
            encode_text(get_random_chars(),
                        self.ctx["secret"]["encoded_salt"]),
        )

        radius_jwt_pass = get_random_chars()
        self._set_secret(
            "radius_jwt_pass",
            encode_text(radius_jwt_pass, self.ctx["secret"]["encoded_salt"]),
        )

        out, err, code = generate_openid_keys(
            radius_jwt_pass,
            "/etc/certs/gluu-radius.jks",
            "/etc/certs/gluu-radius.keys",
            self.ctx["config"]["default_openid_jks_dn_name"],
        )
        if code != 0:
            logger.error(
                "Unable to generate Gluu Radius keys; reason={}".format(err))
            raise click.Abort()

        for key in json.loads(out)["keys"]:
            if key["alg"] == "RS512":
                self.ctx["config"]["radius_jwt_keyId"] = key["kid"]
                break

        with open("/etc/certs/gluu-radius.jks", "rb") as fr:
            self._set_secret(
                "radius_jks_base64",
                encode_text(fr.read(), self.ctx["secret"]["encoded_salt"]))

        basedir, fn = os.path.split("/etc/certs/gluu-radius.keys")
        self._set_secret(
            "gluu_ro_client_base64_jwks",
            encode_template(fn, self.ctx, basedir),
        )
예제 #6
0
    def from_file(self,
                  key: str,
                  src: str,
                  encode: bool = False,
                  binary_mode: bool = False) -> None:
        """Put secret from a file.

        Example:

        .. code-block:: python

            # assuming there is file ``/etc/certs/server.crt`` need to be save
            # as ``server_crt`` secret.
            SecretManager().from_file("server_cert", "/etc/certs/server.crt")

            # assuming there is file ``/etc/certs/server.jks`` need to be save
            # as ``server_jks`` secret.
            SecretManager().from_file(
                "server_jks",
                "/etc/certs/server.jks",
                encode=True,
                binary_mode=True,
            )

        :params key: Key name in secret backend.
        :params src: Absolute path to file to read the secret from.
        :params encode: Encode the content of the file.
        :params binary_mode: Read the file as binary.
        """
        mode = "r"
        if binary_mode:
            mode = "rb"
            encode = True

        with open(src, mode) as f:
            try:
                value = f.read()
            except UnicodeDecodeError:
                raise ValueError(
                    f"Looks like you're trying to read binary file {src}")

        if encode:
            salt = self.adapter.get("encoded_salt")
            value = encode_text(value, salt).decode()
        self.adapter.set(key, value)
예제 #7
0
def get_couchbase_password(manager, plaintext: bool = True) -> str:
    """Get Couchbase user's password from file (default to
    ``/etc/gluu/conf/couchbase_password``).

    To change the location, simply pass ``GLUU_COUCHBASE_PASSWORD_FILE`` environment variable.

    :params manager: An instance of :class:`~pygluu.containerlib.manager._Manager`.
    :params plaintext: Whether to return plaintext or encoded password.
    :returns: Plaintext or encoded password.
    """
    password_file = os.environ.get("GLUU_COUCHBASE_PASSWORD_FILE",
                                   "/etc/gluu/conf/couchbase_password")

    with open(password_file) as f:
        password = f.read().strip()
        if not plaintext:
            password = encode_text(
                password, manager.secret.get("encoded_salt")).decode()
        return password
def test_encode_text(text, key, expected):
    from pygluu.containerlib.utils import encode_text
    assert encode_text(text, key) == expected
예제 #9
0
def get_base_ctx(manager):
    passport_oxtrust_config = '''
    "passportUmaClientId":"%(passport_rs_client_id)s",
    "passportUmaClientKeyId":"%(passport_rs_client_cert_alias)s",
    "passportUmaResourceId":"%(passport_resource_id)s",
    "passportUmaScope":"https://%(hostname)s/oxauth/restv1/uma/scopes/passport_access",
    "passportUmaClientKeyStoreFile":"%(passport_rs_client_jks_fn)s",
    "passportUmaClientKeyStorePassword":"******",
''' % {
        "passport_rs_client_id":
        manager.config.get("passport_rs_client_id"),
        "passport_resource_id":
        manager.config.get("passport_resource_id"),
        "hostname":
        manager.config.get("hostname"),
        "pdp_ep":
        manager.config.get("pdp_ep"),
        "passport_rs_client_jks_fn":
        manager.config.get("passport_rs_client_jks_fn"),
        "passport_rs_client_jks_pass_encoded":
        manager.secret.get("passport_rs_client_jks_pass_encoded"),
        "passport_rs_client_cert_alias":
        manager.config.get("passport_rs_client_cert_alias"),
    }

    redis_pw = manager.secret.get("redis_pw") or ""
    redis_pw_encoded = ""

    if redis_pw:
        redis_pw_encoded = encode_text(
            redis_pw,
            manager.secret.get("encoded_salt"),
        )

    ctx = {
        'cache_provider_type':
        GLUU_CACHE_TYPE,
        'redis_url':
        GLUU_REDIS_URL,
        'redis_type':
        GLUU_REDIS_TYPE,
        'pdp_ep':
        PDP_EP,
        'redis_pw':
        redis_pw,
        'redis_pw_encoded':
        redis_pw_encoded,
        "redis_use_ssl":
        "{}".format(as_boolean(GLUU_REDIS_USE_SSL)).lower(),
        "redis_ssl_truststore":
        GLUU_REDIS_SSL_TRUSTSTORE,
        "redis_sentinel_group":
        GLUU_REDIS_SENTINEL_GROUP,
        'memcached_url':
        GLUU_MEMCACHED_URL,
        'ldap_hostname':
        manager.config.get('ldap_init_host', "localhost"),
        'ldaps_port':
        manager.config.get('ldap_init_port', 1636),
        'ldap_binddn':
        manager.config.get('ldap_binddn'),
        'encoded_ox_ldap_pw':
        manager.secret.get('encoded_ox_ldap_pw'),
        'jetty_base':
        manager.config.get('jetty_base'),
        'orgName':
        manager.config.get('orgName'),
        'oxauth_client_id':
        manager.config.get('oxauth_client_id'),
        'oxauthClient_encoded_pw':
        manager.secret.get('oxauthClient_encoded_pw'),
        'hostname':
        manager.config.get('hostname'),
        'idp_client_id':
        manager.config.get('idp_client_id'),
        'idpClient_encoded_pw':
        manager.secret.get('idpClient_encoded_pw'),
        'oxauth_openid_key_base64':
        manager.secret.get('oxauth_openid_key_base64'),
        'passport_rs_client_id':
        manager.config.get('passport_rs_client_id'),
        'passport_rs_client_base64_jwks':
        manager.secret.get('passport_rs_client_base64_jwks'),
        'passport_rp_client_id':
        manager.config.get('passport_rp_client_id'),
        'passport_rp_client_base64_jwks':
        manager.secret.get('passport_rp_client_base64_jwks'),
        "passport_rp_client_jks_fn":
        manager.config.get("passport_rp_client_jks_fn"),
        "passport_rp_client_jks_pass":
        manager.secret.get("passport_rp_client_jks_pass"),
        # "encoded_ldap_pw": manager.secret.get('encoded_ldap_pw'),
        "encoded_oxtrust_admin_password":
        manager.secret.get('encoded_oxtrust_admin_password'),
        'scim_rs_client_id':
        manager.config.get('scim_rs_client_id'),
        'scim_rs_client_base64_jwks':
        manager.secret.get('scim_rs_client_base64_jwks'),
        'scim_rs_client_cert_alias':
        manager.config.get("scim_rs_client_cert_alias"),
        'scim_rp_client_id':
        manager.config.get('scim_rp_client_id'),
        'scim_rp_client_base64_jwks':
        manager.secret.get('scim_rp_client_base64_jwks'),
        'scim_resource_oxid':
        manager.config.get('scim_resource_oxid'),
        'passport_rp_ii_client_id':
        manager.config.get("passport_rp_ii_client_id"),
        'api_rs_client_base64_jwks':
        manager.secret.get("api_rs_client_base64_jwks"),
        'api_rs_client_cert_alias':
        manager.config.get("api_rs_client_cert_alias"),
        'api_rp_client_base64_jwks':
        manager.secret.get("api_rp_client_base64_jwks"),
        'admin_email':
        manager.config.get('admin_email'),
        'shibJksFn':
        manager.config.get('shibJksFn'),
        'shibJksPass':
        manager.secret.get('shibJksPass'),
        'oxTrustConfigGeneration':
        str(as_boolean(GLUU_OXTRUST_CONFIG_GENERATION)).lower(),
        'encoded_shib_jks_pw':
        manager.secret.get('encoded_shib_jks_pw'),
        'scim_rs_client_jks_fn':
        manager.config.get('scim_rs_client_jks_fn'),
        'scim_rs_client_jks_pass_encoded':
        manager.secret.get('scim_rs_client_jks_pass_encoded'),
        'passport_rs_client_jks_fn':
        manager.config.get('passport_rs_client_jks_fn'),
        'passport_rs_client_jks_pass_encoded':
        manager.secret.get('passport_rs_client_jks_pass_encoded'),
        'shibboleth_version':
        manager.config.get('shibboleth_version'),
        'idp3Folder':
        manager.config.get('idp3Folder'),
        'ldap_site_binddn':
        manager.config.get('ldap_site_binddn'),
        'api_rs_client_jks_fn':
        manager.config.get("api_rs_client_jks_fn"),
        'api_rs_client_jks_pass_encoded':
        manager.secret.get("api_rs_client_jks_pass_encoded"),
        "oxtrust_requesting_party_client_id":
        manager.config.get("oxtrust_requesting_party_client_id"),
        "oxtrust_resource_server_client_id":
        manager.config.get("oxtrust_resource_server_client_id"),
        "oxtrust_resource_id":
        manager.config.get("oxtrust_resource_id"),
        "passport_resource_id":
        manager.config.get("passport_resource_id"),
        "passport_oxtrust_config":
        passport_oxtrust_config,
        "gluu_radius_client_id":
        manager.config.get("gluu_radius_client_id"),
        "gluu_ro_encoded_pw":
        manager.secret.get("gluu_ro_encoded_pw"),
        # "super_gluu_ro_session_script": manager.config.get("super_gluu_ro_session_script"),
        # "super_gluu_ro_script": manager.config.get("super_gluu_ro_script"),
        "enableRadiusScripts":
        "false",  # @TODO: enable it?
        "gluu_ro_client_base64_jwks":
        manager.secret.get("gluu_ro_client_base64_jwks"),
        "gluuPassportEnabled":
        str(as_boolean(GLUU_PASSPORT_ENABLED)).lower(),
        "gluuRadiusEnabled":
        str(as_boolean(GLUU_RADIUS_ENABLED)).lower(),
        "gluuSamlEnabled":
        str(as_boolean(GLUU_SAML_ENABLED)).lower(),
        "gluuScimEnabled":
        str(as_boolean(GLUU_SCIM_ENABLED)).lower(),
        "pairwiseCalculationKey":
        manager.secret.get("pairwiseCalculationKey"),
        "pairwiseCalculationSalt":
        manager.secret.get("pairwiseCalculationSalt"),
        "default_openid_jks_dn_name":
        manager.config.get("default_openid_jks_dn_name"),
        "oxauth_openid_jks_fn":
        manager.config.get("oxauth_openid_jks_fn"),
        "oxauth_openid_jks_pass":
        manager.secret.get("oxauth_openid_jks_pass"),
        "oxauth_legacyIdTokenClaims":
        manager.config.get("oxauth_legacyIdTokenClaims"),
        "passportSpTLSCert":
        manager.config.get("passportSpTLSCert"),
        "passportSpTLSKey":
        manager.config.get("passportSpTLSKey"),
        "oxauth_openidScopeBackwardCompatibility":
        manager.config.get("oxauth_openidScopeBackwardCompatibility"),
        "fido2ConfigFolder":
        manager.config.get("fido2ConfigFolder"),
        "admin_inum":
        manager.config.get("admin_inum"),
        "enable_oxtrust_api_access_policy":
        str(as_boolean(GLUU_OXTRUST_API_ENABLED)).lower(),
        "oxtrust_api_test_mode":
        str(as_boolean(GLUU_OXTRUST_API_TEST_MODE)).lower(),
        "api_test_client_id":
        manager.config.get("api_test_client_id"),
        "encoded_api_test_client_secret":
        encode_text(
            manager.secret.get("api_test_client_secret"),
            manager.secret.get("encoded_salt"),
        ),
        "enable_scim_access_policy":
        str(
            as_boolean(GLUU_SCIM_ENABLED)
            or as_boolean(GLUU_PASSPORT_ENABLED)).lower(),
        "scimTestMode":
        str(as_boolean(GLUU_SCIM_TEST_MODE)).lower(),
        "scim_test_client_id":
        manager.config.get("scim_test_client_id"),
        "encoded_scim_test_client_secret":
        encode_text(
            manager.secret.get("scim_test_client_secret"),
            manager.secret.get("encoded_salt"),
        ),
        "casa_enable_script":
        str(as_boolean(GLUU_CASA_ENABLED)).lower(),
    }
    return ctx
    def oxshibboleth_ctx(self):
        self._set_config("idp_client_id", "1101.{}".format(uuid.uuid4()))
        self._set_secret(
            "idpClient_encoded_pw",
            encode_text(get_random_chars(),
                        self.ctx["secret"]["encoded_salt"]),
        )
        self._set_config("shibJksFn", "/etc/certs/shibIDP.jks")
        self._set_secret("shibJksPass", get_random_chars())
        self._set_secret(
            "encoded_shib_jks_pw",
            encode_text(self.ctx["secret"]["shibJksPass"],
                        self.ctx["secret"]["encoded_salt"]))

        generate_ssl_certkey(
            "shibIDP",
            self.ctx["secret"]["shibJksPass"],
            self.ctx["config"]["admin_email"],
            self.ctx["config"]["hostname"],
            self.ctx["config"]["orgName"],
            self.ctx["config"]["country_code"],
            self.ctx["config"]["state"],
            self.ctx["config"]["city"],
        )

        generate_keystore("shibIDP", self.ctx["config"]["hostname"],
                          self.ctx["secret"]["shibJksPass"])

        with open("/etc/certs/shibIDP.crt") as f:
            self._set_secret(
                "shibIDP_cert",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))

        with open("/etc/certs/shibIDP.key") as f:
            self._set_secret(
                "shibIDP_key",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))

        with open(self.ctx["config"]["shibJksFn"], "rb") as f:
            self._set_secret(
                "shibIDP_jks_base64",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))

        self._set_config("shibboleth_version", "v3")
        self._set_config("idp3Folder", "/opt/shibboleth-idp")

        idp3_signing_cert = "/etc/certs/idp-signing.crt"
        idp3_signing_key = "/etc/certs/idp-signing.key"

        generate_ssl_certkey(
            "idp-signing",
            self.ctx["secret"]["shibJksPass"],
            self.ctx["config"]["admin_email"],
            self.ctx["config"]["hostname"],
            self.ctx["config"]["orgName"],
            self.ctx["config"]["country_code"],
            self.ctx["config"]["state"],
            self.ctx["config"]["city"],
        )

        with open(idp3_signing_cert) as f:
            self._set_secret("idp3SigningCertificateText", f.read())

        with open(idp3_signing_key) as f:
            self._set_secret("idp3SigningKeyText", f.read())

        idp3_encryption_cert = "/etc/certs/idp-encryption.crt"
        idp3_encryption_key = "/etc/certs/idp-encryption.key"

        generate_ssl_certkey(
            "idp-encryption",
            self.ctx["secret"]["shibJksPass"],
            self.ctx["config"]["admin_email"],
            self.ctx["config"]["hostname"],
            self.ctx["config"]["orgName"],
            self.ctx["config"]["country_code"],
            self.ctx["config"]["state"],
            self.ctx["config"]["city"],
        )

        with open(idp3_encryption_cert) as f:
            self._set_secret("idp3EncryptionCertificateText", f.read())

        with open(idp3_encryption_key) as f:
            self._set_secret("idp3EncryptionKeyText", f.read())

        _, err, code = gen_idp3_key(self.ctx["secret"]["shibJksPass"])
        if code != 0:
            logger.warninging(
                f"Unable to generate Shibboleth sealer; reason={err}")
            raise click.Abort()

        with open("/etc/certs/sealer.jks", "rb") as f:
            self._set_secret(
                "sealer_jks_base64",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))

        with open("/etc/certs/sealer.kver") as f:
            self._set_secret(
                "sealer_kver_base64",
                encode_text(f.read(), self.ctx["secret"]["encoded_salt"]))
    def ldap_ctx(self):
        # self._set_secret("encoded_ldap_pw", ldap_encode(self.params["admin_pw"]))
        self._set_secret(
            "encoded_ox_ldap_pw",
            encode_text(self.params["ldap_pw"],
                        self.ctx["secret"]["encoded_salt"]),
        )
        self._set_config("ldap_init_host", "localhost")
        self._set_config("ldap_init_port", 1636)
        self._set_config("ldap_port", 1389)
        self._set_config("ldaps_port", 1636)
        self._set_config("ldap_binddn", "cn=directory manager")
        self._set_config("ldap_site_binddn", "cn=directory manager")
        self._set_secret("ldap_truststore_pass", get_random_chars())
        self._set_config("ldapTrustStoreFn", "/etc/certs/opendj.pkcs12")

        generate_ssl_certkey(
            "opendj",
            self.ctx["secret"]["ldap_truststore_pass"],
            self.ctx["config"]["admin_email"],
            self.ctx["config"]["hostname"],
            self.ctx["config"]["orgName"],
            self.ctx["config"]["country_code"],
            self.ctx["config"]["state"],
            self.ctx["config"]["city"],
        )
        with open("/etc/certs/opendj.pem", "w") as fw:
            with open("/etc/certs/opendj.crt") as fr:
                ldap_ssl_cert = fr.read()
                self._set_secret(
                    "ldap_ssl_cert",
                    encode_text(ldap_ssl_cert,
                                self.ctx["secret"]["encoded_salt"]),
                )

            with open("/etc/certs/opendj.key") as fr:
                ldap_ssl_key = fr.read()
                self._set_secret(
                    "ldap_ssl_key",
                    encode_text(ldap_ssl_key,
                                self.ctx["secret"]["encoded_salt"]),
                )

            ldap_ssl_cacert = "".join([ldap_ssl_cert, ldap_ssl_key])
            fw.write(ldap_ssl_cacert)
            self._set_secret(
                "ldap_ssl_cacert",
                encode_text(ldap_ssl_cacert,
                            self.ctx["secret"]["encoded_salt"]),
            )

        generate_pkcs12(
            "opendj",
            self.ctx["secret"]["ldap_truststore_pass"],
            self.ctx["config"]["hostname"],
        )
        with open(self.ctx["config"]["ldapTrustStoreFn"], "rb") as fr:
            self._set_secret(
                "ldap_pkcs12_base64",
                encode_text(fr.read(), self.ctx["secret"]["encoded_salt"]),
            )

        self._set_secret(
            "encoded_ldapTrustStorePass",
            encode_text(self.ctx["secret"]["ldap_truststore_pass"],
                        self.ctx["secret"]["encoded_salt"]),
        )
def encode_jks(jks="/etc/certs/oxauth-keys.jks"):
    encoded_jks = ""
    with open(jks, "rb") as fd:
        encoded_jks = encode_text(fd.read(),
                                  manager.secret.get("encoded_salt"))
    return encoded_jks
예제 #13
0
def render_couchbase_properties(manager, src: str, dest: str) -> None:
    """Render file contains properties to connect to Couchbase server,
    i.e. ``/etc/gluu/conf/gluu-couchbase.properties``.

    :params manager: An instance of :class:`~pygluu.containerlib.manager._Manager`.
    :params src: Absolute path to the template.
    :params dest: Absolute path where generated file is located.
    """
    persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "couchbase")
    ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING", "default")
    hostname = os.environ.get("GLUU_COUCHBASE_URL", "localhost")
    bucket_prefix = os.environ.get("GLUU_COUCHBASE_BUCKET_PREFIX", "gluu")

    _couchbase_mappings = get_couchbase_mappings(persistence_type,
                                                 ldap_mapping)
    couchbase_buckets = []
    couchbase_mappings = []

    for _, mapping in _couchbase_mappings.items():
        couchbase_buckets.append(mapping["bucket"])

        if not mapping["mapping"]:
            continue

        couchbase_mappings.append(
            f"bucket.{mapping['bucket']}.mapping: {mapping['mapping']}")

    # always have  _default_ bucket
    if bucket_prefix not in couchbase_buckets:
        couchbase_buckets.insert(0, bucket_prefix)

    with open(src) as fr:
        txt = fr.read()

        with open(dest, "w") as fw:
            rendered_txt = txt % {
                "hostname":
                hostname,
                "couchbase_server_user":
                get_couchbase_user(manager),
                "encoded_couchbase_server_pw":
                get_encoded_couchbase_password(manager),
                "couchbase_buckets":
                ", ".join(couchbase_buckets),
                "default_bucket":
                bucket_prefix,
                "couchbase_mappings":
                "\n".join(couchbase_mappings),
                "encryption_method":
                "SSHA-256",
                "ssl_enabled":
                str(
                    as_boolean(
                        os.environ.get("GLUU_COUCHBASE_TRUSTSTORE_ENABLE",
                                       True))).lower(),
                "couchbaseTrustStoreFn":
                manager.config.get("couchbaseTrustStoreFn"),
                "encoded_couchbaseTrustStorePass":
                encode_text(
                    GLUU_COUCHBASE_TRUSTSTORE_PASSWORD,
                    manager.secret.get("encoded_salt"),
                ).decode(),
                "couchbase_conn_timeout":
                get_couchbase_conn_timeout(),
                "couchbase_conn_max_wait":
                get_couchbase_conn_max_wait(),
                "couchbase_scan_consistency":
                get_couchbase_scan_consistency(),
            }
            fw.write(rendered_txt)