Search in sources :

Example 6 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class GenerateCryptoKeysCommand method generateKey.

/**
 * Generate key.
 *
 * @param keySize the key size
 * @return the string
 */
@ShellMethod(key = "generate-key", value = "Generate signing/encryption crypto keys for CAS settings")
public String generateKey(@ShellOption(value = { "key-size", "--key-size" }, defaultValue = "256", help = "Key size") final int keySize) {
    val key = EncodingUtils.generateJsonWebKey(keySize);
    LOGGER.info(key);
    return key;
}
Also used : lombok.val(lombok.val) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 7 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class JasyptEncryptPropertyCommand method encryptValue.

/**
 * Encrypt a value using Jasypt.
 *
 * @param value      the value
 * @param alg        the alg
 * @param provider   the provider
 * @param password   the password
 * @param initVector whether to use initialization vector
 * @param iterations the iterations - defaults to {@value StandardPBEByteEncryptor#DEFAULT_KEY_OBTENTION_ITERATIONS}
 */
@ShellMethod(key = "encrypt-value", value = "Encrypt a CAS property value/setting via Jasypt")
public void encryptValue(@ShellOption(value = { "value", "--value" }, help = "Value to encrypt") final String value, @ShellOption(value = { "alg", "--alg" }, help = "Algorithm to use to encrypt") final String alg, @ShellOption(value = { "provider", "--provider" }, help = "Security provider to use to encrypt") final String provider, @ShellOption(value = { "password", "--password" }, help = "Password (encryption key) to encrypt") final String password, @ShellOption(value = { "initvector", "--initvector", "iv", "--iv" }, help = "Use initialization vector to encrypt", defaultValue = "false") final Boolean initVector, @ShellOption(value = { "iterations", "--iterations" }, defaultValue = ShellOption.NULL, help = "Key obtention iterations to encrypt, default 1000") final String iterations) {
    val cipher = new CasConfigurationJasyptCipherExecutor(this.environment);
    cipher.setAlgorithm(alg);
    cipher.setPassword(password);
    cipher.setProviderName(provider);
    cipher.setKeyObtentionIterations(iterations);
    if (initVector || cipher.isVectorInitializationRequiredFor(alg)) {
        cipher.configureInitializationVector();
    }
    val encrypted = cipher.encryptValue(value);
    LOGGER.info("==== Encrypted Value ====\n[{}]", encrypted);
}
Also used : lombok.val(lombok.val) CasConfigurationJasyptCipherExecutor(org.apereo.cas.configuration.support.CasConfigurationJasyptCipherExecutor) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 8 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class JasyptDecryptPropertyCommand method decryptValue.

/**
 * Decrypt a value using Jasypt.
 *
 * @param value      the value
 * @param alg        the alg
 * @param provider   the provider
 * @param password   the password
 * @param initVector whether to use initialization vector
 * @param iterations the iterations- defaults to {@value StandardPBEByteEncryptor#DEFAULT_KEY_OBTENTION_ITERATIONS}
 */
@ShellMethod(key = "decrypt-value", value = "Decrypt a CAS property value/setting via Jasypt")
public void decryptValue(@ShellOption(value = { "value", "--value" }, help = "Value to decrypt") final String value, @ShellOption(value = { "alg", "--alg" }, help = "Algorithm to use to decrypt") final String alg, @ShellOption(value = { "provider", "--provider" }, help = "Security provider to use to decrypt") final String provider, @ShellOption(value = { "password", "--password" }, help = "Password (encryption key) to decrypt") final String password, @ShellOption(value = { "initvector", "--initvector", "iv", "--iv" }, help = "Use initialization vector to encrypt", defaultValue = "false") final Boolean initVector, @ShellOption(value = { "iterations", "--iterations" }, defaultValue = ShellOption.NULL, help = "Key obtention iterations to decrypt, default 1000") final String iterations) {
    val cipher = new CasConfigurationJasyptCipherExecutor(this.environment);
    cipher.setAlgorithm(alg);
    cipher.setPassword(password);
    cipher.setProviderName(provider);
    cipher.setKeyObtentionIterations(iterations);
    if (initVector || cipher.isVectorInitializationRequiredFor(alg)) {
        cipher.configureInitializationVector();
    }
    val decrypted = cipher.decryptValue(value);
    LOGGER.info("==== Decrypted Value ====\n[{}]", decrypted);
}
Also used : lombok.val(lombok.val) CasConfigurationJasyptCipherExecutor(org.apereo.cas.configuration.support.CasConfigurationJasyptCipherExecutor) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 9 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class ExportPropertiesCommand method exportProperties.

