Ejemplo n.º 1
0
def render_sql_properties(manager, src: str, dest: str) -> None:
    """Render file contains properties to connect to SQL database server.

    :params manager: An instance of :class:`~jans.pycloudlib.manager._Manager`.
    :params src: Absolute path to the template.
    :params dest: Absolute path where generated file is located.
    """

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

    with open(dest, "w") as f:
        rendered_txt = txt % {
            "rdbm_db":
            os.environ.get("CN_SQL_DB_NAME", "jans"),
            "rdbm_type":
            os.environ.get("CN_SQL_DB_DIALECT", "mysql"),
            "rdbm_host":
            os.environ.get("CN_SQL_DB_HOST", "localhost"),
            "rdbm_port":
            os.environ.get("CN_SQL_DB_PORT", 3306),
            "rdbm_user":
            os.environ.get("CN_SQL_DB_USER", "jans"),
            "rdbm_password_enc":
            encode_text(
                get_sql_password(manager),
                manager.secret.get("encoded_salt"),
            ).decode(),
            "server_time_zone":
            os.environ.get("CN_SQL_DB_TIMEZONE", "UTC"),
        }
        f.write(rendered_txt)
Ejemplo n.º 2
0
        def auth_server_client():
            if not self.manager.config.get("admin_ui_client_id"):
                self.manager.config.set("admin_ui_client_id",
                                        f"1901.{uuid4()}")

            client_pw = self.manager.secret.get("admin_ui_client_pw")
            if not client_pw:
                client_pw = get_random_chars()
                self.manager.secret.set("admin_ui_client_pw", client_pw)

            if not self.manager.secret.get("admin_ui_client_encoded_pw"):
                self.manager.secret.set(
                    "admin_ui_client_encoded_pw",
                    encode_text(client_pw,
                                self.manager.secret.get("encoded_salt")),
                )
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def merge_casa_ctx(manager, ctx):
    # Casa client
    ctx["casa_client_id"] = manager.config.get("casa_client_id")
    if not ctx["casa_client_id"]:
        ctx["casa_client_id"] = f"1902.{uuid4()}"
        manager.config.set("casa_client_id", ctx["casa_client_id"])

    ctx["casa_client_pw"] = manager.secret.get("casa_client_pw")
    if not ctx["casa_client_pw"]:
        ctx["casa_client_pw"] = get_random_chars()
        manager.secret.set("casa_client_pw", ctx["casa_client_pw"])

    ctx["casa_client_encoded_pw"] = manager.secret.get(
        "casa_client_encoded_pw")
    if not ctx["casa_client_encoded_pw"]:
        ctx["casa_client_encoded_pw"] = encode_text(
            ctx["casa_client_pw"],
            manager.secret.get("encoded_salt"),
        ).decode()
        manager.secret.set("casa_client_encoded_pw",
                           ctx["casa_client_encoded_pw"])

    return ctx