/**
 * Export properties.
 *
 * @param dir the directory for the configuration export
 * @throws Exception the exception
 */
@ShellMethod(key = "export-props", value = "Export CAS properties and settings from configuration metadata.")
public void exportProperties(@ShellOption(value = { "dir", "--dir" }, help = "Path to a directory where reference configuration files would be exported.", defaultValue = "./etc/cas/config") final String dir) throws Exception {
    val allProps = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.ALL).build());
    try (val writer = Files.newBufferedWriter(new File(dir, "all-properties.ref").toPath(), Charset.defaultCharset())) {
        allProps.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
        writer.flush();
    }
    val casProps = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.CAS).build());
    try (val writer = Files.newBufferedWriter(new File(dir, "cas-properties.ref").toPath(), Charset.defaultCharset())) {
        casProps.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
        writer.flush();
    }
    val thirdPartyProperties = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.THIRD_PARTY).build());
    try (val writer = Files.newBufferedWriter(new File(dir, "thirdparty-properties.ref").toPath(), Charset.defaultCharset())) {
        thirdPartyProperties.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
        writer.flush();
    }
    LOGGER.info("Exported configuration properties to [{}]", new File(dir).getAbsolutePath());
}
Also used : lombok.val(lombok.val) ShellCommandGroup(org.springframework.shell.standard.ShellCommandGroup) Unchecked(org.jooq.lambda.Unchecked) Files(java.nio.file.Files) WordUtils(org.apache.commons.text.WordUtils) lombok.val(lombok.val) ConfigurationMetadataCatalogQuery(org.apereo.cas.metadata.ConfigurationMetadataCatalogQuery) ShellMethod(org.springframework.shell.standard.ShellMethod) StringUtils(org.apache.commons.lang3.StringUtils) ShellComponent(org.springframework.shell.standard.ShellComponent) ShellOption(org.springframework.shell.standard.ShellOption) File(java.io.File) Slf4j(lombok.extern.slf4j.Slf4j) Charset(java.nio.charset.Charset) Writer(java.io.Writer) CasConfigurationMetadataCatalog(org.apereo.cas.metadata.CasConfigurationMetadataCatalog) CasReferenceProperty(org.apereo.cas.metadata.CasReferenceProperty) File(java.io.File) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 10 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class GenerateSamlIdPMetadataCommand method generate.

/**
 * Generate saml2 idp metadata at the specified location.
 *
 * @param metadataLocation the metadata location
 * @param entityId         the entity id
 * @param serverPrefix     the server prefix
 * @param scope            the scope
 * @param force            force generation of metadata
 * @param subjectAltNames  additional subject alternative names for cert (besides entity id)
 * @throws Exception the exception
 */