Ejemplo n.º 5
0
def get_base_ctx(manager):
    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"),
        ).decode()

    doc_store_type = os.environ.get("CN_DOCUMENT_STORE_TYPE", "LOCAL")
    jca_user, jca_pw = get_jackrabbit_creds()

    jca_pw_encoded = encode_text(
        jca_pw,
        manager.secret.get("encoded_salt"),
    ).decode()

    cache_type = os.environ.get("CN_CACHE_TYPE", "NATIVE_PERSISTENCE")
    redis_url = os.environ.get('CN_REDIS_URL', 'localhost:6379')
    redis_type = os.environ.get('CN_REDIS_TYPE', 'STANDALONE')
    redis_use_ssl = os.environ.get("CN_REDIS_USE_SSL", False)
    redis_ssl_truststore = os.environ.get("CN_REDIS_SSL_TRUSTSTORE", "")
    redis_sentinel_group = os.environ.get("CN_REDIS_SENTINEL_GROUP", "")
    memcached_url = os.environ.get('CN_MEMCACHED_URL', 'localhost:11211')
    oxtrust_config_generation = os.environ.get("CN_OXTRUST_CONFIG_GENERATION",
                                               True)
    passport_enabled = os.environ.get("CN_PASSPORT_ENABLED", False)
    radius_enabled = os.environ.get("CN_RADIUS_ENABLED", False)
    casa_enabled = os.environ.get("CN_CASA_ENABLED", False)
    saml_enabled = os.environ.get("CN_SAML_ENABLED", False)
    scim_enabled = os.environ.get("CN_SCIM_ENABLED", False)

    ctx = {
        'cache_provider_type':
        cache_type,
        'redis_url':
        redis_url,
        'redis_type':
        redis_type,
        'redis_pw':
        redis_pw,
        'redis_pw_encoded':
        redis_pw_encoded,
        "redis_use_ssl":
        "{}".format(as_boolean(redis_use_ssl)).lower(),
        "redis_ssl_truststore":
        redis_ssl_truststore,
        "redis_sentinel_group":
        redis_sentinel_group,
        'memcached_url':
        memcached_url,
        "document_store_type":
        doc_store_type,
        "jca_server_url":
        get_jackrabbit_rmi_url(),
        "jca_username":
        jca_user,
        "jca_pw":
        jca_pw,
        "jca_pw_encoded":
        jca_pw_encoded,
        'ldap_hostname':
        manager.config.get('ldap_init_host'),
        'ldaps_port':
        manager.config.get('ldap_init_port'),
        'ldap_binddn':
        manager.config.get('ldap_binddn'),
        "ldap_use_ssl":
        str(as_boolean(os.environ.get("CN_LDAP_USE_SSL", True))).lower(),
        'encoded_ox_ldap_pw':
        manager.secret.get('encoded_ox_ldap_pw'),
        'jetty_base':
        manager.config.get('jetty_base'),
        'orgName':
        manager.config.get('orgName'),
        'hostname':
        manager.config.get('hostname'),
        'idp_client_id':
        manager.config.get('idp_client_id'),
        'idpClient_encoded_pw':
        manager.secret.get('idpClient_encoded_pw'),
        'auth_openid_key_base64':
        manager.secret.get('auth_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_rs_client_cert_alias': manager.config.get('passport_rs_client_cert_alias'),
        # '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_admin_password":
        manager.secret.get('encoded_admin_password'),
        # 'passport_rp_ii_client_id': manager.config.get("passport_rp_ii_client_id"),
        'admin_email':
        manager.config.get('admin_email'),
        'shibJksFn':
        manager.config.get('shibJksFn'),
        'shibJksPass':
        manager.secret.get('shibJksPass'),
        'oxTrustConfigGeneration':
        str(as_boolean(oxtrust_config_generation)).lower(),
        'encoded_shib_jks_pw':
        manager.secret.get('encoded_shib_jks_pw'),
        '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'),
        "passport_resource_id":
        manager.config.get("passport_resource_id"),
        "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"),
        "jansPassportEnabled":
        str(as_boolean(passport_enabled)).lower(),
        "jansRadiusEnabled":
        str(as_boolean(radius_enabled)).lower(),
        "jansSamlEnabled":
        str(as_boolean(saml_enabled)).lower(),
        "jansScimEnabled":
        str(as_boolean(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"),
        "auth_openid_jks_pass":
        manager.secret.get("auth_openid_jks_pass"),
        "auth_legacyIdTokenClaims":
        manager.config.get("auth_legacyIdTokenClaims"),
        "passportSpTLSCert":
        manager.config.get("passportSpTLSCert"),
        "passportSpTLSKey":
        manager.config.get("passportSpTLSKey"),
        "auth_openidScopeBackwardCompatibility":
        manager.config.get("auth_openidScopeBackwardCompatibility"),
        "fido2ConfigFolder":
        manager.config.get("fido2ConfigFolder"),
        "admin_inum":
        manager.config.get("admin_inum"),
        "enable_scim_access_policy":
        str(as_boolean(scim_enabled) or as_boolean(passport_enabled)).lower(),
        "scim_client_id":
        manager.config.get("scim_client_id"),
        "scim_client_encoded_pw":
        manager.secret.get("scim_client_encoded_pw"),
        "casa_enable_script":
        str(as_boolean(casa_enabled)).lower(),
        # "oxd_hostname": "localhost",
        # "oxd_port": "8443",
        "jca_client_id":
        manager.config.get("jca_client_id"),
        "jca_client_encoded_pw":
        manager.secret.get("jca_client_encoded_pw"),
    }

    # JWKS URI
    jwks_uri = f"https://{ctx['hostname']}/jans-auth/restv1/jwks"
    auth_openid_jks_fn = manager.config.get("auth_openid_jks_fn")

    ext_jwks_uri = os.environ.get("CN_OB_EXT_SIGNING_JWKS_URI", "")
    if ext_jwks_uri:
        jwks_uri = ext_jwks_uri
        auth_openid_jks_fn = "/etc/certs/ob-ext-signing.jks"

    ctx["jwks_uri"] = jwks_uri
    ctx["auth_openid_jks_fn"] = auth_openid_jks_fn

    # static kid
    ctx["staticKid"] = os.environ.get("CN_OB_STATIC_KID", "")

    # admin-ui plugins
    ctx["admin_ui_client_id"] = manager.config.get("admin_ui_client_id")
    if not ctx["admin_ui_client_id"]:
        ctx["admin_ui_client_id"] = f"1901.{uuid4()}"
        manager.config.set("admin_ui_client_id", ctx["admin_ui_client_id"])

    ctx["admin_ui_client_pw"] = manager.secret.get("admin_ui_client_pw")
    if not ctx["admin_ui_client_pw"]:
        ctx["admin_ui_client_pw"] = get_random_chars()
        manager.secret.set("admin_ui_client_pw", ctx["admin_ui_client_pw"])

    ctx["admin_ui_client_encoded_pw"] = manager.secret.get(
        "admin_ui_client_encoded_pw")
    if not ctx["admin_ui_client_encoded_pw"]:
        ctx["admin_ui_client_encoded_pw"] = encode_text(
            ctx["admin_ui_client_pw"],
            manager.secret.get("encoded_salt")).decode()
        manager.secret.set(
            "admin_ui_client_encoded_pw",
            ctx["admin_ui_client_encoded_pw"],
        )

    # token server client
    ctx["token_server_admin_ui_client_id"] = manager.config.get(
        "token_server_admin_ui_client_id")
    if not ctx["token_server_admin_ui_client_id"]:
        ctx["token_server_admin_ui_client_id"] = f"1901.{uuid4()}"
        manager.config.set("token_server_admin_ui_client_id",
                           ctx["token_server_admin_ui_client_id"])

    ctx["token_server_admin_ui_client_pw"] = manager.secret.get(
        "token_server_admin_ui_client_pw")
    if not ctx["token_server_admin_ui_client_pw"]:
        ctx["token_server_admin_ui_client_pw"] = get_random_chars()
        manager.secret.set("token_server_admin_ui_client_pw",
                           ctx["token_server_admin_ui_client_pw"])

    ctx["token_server_admin_ui_client_encoded_pw"] = manager.secret.get(
        "token_server_admin_ui_client_encoded_pw")
    if not ctx["token_server_admin_ui_client_encoded_pw"]:
        ctx["token_server_admin_ui_client_encoded_pw"] = encode_text(
            ctx["token_server_admin_ui_client_pw"],
            manager.secret.get("encoded_salt"),
        ).decode()
        manager.secret.set(
            "token_server_admin_ui_client_encoded_pw",
            ctx["token_server_admin_ui_client_encoded_pw"],
        )

    # finalize ctx
    return ctx
def encode_jks(manager, jks="/etc/certs/auth-keys.jks"):
    encoded_jks = ""
    with open(jks, "rb") as fd:
        encoded_jks = encode_text(fd.read(),
                                  manager.secret.get("encoded_salt"))
    return encoded_jks
Ejemplo n.º 7
0
def test_encode_text(text, key, expected):
    from jans.pycloudlib.utils import encode_text
    assert encode_text(text, key) == expected
Ejemplo n.º 8
0
def render_couchbase_properties(manager, src: str, dest: str) -> None:
    """Render file contains properties to connect to Couchbase server,
    i.e. ``/etc/jans/conf/jans-couchbase.properties``.

    :params manager: An instance of :class:`~jans.pycloudlib.manager._Manager`.
    :params src: Absolute path to the template.
    :params dest: Absolute path where generated file is located.
    """
    persistence_type = os.environ.get("CN_PERSISTENCE_TYPE", "couchbase")
    ldap_mapping = os.environ.get("CN_PERSISTENCE_LDAP_MAPPING", "default")
    hostname = os.environ.get("CN_COUCHBASE_URL", "localhost")
    bucket_prefix = os.environ.get("CN_COUCHBASE_BUCKET_PREFIX", "jans")

    _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": encode_text(
                    get_couchbase_password(manager),
                    manager.secret.get("encoded_salt"),
                ).decode(),
                "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("CN_COUCHBASE_TRUSTSTORE_ENABLE", True)
                )).lower(),
                "couchbaseTrustStoreFn": manager.config.get("couchbaseTrustStoreFn") or "/etc/certs/couchbase.pkcs12",
                "encoded_couchbaseTrustStorePass": encode_text(
                    CN_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(),
                "couchbase_keepalive_interval": get_couchbase_keepalive_interval(),
                "couchbase_keepalive_timeout": get_couchbase_keepalive_timeout(),
            }
            fw.write(rendered_txt)