@ShellMethod(key = "generate-idp-metadata", value = "Generate SAML2 IdP Metadata")
public void generate(@ShellOption(value = { "metadataLocation", "--metadataLocation" }, help = "Directory location to hold metadata and relevant keys/certificates", defaultValue = "/etc/cas/saml") final String metadataLocation, @ShellOption(value = { "entityId", "--entityId" }, help = "Entity ID to use for the generated metadata", defaultValue = "cas.example.org") final String entityId, @ShellOption(value = { "hostName", "--hostName" }, help = "CAS server prefix to be used at the IdP host name when generating metadata", defaultValue = "https://cas.example.org/cas") final String serverPrefix, @ShellOption(value = { "scope", "--scope" }, help = "Scope to use when generating metadata", defaultValue = "example.org") final String scope, @ShellOption(value = { "force", "--force" }, help = "Force metadata generation (XML only, not certs), overwriting anything at the specified location") final boolean force, @ShellOption(value = { "subjectAltNames", "--subjectAltNames" }, help = "Comma separated list of other subject alternative names for the certificate (besides entityId)", defaultValue = StringUtils.EMPTY) final String subjectAltNames) throws Exception {
    val locator = new FileSystemSamlIdPMetadataLocator(new File(metadataLocation), Caffeine.newBuilder().initialCapacity(1).maximumSize(1).build());
    val writer = new DefaultSamlIdPCertificateAndKeyWriter();
    writer.setHostname(entityId);
    if (StringUtils.isNotBlank(subjectAltNames)) {
        writer.setUriSubjectAltNames(Arrays.asList(StringUtils.split(subjectAltNames, ",")));
    }
    val generateMetadata = FunctionUtils.doIf(locator.exists(Optional.empty()), () -> Boolean.TRUE, () -> {
        LOGGER.warn("Metadata artifacts are available at the specified location [{}]", metadataLocation);
        return force;
    }).get();
    if (generateMetadata) {
        val props = new CasConfigurationProperties();
        props.getAuthn().getSamlIdp().getCore().setEntityId(entityId);
        props.getServer().setScope(scope);
        props.getServer().setPrefix(serverPrefix);
        val context = SamlIdPMetadataGeneratorConfigurationContext.builder().samlIdPMetadataLocator(locator).samlIdPCertificateAndKeyWriter(writer).applicationContext(applicationContext).casProperties(props).metadataCipherExecutor(CipherExecutor.noOpOfStringToString()).openSamlConfigBean(openSamlConfigBean).velocityEngine(velocityEngineFactoryBean).build();
        val generator = new FileSystemSamlIdPMetadataGenerator(context);
        generator.initialize();
        generator.generate(Optional.empty());
        LOGGER.info("Generated metadata is available at [{}]", locator.resolveMetadata(Optional.empty()));
    } else {
        LOGGER.info("No metadata was generated; it might already exist at the specified path");
    }
}
Also used : lombok.val(lombok.val) FileSystemSamlIdPMetadataGenerator(org.apereo.cas.support.saml.idp.metadata.generator.FileSystemSamlIdPMetadataGenerator) DefaultSamlIdPCertificateAndKeyWriter(org.apereo.cas.support.saml.idp.metadata.writer.DefaultSamlIdPCertificateAndKeyWriter) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) FileSystemSamlIdPMetadataLocator(org.apereo.cas.support.saml.idp.metadata.locator.FileSystemSamlIdPMetadataLocator) File(java.io.File) ShellMethod(org.springframework.shell.standard.ShellMethod)

Aggregations

lombok.val (lombok.val)18 ShellMethod (org.springframework.shell.standard.ShellMethod)18 File (java.io.File)7 CasConfigurationJasyptCipherExecutor (org.apereo.cas.configuration.support.CasConfigurationJasyptCipherExecutor)3 SneakyThrows (lombok.SneakyThrows)2 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 Writer (java.io.Writer)1 HttpURLConnection (java.net.HttpURLConnection)1 Charset (java.nio.charset.Charset)1 Files (java.nio.file.Files)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Provider (java.security.Provider)1 HashMap (java.util.HashMap)1 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)1 Entity (javax.persistence.Entity)1 MappedSuperclass (javax.persistence.MappedSuperclass)1 Slf4j (lombok.extern.slf4j.Slf4j)1 StringUtils (org.apache.commons.lang3.StringUtils)1